GCC not performing loop invariant code motion

爷,独闯天下 提交于 2021-02-09 07:12:33

问题


I decided to check the result of loop invariant code motion optimization using g++. However, when I compiled the following code with -fmove-loop-invariants and analysed its assembly, I saw that k + 17 calculation is still performed in the loop body.

What could prevent the compiler from optimizing it?

May be the compiler concludes that it is more efficient to recalculate k + 17?

int main()
{
    int k = 0;
    std::cin >> k;

    for (int i = 0; i < 10000; ++i)
    {
        int n = k + 17; // not moved out of the loop
        printf("%d\n", n);
    }

    return 0;
}

Tried g++ -O0 -fmove-loop-invariants, g++ -O3 and g++ -O3 -fmove-loop-invariants using both g++ 4.6.3 and g++ 4.8.3.


回答1:


EDIT: Ignore my previous answer. You can see that the calculation has been folded into a constant. Therefore it is performing the loop invariant optimization.


Because of the as-if rule. Simply put, the compiler is not allowed to make any optimizations that may affect the observable behavior of the program, in this case the printf. You can see what happens if you make n volatile and remove the printf:

for (int i = 0; i < 10000; ++i)
{
    volatile int n = k + 17; // not moved out of the loop
}

// Example assembly output for GCC 4.6.4
// ...
        movl    $10000, %eax
        addl    $17, %edx
.L2:
        subl    $1, %eax
        movl    %edx, 12(%rsp)
// ...


来源:https://stackoverflow.com/questions/35387788/gcc-not-performing-loop-invariant-code-motion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!