[LLVMdev] Is it correct to access non-atomic variables using atomic operations?

Jeffrey Yasskin jyasskin at googlers.com
Fri Aug 3 16:24:52 PDT 2012


On Sat, Aug 4, 2012 at 12:11 AM, Lei Zhao <leizhao833 at gmail.com> wrote:
> Hi Everyone,
>
>   This might be more a C/C++11 question than a LLVM question: I wondering if it is semantically correct to access an ordinary variable via atomic operations, like:
>
> int val;
> void foo(){ atomic_store((atomic_int *)(&val), 42); }
>
>   I tried this simple program on clang+llvm and 42 seems to be correctly stored to val. But, is this just by luck or a right way to go?

Like with nearly all type punning, alias analysis is likely to eat
your program if you do this.

In LLVM itself, atomic operations are simply a different kind of
operation on ordinary addresses. Running an atomic operation and a
non-atomic operation on the same address concurrently, where at least
one of the operations is a write, is a data race, which gives 'undef'
results, but as long as you separate your non-atomic operations from
other operations with happens-before edges, you'll be fine:
http://llvm.org/docs/LangRef.html#memmodel.

I don't think Clang exposes any way to get at the raw LLVM operations
from C++, which I think is probably the right design. Why do you think
you want to access an ordinary variable with atomic operations instead
of just defining atomic variables?

Jeffrey



More information about the llvm-dev mailing list