llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Passing 0 to __atomic_fetch_add generates mfence instead of lock xadd

Open goussepi opened this issue 10 years ago • 5 comments

Bugzilla Link 28498
Version trunk
OS All
CC @efriedma-quic,@pogo59

Extended Description

Using clang 3.9 on trunk at r273567 Target: x86_64-unknown-linux-gnu

When passing a '0' constant to '__atomic_fetch_add', an mfence instruction is generated instead of the usual 'lock xadd' which seems less efficient.


#include <stdint.h>

int64_t * g_ptr;

int foo() { return __atomic_fetch_add(g_ptr, 0, __ATOMIC_RELAXED); }

clang -O3 -S test.c

Generates:

movq %rdi, -8(%rsp) movq g_ptr(%rip), %rax mfence movq (%rax), %rax retq

Using gcc:

movq g_ptr(%rip), %rdx movq %rdi, -8(%rsp) xorl %eax, %eax lock xaddq %rax, (%rdx) ret

goussepi avatar Jul 11 '16 12:07 goussepi

I forgot to mention that the reason for wanting to pass 0 to __atomic_fetch_add is to attempt to create a memory barrier.

For the sake of anyone dealing with your code in the future, please don't do this... if you need a fence, write a fence (or inline assembly if necessary).

AMD optimization guide 11.5.1 seems to imply that use of locked instructions should be used instead of mfence instructions in order to achieve best performances for memory barriers.

Hmm, okay... took a look at the optimization manuals, and that seems reasonable. LLVM actually already knows how to generate a locked instruction as a fence, but doesn't use it for targets with SSE2. Probably easy to change.

efriedma-quic avatar Jul 12 '16 19:07 efriedma-quic

Hi Eli, Thanks for looking into this!

Double-checked, it should be fine; the fence isn't necessary.

I forgot to mention that the reason for wanting to pass 0 to __atomic_fetch_add is to attempt to create a memory barrier.

AMD optimization guide 11.5.1 seems to imply that use of locked instructions should be used instead of mfence instructions in order to achieve best performances for memory barriers.

In this case it would make sense to prefer 'lock xadd' over 'mfence', did I understood your point correctly?

goussepi avatar Jul 12 '16 12:07 goussepi

Double-checked, it should be fine; the fence isn't necessary.

efriedma-quic avatar Jul 11 '16 23:07 efriedma-quic

IIRC mfence is actually more efficient than lock xadd.

Off the top of my head, I think __atomic_fetch_add(g_ptr, 0, __ATOMIC_RELAXED); should be equivalent to __atomic_load(g_ptr, __ATOMIC_RELAXED);, but I'd need to double-check the standard.

efriedma-quic avatar Jul 11 '16 22:07 efriedma-quic

The original testcase gets optimized to a simple load now.

efriedma-quic avatar May 03 '22 21:05 efriedma-quic