Compiler generates bad assembler code for xaddl __asm__ function when -O3 is turned on.
Following code will generate bad assembly: #include <iostream> inline int atomicAddReturn(int i, int volatile* p) { int __i; __i = i; __asm__ __volatile__( "lock;xaddl %0, %1" :"=r"(i) :"m"(*p), "r"(i)); return i + __i; } void f(int value) { std::cout << value << std::endl; } void func(volatile int * p) { for (int i = 0; i < 10; ++i) { f(atomicAddReturn(1, p)); } std::cout << "Value == " << *p << std::endl; } int main() { volatile int value = 0; func(&value); return 0; } It generates wrong assembly near xaddl function: call _ZNSolsEm movl %eax, (%esp) call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_ addl $16, %esp decl %esi js .L44 .L28: movl $1, %edx #APP lock;xaddl %eax, (%ebx) #NO_APP movl _ZSt4cout, %ecx leal 1(%eax), %edx movl -12(%ecx), %eax addl $_ZSt4cout, %eax movl 12(%eax), %eax testb $64, %al jne .L21 testb $8, %al jne .L21 subl $8, %esp pushl %edx pushl $_ZSt4cout call _ZNSolsEl movl %eax, (%esp) call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_ addl $16, %esp decl %esi jns .L28 .L44: As you can see edx is set with value "1" instead of eax. After compilation and execution program prints random data. -- Summary: Compiler generates bad assembler code for xaddl __asm__ function Product: gcc Version: 3.4.5 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ AssignedTo: unassigned at gcc dot gnu dot org ReportedBy: l_heldt at poczta dot onet dot pl http://gcc.gnu.org/bugzilla/show_bug.cgi?id=27836