Representation of 'atomic load' and 'atomic store' in IR.
[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>.  This is a low-level 
143    synchronization primitive. In general, optimizers should treat this like
144    a nothrow call.</p>
145
146 <p>Release is similar to Acquire, but with a barrier of the sort necessary to
147    release a lock.This corresponds to the C++0x/C1x
148    <code>memory_order_release</code>.</p>
149
150 <p>AcquireRelease (<code>acq_rel</code> in IR) provides both an Acquire and a Release barrier.
151    This corresponds to the C++0x/C1x <code>memory_order_acq_rel</code>. In general,
152    optimizers should treat this like a nothrow call.</p>
153
154 <p>SequentiallyConsistent (<code>seq_cst</code> in IR) provides Acquire and/or
155    Release semantics, and in addition guarantees a total ordering exists with
156    all other SequentiallyConsistent operations. This corresponds to the
157    C++0x/C1x <code>memory_order_seq_cst</code>, and Java volatile.  The intent
158    of this ordering level is to provide a programming model which is relatively
159    easy to understand. In general, optimizers should treat this like a
160    nothrow call.</p>
161
162 </div>
163
164 <!-- *********************************************************************** -->
165 <h2>
166   <a name="otherinst">Other atomic instructions</a>
167 </h2>
168 <!-- *********************************************************************** -->
169
170 <div>
171
172 <p><code>cmpxchg</code> and <code>atomicrmw</code> are essentially like an
173    atomic load followed by an atomic store (where the store is conditional for
174    <code>cmpxchg</code>), but no other memory operation operation can happen
175    between the load and store.</p>
176
177 <p>A <code>fence</code> provides Acquire and/or Release ordering which is not
178    part of another operation; it is normally used along with Monotonic memory
179    operations.  A Monotonic load followed by an Acquire fence is roughly
180    equivalent to an Acquire load.</p>
181
182 <p>Frontends generating atomic instructions generally need to be aware of the
183    target to some degree; atomic instructions are guaranteed to be lock-free,
184    and therefore an instruction which is wider than the target natively supports
185    can be impossible to generate.</p>
186
187 </div>
188
189 <!-- *********************************************************************** -->
190 <h2>
191   <a name="iropt">Atomics and IR optimization</a>
192 </h2>
193 <!-- *********************************************************************** -->
194
195 <div>
196
197 <p>Predicates for optimizer writers to query:
198 <ul>
199   <li>isSimple(): A load or store which is not volatile or atomic.  This is
200       what, for example, memcpyopt would check for operations it might
201       transform.
202   <li>isUnordered(): A load or store which is not volatile and at most
203       Unordered. This would be checked, for example, by LICM before hoisting
204       an operation.
205   <li>mayReadFromMemory()/mayWriteToMemory(): Existing predicate, but note
206       that they returns true for any operation which is volatile or at least
207       Monotonic.
208   <li>Alias analysis: Note that AA will return ModRef for anything Acquire or
209       Release, and for the address accessed by any Monotonic operation.
210 </ul>
211
212 <p>There are essentially two components to supporting atomic operations. The
213    first is making sure to query isSimple() or isUnordered() instead
214    of isVolatile() before transforming an operation.  The other piece is
215    making sure that a transform does not end up replacing, for example, an 
216    Unordered operation with a non-atomic operation.  Most of the other 
217    necessary checks automatically fall out from existing predicates and
218    alias analysis queries.</p>
219
220 <p>Some examples of how optimizations interact with various kinds of atomic
221    operations:
222 <ul>
223   <li>memcpyopt: An atomic operation cannot be optimized into part of a
224       memcpy/memset, including unordered loads/stores.  It can pull operations
225       across some atomic operations.
226   <li>LICM: Unordered loads/stores can be moved out of a loop.  It just treats
227       monotonic operations like a read+write to a memory location, and anything
228       stricter than that like a nothrow call.
229   <li>DSE: Unordered stores can be DSE'ed like normal stores.  Monotonic stores
230       can be DSE'ed in some cases, but it's tricky to reason about, and not
231       especially important.
232   <li>Folding a load: Any atomic load from a constant global can be
233       constant-folded, because it cannot be observed.  Similar reasoning allows
234       scalarrepl with atomic loads and stores.
235 </ul>
236
237 </div>
238
239 <!-- *********************************************************************** -->
240 <h2>
241   <a name="codegen">Atomics and Codegen</a>
242 </h2>
243 <!-- *********************************************************************** -->
244
245 <div>
246
247 <p>Atomic operations are represented in the SelectionDAG with
248    <code>ATOMIC_*</code> opcodes.  On architectures which use barrier
249    instructions for all atomic ordering (like ARM), appropriate fences are
250    split out as the DAG is built.</p>
251
252 <p>The MachineMemOperand for all atomic operations is currently marked as
253    volatile; this is not correct in the IR sense of volatile, but CodeGen
254    handles anything marked volatile very conservatively.  This should get
255    fixed at some point.</p>
256
257 <p>The implementation of atomics on LL/SC architectures (like ARM) is currently
258    a bit of a mess; there is a lot of copy-pasted code across targets, and
259    the representation is relatively unsuited to optimization (it would be nice
260    to be able to optimize loops involving cmpxchg etc.).</p>
261
262 <p>On x86, all atomic loads generate a <code>MOV</code>.
263    SequentiallyConsistent stores generate an <code>XCHG</code>, other stores
264    generate a <code>MOV</code>. SequentiallyConsistent fences generate an
265    <code>MFENCE</code>, other fences do not cause any code to be generated.
266    cmpxchg uses the <code>LOCK CMPXCHG</code> instruction.
267    <code>atomicrmw xchg</code> uses <code>XCHG</code>,
268    <code>atomicrmw add</code> and <code>atomicrmw sub</code> use
269    <code>XADD</code>, and all other <code>atomicrmw</code> operations generate
270    a loop with <code>LOCK CMPXCHG</code>.  Depending on the users of the
271    result, some <code>atomicrmw</code> operations can be translated into
272    operations like <code>LOCK AND</code>, but that does not work in
273    general.</p>
274
275 <p>On ARM, MIPS, and many other RISC architectures, Acquire, Release, and
276    SequentiallyConsistent semantics require barrier instructions
277    for every such operation. Loads and stores generate normal instructions.
278    <code>atomicrmw</code> and <code>cmpxchg</code> generate LL/SC loops.</p>
279
280 </div>
281
282 <!-- *********************************************************************** -->
283
284 <hr>
285 <address>
286   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
287   src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
288   <a href="http://validator.w3.org/check/referer"><img
289   src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
290
291   <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
292   Last modified: $Date: 2011-08-09 02:07:00 -0700 (Tue, 09 Aug 2011) $
293 </address>
294
295 </body>
296 </html>