Changes per Jeffrey's comments.
[oota-llvm.git] / docs / Atomics.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2                       "http://www.w3.org/TR/html4/strict.dtd">
3 <html>
4 <head>
5   <title>LLVM Atomic Instructions and Concurrency Guide</title>
6   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
7   <link rel="stylesheet" href="llvm.css" type="text/css">
8 </head>
9 <body>
10
11 <h1>
12   LLVM Atomic Instructions and Concurrency Guide
13 </h1>
14
15 <ol>
16   <li><a href="#introduction">Introduction</a></li>
17   <li><a href="#loadstore">Load and store</a></li>
18   <li><a href="#ordering">Atomic orderings</a></li>
19   <li><a href="#otherinst">Other atomic instructions</a></li>
20   <li><a href="#iropt">Atomics and IR optimization</a></li>
21   <li><a href="#codegen">Atomics and Codegen</a></li>
22 </ol>
23
24 <div class="doc_author">
25   <p>Written by Eli Friedman</p>
26 </div>
27
28 <!-- *********************************************************************** -->
29 <h2>
30   <a name="introduction">Introduction</a>
31 </h2>
32 <!-- *********************************************************************** -->
33
34 <div>
35
36 <p>Historically, LLVM has not had very strong support for concurrency; some
37 minimal intrinsics were provided, and <code>volatile</code> was used in some
38 cases to achieve rough semantics in the presence of concurrency.  However, this
39 is changing; there are now new instructions which are well-defined in the
40 presence of threads and asynchronous signals, and the model for existing
41 instructions has been clarified in the IR.</p>
42
43 <p>The atomic instructions are designed specifically to provide readable IR and
44    optimized code generation for the following:</p>
45 <ul>
46   <li>The new C++0x <code>&lt;atomic&gt;</code> header.</li>
47   <li>Proper semantics for Java-style memory, for both <code>volatile</code> and
48       regular shared variables.</li>
49   <li>gcc-compatible <code>__sync_*</code> builtins.</li>
50   <li>Other scenarios with atomic semantics, including <code>static</code>
51       variables with non-trivial constructors in C++.</li>
52 </ul>
53
54 <p>This document is intended to provide a guide to anyone either writing a
55    frontend for LLVM or working on optimization passes for LLVM with a guide
56    for how to deal with instructions with special semantics in the presence of
57    concurrency.  This is not intended to be a precise guide to the semantics;
58    the details can get extremely complicated and unreadable, and are not
59    usually necessary.</p>
60
61 </div>
62
63 <!-- *********************************************************************** -->
64 <h2>
65   <a name="loadstore">Load and store</a>
66 </h2>
67 <!-- *********************************************************************** -->
68
69 <div>
70
71 <p>The basic <code>'load'</code> and <code>'store'</code> allow a variety of 
72    optimizations, but can have unintuitive results in a concurrent environment.
73    For a frontend writer, the rule is essentially that all memory accessed 
74    with basic loads and stores by multiple threads should be protected by a
75    lock or other synchronization; otherwise, you are likely to run into
76    undefined behavior. (Do not use volatile as a substitute for atomics; it
77    might work on some platforms, but does not provide the necessary guarantees
78    in general.)</p>
79
80 <p>From the optimizer's point of view, the rule is that if there
81    are not any instructions with atomic ordering involved, concurrency does not
82    matter, with one exception: if a variable might be visible to another
83    thread or signal handler, a store cannot be inserted along a path where it
84    might not execute otherwise. Note that speculative loads are allowed;
85    a load which is part of a race returns <code>undef</code>, but is not
86    undefined behavior.</p>
87
88 <p>For cases where simple loads and stores are not sufficient, LLVM provides
89    atomic loads and stores with varying levels of guarantees.</p>
90
91 </div>
92
93 <!-- *********************************************************************** -->
94 <h2>
95   <a name="ordering">Atomic orderings</a>
96 </h2>
97 <!-- *********************************************************************** -->
98
99 <div>
100
101 <p>In order to achieve a balance between performance and necessary guarantees,
102    there are six levels of atomicity. They are listed in order of strength;
103    each level includes all the guarantees of the previous level except for
104    Acquire/Release.</p>
105
106 <p>Unordered is the lowest level of atomicity. It essentially guarantees that
107    races produce somewhat sane results instead of having undefined behavior. 
108    This is intended to match the Java memory model for shared variables. It 
109    cannot be used for synchronization, but is useful for Java and other 
110    "safe" languages which need to guarantee that the generated code never 
111    exhibits undefined behavior.  Note that this guarantee is cheap on common
112    platforms for loads of a native width, but can be expensive or unavailable
113    for wider loads, like a 64-bit load on ARM. (A frontend for a "safe"
114    language would normally split a 64-bit load on ARM into two 32-bit
115    unordered loads.) In terms of the optimizer, this prohibits any
116    transformation that transforms a single load into multiple loads, 
117    transforms a store into multiple stores, narrows a store, or stores a
118    value which would not be stored otherwise.  Some examples of unsafe
119    optimizations are narrowing an assignment into a bitfield, rematerializing
120    a load, and turning loads and stores into a memcpy call. Reordering 
121    unordered operations is safe, though, and optimizers should take 
122    advantage of that because unordered operations are common in
123    languages that need them.</p>
124
125 <p>Monotonic is the weakest level of atomicity that can be used in
126    synchronization primitives, although it does not provide any general
127    synchronization. It essentially guarantees that if you take all the
128    operations affecting a specific address, a consistent ordering exists.
129    This corresponds to the C++0x/C1x <code>memory_order_relaxed</code>; see 
130    those standards for the exact definition.  If you are writing a frontend, do
131    not use the low-level synchronization primitives unless you are compiling
132    a language which requires it or are sure a given pattern is correct. In
133    terms of the optimizer, this can be treated as a read+write on the relevant 
134    memory location (and alias analysis will take advantage of that).  In 
135    addition, it is legal to reorder non-atomic and Unordered loads around 
136    Monotonic loads. CSE/DSE and a few other optimizations are allowed, but
137    Monotonic operations are unlikely to be used in ways which would make
138    those optimizations useful.</p>
139
140 <p>Acquire provides a barrier of the sort necessary to acquire a lock to access
141    other memory with normal loads and stores. This corresponds to the 
142    C++0x/C1x <code>memory_order_acquire</code>. It should also be used for
143    C++0x/C1x <code>memory_order_consume</code>. This is a low-level 
144    synchronization primitive. In general, optimizers should treat this like
145    a nothrow call.</p>
146
147 <p>Release is similar to Acquire, but with a barrier of the sort necessary to
148    release a lock. This corresponds to the C++0x/C1x
149    <code>memory_order_release</code>. In general, optimizers should treat this
150    like a nothrow call.</p>
151
152 <p>AcquireRelease (<code>acq_rel</code> in IR) provides both an Acquire and a Release barrier.
153    This corresponds to the C++0x/C1x <code>memory_order_acq_rel</code>. In general,
154    optimizers should treat this like a nothrow call.</p>
155
156 <p>SequentiallyConsistent (<code>seq_cst</code> in IR) provides Acquire and/or
157    Release semantics, and in addition guarantees a total ordering exists with
158    all other SequentiallyConsistent operations. This corresponds to the
159    C++0x/C1x <code>memory_order_seq_cst</code>, and Java volatile.  The intent
160    of this ordering level is to provide a programming model which is relatively
161    easy to understand. In general, optimizers should treat this like a
162    nothrow call.</p>
163
164 </div>
165
166 <!-- *********************************************************************** -->
167 <h2>
168   <a name="otherinst">Other atomic instructions</a>
169 </h2>
170 <!-- *********************************************************************** -->
171
172 <div>
173
174 <p><code>cmpxchg</code> and <code>atomicrmw</code> are essentially like an
175    atomic load followed by an atomic store (where the store is conditional for
176    <code>cmpxchg</code>), but no other memory operation can happen between
177    the load and store.  Note that our cmpxchg does not have quite as many
178    options for making cmpxchg weaker as the C++0x version.</p>
179
180 <p>A <code>fence</code> provides Acquire and/or Release ordering which is not
181    part of another operation; it is normally used along with Monotonic memory
182    operations.  A Monotonic load followed by an Acquire fence is roughly
183    equivalent to an Acquire load.</p>
184
185 <p>Frontends generating atomic instructions generally need to be aware of the
186    target to some degree; atomic instructions are guaranteed to be lock-free,
187    and therefore an instruction which is wider than the target natively supports
188    can be impossible to generate.</p>
189
190 </div>
191
192 <!-- *********************************************************************** -->
193 <h2>
194   <a name="iropt">Atomics and IR optimization</a>
195 </h2>
196 <!-- *********************************************************************** -->
197
198 <div>
199
200 <p>Predicates for optimizer writers to query:
201 <ul>
202   <li>isSimple(): A load or store which is not volatile or atomic.  This is
203       what, for example, memcpyopt would check for operations it might
204       transform.
205   <li>isUnordered(): A load or store which is not volatile and at most
206       Unordered. This would be checked, for example, by LICM before hoisting
207       an operation.
208   <li>mayReadFromMemory()/mayWriteToMemory(): Existing predicate, but note
209       that they return true for any operation which is volatile or at least
210       Monotonic.
211   <li>Alias analysis: Note that AA will return ModRef for anything Acquire or
212       Release, and for the address accessed by any Monotonic operation.
213 </ul>
214
215 <p>There are essentially two components to supporting atomic operations. The
216    first is making sure to query isSimple() or isUnordered() instead
217    of isVolatile() before transforming an operation.  The other piece is
218    making sure that a transform does not end up replacing, for example, an 
219    Unordered operation with a non-atomic operation.  Most of the other 
220    necessary checks automatically fall out from existing predicates and
221    alias analysis queries.</p>
222
223 <p>Some examples of how optimizations interact with various kinds of atomic
224    operations:
225 <ul>
226   <li>memcpyopt: An atomic operation cannot be optimized into part of a
227       memcpy/memset, including unordered loads/stores.  It can pull operations
228       across some atomic operations.
229   <li>LICM: Unordered loads/stores can be moved out of a loop.  It just treats
230       monotonic operations like a read+write to a memory location, and anything
231       stricter than that like a nothrow call.
232   <li>DSE: Unordered stores can be DSE'ed like normal stores.  Monotonic stores
233       can be DSE'ed in some cases, but it's tricky to reason about, and not
234       especially important.
235   <li>Folding a load: Any atomic load from a constant global can be
236       constant-folded, because it cannot be observed.  Similar reasoning allows
237       scalarrepl with atomic loads and stores.
238 </ul>
239
240 </div>
241
242 <!-- *********************************************************************** -->
243 <h2>
244   <a name="codegen">Atomics and Codegen</a>
245 </h2>
246 <!-- *********************************************************************** -->
247
248 <div>
249
250 <p>Atomic operations are represented in the SelectionDAG with
251    <code>ATOMIC_*</code> opcodes.  On architectures which use barrier
252    instructions for all atomic ordering (like ARM), appropriate fences are
253    split out as the DAG is built.</p>
254
255 <p>The MachineMemOperand for all atomic operations is currently marked as
256    volatile; this is not correct in the IR sense of volatile, but CodeGen
257    handles anything marked volatile very conservatively.  This should get
258    fixed at some point.</p>
259
260 <p>The implementation of atomics on LL/SC architectures (like ARM) is currently
261    a bit of a mess; there is a lot of copy-pasted code across targets, and
262    the representation is relatively unsuited to optimization (it would be nice
263    to be able to optimize loops involving cmpxchg etc.).</p>
264
265 <p>On x86, all atomic loads generate a <code>MOV</code>.
266    SequentiallyConsistent stores generate an <code>XCHG</code>, other stores
267    generate a <code>MOV</code>. SequentiallyConsistent fences generate an
268    <code>MFENCE</code>, other fences do not cause any code to be generated.
269    cmpxchg uses the <code>LOCK CMPXCHG</code> instruction.
270    <code>atomicrmw xchg</code> uses <code>XCHG</code>,
271    <code>atomicrmw add</code> and <code>atomicrmw sub</code> use
272    <code>XADD</code>, and all other <code>atomicrmw</code> operations generate
273    a loop with <code>LOCK CMPXCHG</code>.  Depending on the users of the
274    result, some <code>atomicrmw</code> operations can be translated into
275    operations like <code>LOCK AND</code>, but that does not work in
276    general.</p>
277
278 <p>On ARM, MIPS, and many other RISC architectures, Acquire, Release, and
279    SequentiallyConsistent semantics require barrier instructions
280    for every such operation. Loads and stores generate normal instructions.
281    <code>atomicrmw</code> and <code>cmpxchg</code> generate LL/SC loops.</p>
282
283 </div>
284
285 <!-- *********************************************************************** -->
286
287 <hr>
288 <address>
289   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
290   src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
291   <a href="http://validator.w3.org/check/referer"><img
292   src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
293
294   <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
295   Last modified: $Date: 2011-08-09 02:07:00 -0700 (Tue, 09 Aug 2011) $
296 </address>
297
298 </body>
299 </html>