I am trying to understand assembly a little better, so I've been paying attention to the assembly output from CDB when I debug my code. My platform is an Intel Xeon with Windows 7.
The following C++ code:
int main()
{
int a = 30;
int b = 0;
b = ++a;
return 0;
}
produces the following assembly for the line with the increment operator:
b = ++a;
0x13f441023 <+0x0013> mov eax,dword ptr [rsp]
0x13f441026 <+0x0016> inc eax
0x13f441028 <+0x0018> mov dword ptr [rsp],eax //Move eax to some memory address
0x13f44102b <+0x001b> mov eax,dword ptr [rsp] //Move it back to eax?
0x13f44102e <+0x001e> mov dword ptr [rsp+4],eax
My question is, what is the purpose of moving the value in eax to memory, then immediately moving the same value back into eax, as indicated by the comments? Is this for thread safety, or just some artifact of a debug build?
-O0is kind of pointless, at least if you're going to scrutinize its efficiency.movwould ever be useful. On a side note, optimizing with -02 removes the redundant operation.b=++a. It is effectively the same asb=(a+=1);so you computea+1and store that intoaand then copy fromatob. An unoptimized compile is not supposed to notice that the value just stored intoais still in eax, so you don't need to read it back fromawhen copyingatob. An unoptimized compile forgets the register contents after each step.++aand the final 2 do theb = a(whereaalready has the incremented value). Due to no optimization, the compiler didn't eliminate the reload ofeax.