On 2017-08-14 21:39 +0100, Marcel Keller wrote: > Hi, > > I've found that the attached code behaves differently when compiling > with or without -O in GCC 7.2. > > $ gcc asm.cpp ; ./a.out > 1 > $ gcc -O asm.cpp ; ./a.out > 0 > > Looking at the compiled program in the second case, GCC seems to omit > the inline assembly: > > 00000000004004e7 <f(long*)>: > 4004e7: f3 c3 repz retq > > My understanding is that the "memory" cobbler should tell GCC to assume > that the assembly changes the memory (which it does). Am I missing > something here? <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Extended-Asm.html#Volatile>: GCC’s optimizers sometimes discard asm statements if they determine there is no need for the output variables. Also, the optimizers may move code out of loops if they believe that the code will always return the same result (i.e. none of its input values change between calls). Using the volatile qualifier disables these optimizations. asm statements that have no output operands, including asm goto statements, are implicitly volatile. In your code: asm( "addl $1,(%1)" : "=r"(res) : "rdi"(z) : "memory" ); "res" is an unused output variable. So GCC just optimize it away. You should use "asm volatile". > Best regards, > Marcel > -- Xi Ruoyao <ryxi@xxxxxxxxxxxxxxxxx> School of Aerospace Science and Technology, Xidian University