I have a simple C++ code snippet as shown below:
int A;
int B;
void foo() {
A = B + 1;
// asm volatile("" ::: "memory");
B = 0;
}
When I compile this code, the generated assembly code is reordered as follows:
foo():
mov eax, DWORD PTR B[rip]
mov DWORD PTR B[rip], 0
add eax, 1
mov DWORD PTR A[rip], eax
ret
B:
.zero 4
A:
.zero 4
However, when I add a memory fence (commented line in the C++ code), the instructions are not reordered. My understanding is that adding a volatile
qualifier to a variable should also prevent instruction reordering. So, I modified the code to add volatile
to variable B:
int A;
volatile int B;
void foo() {
A = B + 1;
B = 0;
}
To my surprise, the generated assembly code still shows reordered instructions. Can someone explain why the volatile
qualifier did not prevent instruction reordering in this case?
Code is available in godbolt