GCC会优化内联访问器吗?

问题描述 投票:1回答:2

假设我有这堂课

class Point 
{
  inline float x() const { return v[0]; }
  inline float y() const { return v[1]; }
  inline float z() const { return v[2]; }

  float v[3];
};

我愿意:

Point myPoint;
myPoint[0] = 5;

// unrelated code goes here

float myVal = myPoint.x() + 5;

-O2-O3上的GCC将仅获得x()来优化对v[0]的所有调用吗? IE:

float myVal = myPoint.v[0] + 5;

或者有没有理由为什么这不可能?

更新:应该提一下,我的确意识到inline对编译器的建议比其他任何建议都重要,但无论如何都在想。

还有一个问题,对此类进行模板化会对可以完成的优化有影响吗?

c++ c++11 gcc optimization accessor
2个回答
0
投票

您可以在这里观察到差异:https://godbolt.org/

假设您有此代码(您无法编译:缺少;,并且Point没有[]):

struct Point 
{
  inline float x() const { return v[0]; }
  inline float y() const { return v[1]; }
  inline float z() const { return v[2]; }

  float v[3];
};

int main() {
    Point myPoint;
    myPoint.v[0] = 5;

    float myVal = myPoint.x() + 5;
    return myVal;
}

然后gcc 9.2 emits

Point::x() const:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     rax, QWORD PTR [rbp-8]
        movss   xmm0, DWORD PTR [rax]
        pop     rbp
        ret
main:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        movss   xmm0, DWORD PTR .LC0[rip]
        movss   DWORD PTR [rbp-16], xmm0
        lea     rax, [rbp-16]
        mov     rdi, rax
        call    Point::x() const
        movss   xmm1, DWORD PTR .LC0[rip]
        addss   xmm0, xmm1
        movss   DWORD PTR [rbp-4], xmm0
        movss   xmm0, DWORD PTR [rbp-4]
        cvttss2si       eax, xmm0
        leave
        ret
.LC0:
        .long   1084227584

我不擅长阅读汇编程序,但我将以上内容与the output with -O3进行比较就足以令人信服:

-O3

0
投票

它可能是内联的,也可能不是。那里没有保证。但是,如果希望始终将其内联,请使用main: mov eax, 10 ret 属性。参见文档[[gnu::always_inline]]

© www.soinside.com 2019 - 2024. All rights reserved.