Is the compiler allowed to optimize this (according to the C++17 standard):
int fn() {
volatile int x = 0;
return x;
}
to this?
int fn() {
return 0;
}
If yes, why? If not, why not?
Here's some thinking about this subject: current compilers compile fn()
as a local variable put on the stack, then return it. For example, on x86-64, gcc creates this:
mov DWORD PTR [rsp-0x4],0x0 // this is x
mov eax,DWORD PTR [rsp-0x4] // eax is the return register
ret
Now, as far as I know the standard doesn't say that a local volatile variable should be put on the stack. So, this version would be equally good:
mov edx,0x0 // this is x
mov eax,edx // eax is the return
ret
Here, edx
stores x
. But now, why stop here? As edx
and eax
are both zero, we could just say:
xor eax,eax // eax is the return, and x as well
ret
And we transformed fn()
to the optimized version. Is this transformation valid? If not, which step is invalid?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…