The source code I use in this post, is also available here: https://gcc.godbolt.org/z/dGvxnv
Given this C source code:
int pure_f(int a, int b) __attribute__((pure));
int const_f(int a, int b) __attribute__((const));
int my_f(int a, int b) {
int x = pure_f(a, b);
if (a > 0) {
return x;
}
return a;
}
If this is compiled with gcc with -O3
, I would expect that the evaluation of pure_f(a, b)
is moved into the if
. But it is not done:
my_f(int, int):
push r12
mov r12d, edi
call pure_f(int, int)
test r12d, r12d
cmovg r12d, eax
mov eax, r12d
pop r12
ret
On the other side, if const_f
is called instead of pure_f
, it is moved into the if
:
my_f(int, int):
test edi, edi
jg .L4
mov eax, edi
ret
.L4:
jmp const_f(int, int)
Why isn't this optimization applied for a pure function? From my understanding, this should also be possible and it seems to be beneficial.
-- EDIT --
GCC bug report (see comments): https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97307