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.
int k = 0; std::cin >> k;
and madek
a parameter:main(int k, char **argv)
. Invariant is moved starting from-O1
. The last small question is why invariant is not moved when compiling with-O0 -fmove-loop-invariants
? – LVKlea esi, [rax+17]
within the loop, perhaps as you say this doesn't take any more cycles than just loading rax by itself. clang 3.7 still doesadd esi, 17
within the loop even at-O3
– M.M-O0 -fmove-loop-invariants
does not make sense, as -O0 disables all optimizations (even if you try to enable them with -f flags). – Marc Glisse