-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.html
936 lines (913 loc) · 44.8 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>No sane compiler would optimize atomics</title>
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/league.css">
<!-- Theme used for syntax highlighting of code -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<h1>No Sane Compiler Would Optimize Atomics</h1>
<p>JF Bastien <<a href="https://twitter.com/jfbastien">@jfbastien</a>></p>
</section>
<section>
<strong><code class="c++" style="font-size: 400%">false</code></strong>
<aside class="notes">
<p>Compilers do optimize atomics, memory accesses around atomics, and utilize architecture-specific knowledge. My hobby is to encourage compilers to do more of this, programmers to rely on it, and hardware vendors to give us new atomic toys to optimize with. Oh, and standardize yet more close-to-the-metal concurrency and parallelism tools.</p>
<p>But, you say, surely volatile always means volatile, there’s nothing wrong with my benign races, nothing could even go wrong with non-temporal accesses, and who needs 6 memory orderings anyways‽ I’m glad you asked, let me tell you about my hobby…</p>
</aside>
</section>
<section>
<h1>Disclaimer</h1>
<img src="lock-free.gif" style="zoom:70%; border:none" />
<aside class="notes">Peek under the hood. Prefer higher-level primitives (parallelism TS, mutex, etc).</aside>
</section>
<section>
<h2>When to go lock-free?</h2>
<img src="lock-free.svg" style="border:none" />
<aside class="notes">
From Fedor Pikus' talk earlier this week "The speed of concurrency (is lock-free faster?)".
Note: "does it work" has two "no" branches... That was inadvertent snark!
Also see Hans Boehm's talk "Using weakly ordered C++ atomics correctly".
</aside>
</section>
<section><h1>Quick Review</h1></section>
<section>
<h2>C++11 added</h2>
<ul>
<li class="fragment">A memory model</li>
<li class="fragment">Threads</li>
<li class="fragment">Classes to communicate between threads</li>
</ul>
<p class="fragment">Threads didn't exist before C++11</p>
</section>
<section>
<h1>Sequential Consistency</h1>
<p class="fragment">Naïve model: memory accesses are simply interleaved</p>
<img class="fragment" src="zipper.gif" style="zoom:50%; border:none" />
<p class="fragment">Hardware doesn't work that way</p>
<p class="fragment">Overly restrictive</p>
<aside class="notes">Limits compiler + HW reordering / optimizations; access granularity; want to reason about atomic code regions; fences cost 2 to 200 cycles depending on architecture</aside>
</section>
<section>
<h1>SC-DRF</h1>
<p class="fragment">Data race:</p>
<ul>
<li class="fragment">Two accesses to the same <em>memory location</em> by different threads are <em>not ordered</em></li>
<li class="fragment">At least one of them stores to the memory location</li>
<li class="fragment">At least one of them is not a synchronization action</li>
</ul>
<p class="fragment">Data races are UB</p>
<aside class="notes">You should use address sanitizer</aside>
</section>
<section>
<h1>[intro.multithread]</h1>
<p class="fragment">1.10 Multi-threaded executions and data races</p>
</section>
<section>
<h1>Atomic operations</h1>
<p class="fragment"><strong>Atomic</strong>: indivisible with respect to all other atomic accesses to that object</p>
<aside class="notes">No tearing, no duplication, no elision.</aside>
</section>
<section>
<h1>Memory order</h1>
<ul>
<li><code class="c++">relaxed</code></li>
<li><code class="c++">consume</code></li>
<li><code class="c++">acquire</code></li>
<li><code class="c++">release</code></li>
<li><code class="c++">acq_rel</code></li>
<li><code class="c++">seq_cst</code></li>
</ul>
<aside class="notes">Used as constants passed to atomic operations. You can use a runtime variable, but your life will be sad. Actually a lattice, because cmpxchg, though we may change that in the standard, see http://wg21.link/p0418 when published.</aside>
</section>
<section>
<h1><code class="c++">relaxed</code></h1>
<p class="fragment">racing accesses</p>
<p class="fragment">indivisible</p>
<p class="fragment">enforce cache coherency</p>
<p class="fragment">doesn't guarantee visibility</p>
<aside class="notes">Location may be concurrently modified, refrain from optimizations that will break if it is. Cache coherence: single-variable ordering, implicit on most architectures, but requires ld.acq on Itanium.</aside>
</section>
<section>
<h1><code class="c++">relaxed</code></h1>
<p class="fragment">“C++14 replaced the offensive wording with hand waving”</p>
<p class="fragment">“it's probably incorrect if you care about the result”</p>
<p class="fragment">— Hans Boehm</p>
<aside class="notes">Paraphrasing Hans Boehm's talk yesterday.</aside>
</section>
<section>
<h1>Atomic</h1>
<p class="fragment"><code class="c++">template<class T><br>struct atomic;</code></p>
<p class="fragment"><code class="c++">template<><br>struct atomic<integral>;</code></p>
<p class="fragment"><code class="c++">template<class T><br>struct atomic<T*>;</code></p>
<p class="fragment"><code class="c++">template<class T><br>struct atomic<floating-point>; // future</code></p>
<aside class="notes">All atomics operations are on atomic objects. Lifetime of memory locations, exclusively atomic or not. Holds a representation of T (alignment, etc).</aside>
</section>
<section>
<h1>Atomic<T></h1>
<ul class="fragment">
<li><code class="c++">load</code></li>
<li><code class="c++">store</code></li>
<li><code class="c++">exchange</code></li>
<li><code class="c++">compare_exchange_{weak,strong}</code></li>
<li><code class="c++">is_lock_free</code></li>
<li><code class="c++">static constexpr is_always_lock_free</code></li>
</ul>
<aside class="notes">Must be trivially copyable; can be structs, but watch out for padding bits! All have atomic ordering (except lock free).</aside>
</section>
<section>
<h1>Atomic<integral></h1>
<ul class="fragment">
<li><code class="c++">fetch_add</code></li>
<li><code class="c++">fetch_sub</code></li>
<li><code class="c++">fetch_and</code></li>
<li><code class="c++">fetch_or</code></li>
<li><code class="c++">fetch_xor</code></li>
</ul>
<aside class="notes">Some shorthands (without ordering) and coercions; integers are two's complement (no UB!).</aside>
</section>
<section>
<h1>Atomic<T*></h1>
<ul class="fragment">
<li><code class="c++">fetch_add</code></li>
<li><code class="c++">fetch_sub</code></li>
</ul>
</section>
<section>
<h1>Atomic<floating-point></h1>
<ul class="fragment">
<li><code class="c++">fetch_add</code></li>
<li><code class="c++">fetch_sub</code></li>
<li>More?</li>
</ul>
<aside class="notes">What can hardware do? FMA? Need cmpxchg? What of FP env (round, denorm, etc)? What's useful? See http://wg21.link/p0020</aside>
</section>
<section>
<h1>Fences</h1>
<ul class="fragment">
<li><code class="c++">atomic_thread_fence</code></li>
<li><code class="c++">atomic_signal_fence</code></li>
</ul>
<aside class="notes">Signal fence is basically a compiler barrier. Exist to order atomic operations that don't enforce ordering. On x86: compiler fences.</aside>
</section>
<section>
<h1>Lock-freedom</h1>
<p class="fragment">Guaranteed for <code class="c++">std::atomic_flag</code></p>
<p class="fragment">Roughly: is there a compare-exchange for this size?</p>
<p class="fragment">This is what I'm focusing on.</p>
<p class="fragment">What does non-lock-free mean?</p>
<aside class="notes">Why a runtime value? If it's not lock-free, you probably want to use a coarse-grained lock (unless you're lazy and want the implementation's locks).</aside>
</section>
<section>
<h1>Simple usage</h1>
<pre class="fragment"><code class="c++" data-noescape>
struct Data { int spam, bacon, eggs; std::atomic<int> ready; };
void write(Data *d) {
d->spam = 0xBEEF;
d->bacon = 0xCAFE;
d->eggs = 0x0000;
d->ready.store(1, std::memory_order_release);
}
auto read(Data *d) {
while (!d->ready.load(std::memory_order_acquire)) ;
return std::make_tuple(d->spam, d->bacon, d->eggs);
}
</code></pre>
<aside class="notes">For illustration only, this isn't great code! Only certain variables are atomic, despite the entire struct beign accessed by the two threads.</aside>
</section>
<section>
<h1>We have our tools!</h1>
<p class="fragment">Why is the language set up this way?</p>
<p class="fragment">Provide an abstraction for relevant hardware platforms.</p>
<aside class="notes">Let's look at a few architectures. For more details see https://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html or your neighborhood compiler.</aside>
</section>
<section>
<h1>x86-64</h1>
<table class="fragment" style="font-size: 65%">
<tr><td>load <code class="c++">relaxed</code></td><td><code class="x86asm">MOV</code></td></tr>
<tr><td>load <code class="c++">consume</code></td><td><code class="x86asm">MOV</code></td></tr>
<tr><td>load <code class="c++">acquire</code></td><td><code class="x86asm">MOV</code></td></tr>
<tr><td>load <code class="c++">seq_cst</code></td><td><code class="x86asm">MOV</code></td></tr>
<tr><td>store <code class="c++">relaxed</code></td><td><code class="x86asm">MOV</code></td></tr>
<tr><td>store <code class="c++">release</code></td><td><code class="x86asm">MOV</code></td></tr>
<tr><td>store <code class="c++">seq_cst</code></td><td><code class="x86asm">LOCK XCHG</code></td></tr>
<tr><td>non-<code class="c++">seq_cst</code> fence</td><td><code class="x86asm"># free!</code></td></tr>
<tr><td><code class="c++">seq_cst</code> fence</td><td><code class="x86asm">MFENCE</code></td></tr>
</table>
<aside class="notes">Not mentioning RMW / cmpxchg. Why the fence? Loads may be reordered with older stores to different locations.</aside>
</section>
<section>
<h1>Power</h1>
<table class="fragment" style="font-size: 65%">
<tr><td>load <code class="c++">relaxed</code></td><td><code class="x86asm">ld</code></td></tr>
<tr><td>load <code class="c++">consume</code></td><td><code class="x86asm">ld + dependencies</code></td></tr>
<tr><td>load <code class="c++">acquire</code></td><td><code class="x86asm">ld; cmp; bc; isync</code></td></tr>
<tr><td>load <code class="c++">seq_cst</code></td><td><code class="x86asm">hwsync; ld; cmp; bc; isync</code></td></tr>
<tr><td>store <code class="c++">relaxed</code></td><td><code class="x86asm">st</code></td></tr>
<tr><td>store <code class="c++">release</code></td><td><code class="x86asm">lwsync; st</code></td></tr>
<tr><td>store <code class="c++">seq_cst</code></td><td><code class="x86asm">hwsync; st</code></td></tr>
<tr><td><code class="c++">cmpxchg relaxed</code></td><td><code class="x86asm">_loop: lwarx; cmp; bc _exit; stwcx.; bc _loop; _exit:</code></td></tr>
<tr><td>non-<code class="c++">seq_cst</code> fence</td><td><code class="x86asm">lwsync</code></td></tr>
<tr><td><code class="c++">seq_cst</code> fence</td><td><code class="x86asm">hwsync</code></td></tr>
</table>
<aside class="notes">cmpxchg is ll / sc, more variants missing, RMW uses ll / sc. Not showing 64-bit.</aside>
</section>
<section>
<h1>ARMv7</h1>
<table class="fragment" style="font-size: 65%">
<tr><td>load <code class="c++">relaxed</code></td><td><code class="x86asm">ldr</code></td></tr>
<tr><td>load <code class="c++">consume</code></td><td><code class="x86asm">ldr + dependencies</code></td></tr>
<tr><td>load <code class="c++">acquire</code></td><td><code class="x86asm">ldr; dmb</code></td></tr>
<tr><td>load <code class="c++">seq_cst</code></td><td><code class="x86asm">ldr; dmb</code></td></tr>
<tr><td>store <code class="c++">relaxed</code></td><td><code class="x86asm">str</code></td></tr>
<tr><td>store <code class="c++">release</code></td><td><code class="x86asm">dmb; str</code></td></tr>
<tr><td>store <code class="c++">seq_cst</code></td><td><code class="x86asm">dmb; str; dmb</code></td></tr>
<tr><td><code class="c++">cmpxchg relaxed</code></td><td><code class="x86asm">_loop: ldrex; mov 0; teq; strexeq; teq 0; bne _loop</code></td></tr>
<tr><td>fences</td><td><code class="x86asm">dmb</code></td></tr>
</table>
<aside class="notes">Similar to Power, same for MIPS. 64-bit is slightly horrible; has ldrexd; sometimes ldrd is single-copy atomic. Many dmbs. "dmb sy" is system-wide (too strong for C++), "dmb ish" is often what you want. ARM has other barrier instructions as well!</aside>
</section>
<section>
<h1>ARMv8 A64</h1>
<table class="fragment" style="font-size: 65%">
<tr><td>load <code class="c++">relaxed</code></td><td><code class="x86asm">ldr</code></td></tr>
<tr><td>load <code class="c++">consume</code></td><td><code class="x86asm">ldr + dependencies</code></td></tr>
<tr><td>load <code class="c++">acquire</code></td><td><code class="x86asm">ldar</code></td></tr>
<tr><td>load <code class="c++">seq_cst</code></td><td><code class="x86asm">ldar</code></td></tr>
<tr><td>store <code class="c++">relaxed</code></td><td><code class="x86asm">str</code></td></tr>
<tr><td>store <code class="c++">release</code></td><td><code class="x86asm">stlr</code></td></tr>
<tr><td>store <code class="c++">seq_cst</code></td><td><code class="x86asm">stlr</code></td></tr>
<tr><td><code class="c++">cmpxchg relaxed</code></td><td><code class="x86asm">_loop: ldxr; cmp; bne _exit; stxr; cbz _loop; _exit</code></td></tr>
<tr><td>fences</td><td><code class="x86asm">dmb</code></td></tr>
</table>
<aside class="notes">Life imitates standards! Added "acquire" / "release" primitives, even to aarch32.</aside>
</section>
<section>
<h1>Itanium</h1>
<table class="fragment" style="font-size: 65%">
<tr><td>load <code class="c++">relaxed</code></td><td><code class="x86asm">ld.acq</code></td></tr>
<tr><td>load <code class="c++">consume</code></td><td><code class="x86asm">ld.acq</code></td></tr>
<tr><td>load <code class="c++">acquire</code></td><td><code class="x86asm">ld.acq</code></td></tr>
<tr><td>load <code class="c++">seq_cst</code></td><td><code class="x86asm">ld.acq</code></td></tr>
<tr><td>store <code class="c++">relaxed</code></td><td><code class="x86asm">st.rel</code></td></tr>
<tr><td>store <code class="c++">release</code></td><td><code class="x86asm">st.rel</code></td></tr>
<tr><td>store <code class="c++">seq_cst</code></td><td><code class="x86asm">st.rel; mfB</code></td></tr>
<tr><td><code class="c++">cmpxchg acquire</code></td><td><code class="x86asm">cmpxchg.acq</code></td></tr>
<tr><td>non-<code class="c++">seq_cst</code> fence</td><td><code class="x86asm"># free!</code></td></tr>
<tr><td><code class="c++">seq_cst</code> fence</td><td><code class="x86asm">mf</code></td></tr>
</table>
</section>
<section>
<h1>Alpha</h1>
<div class="fragment" style="font-size: 45%; text-align: justify">
<p>Oh, one of my favorite (NOT!) pieces of code in the kernel is the
implementation of the <code>smp_read_barrier_depends()</code> macro, which
on every single architecture except for one (alpha) is a no-op.</p>
<p>We have basically 30 or so empty definitions for it, and I think we have
something like five uses of it. One of them, I think, is performance
crticial, and the reason for that macro existing.</p>
<p>What does it do? The semantics is that it's a read barrier between two
different reads that we want to happen in order wrt two writes on the
writing side (the writing side also has to have a <code>smp_wmb()</code>
to order those writes). But the reason it isn't a simple read barrier is
that the reads are actually causally *dependent*, ie we have code like</p>
<pre class="c++"><code class="c++" data-noescape>
first_read = read_pointer;
smp_read_barrier_depends();
second_read = *first_read;
</code></pre>
<p>and it turns out that on pretty much all architectures (except for
alpha), the *data*dependency* will already guarantee that the CPU reads
the thing in order. And because a read barrier can actually be quite
expensive, we don't want to have a read barrier for this case.</p>
<p>But alpha? Its memory consistency is so broken that even the data
dependency doesn't actually guarantee cache access order. It's strange,
yes. No, it's not that alpha does some magic value prediction and can do
the second read without having even done the first read first to get the
address. What's actually going on is that the cache itself is unordered,
and without the read barrier, you may get a stale version from the cache
even if the writes were forced (by the write barrier in the writer) to
happen in the right order.</p>
<p>— Linus Torvalds</p>
</div>
<aside class="notes">Hard to implement C++ efficiently on Alpha! Exception that proves the rule?</aside>
</section>
<section>
<h1><code class="c++">consume</code></h1>
<p class="fragment">ARM address dependency rule</p>
<pre class="fragment c++"><code class="c++" data-noescape>
LDR r1, [r0]
LDR r2, [r1]
</code></pre>
<pre class="fragment c++"><code class="c++" data-noescape>
LDR r1, [r0]
AND r1, r1, #0
LDR r2, [r3, r1]
</code></pre>
<p class="fragment">Look ma, no barrier!</p>
<aside class="notes">Value returned by read is used to compute virtual address of subsequent read or write, these two memory accesses are observed in program order. Not control dependency on ARM. See "Barrier Litmus Tests and Cookbook". See http://wg21.link/p0190 consume isn't implemented because dependencies aren't how compilers work.</aside>
</section>
<section>
<h1><code class="c++">consume</code> maybe?</h1>
<pre class="fragment c++"><code class="c++" data-noescape>
template <typename T> auto consumeLoad(const T* location) {
using Returned = typename std::remove_cv<T>::type;
struct Consumed { Returned value; size_t dependency; } ret{};
ret.value = reinterpret_cast<const volatile std::atomic<Returned>*>(
location)->load(std::memory_order_relaxed);
#if CPU(ARM)
asm volatile("eor %[dependency], %[in], %[in]"
: [dependency] "=r"(ret.dependency)
: [in] "r"(ret.value)
: "memory");
#else
std::atomic_thread_fence(std::memory_order_acquire);
ret.dependency = 0;
#endif
return ret;
}
</code></pre>
<p><span class="fragment"><small>“looks like it probably works” — Richard Smith</small><br></span>
<span class="fragment"><small>“(other than the aliasing violation)”</small></span></p>
<aside class="notes">The actual code is more complicated.</aside>
</section>
<section>
<h1>Architecture-specific</h1>
<p>Same architecture, different instructions / performance.</p>
<p class="fragment">Flags to the rescue: <code>-march</code>, <code>-mcpu</code>, <code>-mattr</code></p>
<ul>
<li class="fragment">Special instructions</li>
<li class="fragment">what's the best spinloop?</li>
<li class="fragment">nominally incorrect code</li>
<li class="fragment">Workaround CPU bugs</li>
</ul>
<aside class="notes">Special: Intel RTM / HLE. Incorrect: on Apple Swift processor DMB ISH versus DMB ISHST (only wait for stores); some arch doesn't need barrier at all! AMD CPU bug for Chrome: barrier bug in AMD errata 147, Opterons 1xx/2xx/8xx, 2003-2004, 0.02% of Chrome users, compiler workaround.</aside>
</section>
<section>
<h1>Takeaways</h1>
<ul>
<li class="fragment">C++ exposes hardware portably</li>
<li class="fragment">Hardware changes over time</li>
<li class="fragment">Assembly operations operation on memory locations</li>
<li class="fragment">C++ atomics operate on datastructures</li>
</ul>
<aside class="notes">Portability is hard. Compiler should know best. C++ is higher level than asm. Operating on data instead of code is contended.</aside>
</section>
<section><h1>How do we optimize atomics?</h1></section>
<section>
<h2><em>as-if</em></h2>
<p class="fragment"><strong>more atomic</strong>: don’t violate forward progress</p>
<p class="fragment"><strong>less atomic</strong>: don’t add non-benign races which weren’t already present</p>
</section>
<section>
<h2>Put another way</h2>
<p>correct programs must work under all executions an implementation is allowed to create</p>
<aside class="notes">
<p>Keep in mind: compilers optimize code that compiler developers see and think are worth optimizing. We’re not trying to trip you!</p>
</aside>
</section>
<section>
<h2>What can the compiler do?</h2>
<p class="fragment">At least as much as the hardware could do</p>
<p class="fragment">and maybe more 😉</p>
<aside class="notes">Is this circular, since HW adapts to the standard? Can we optimize assuming there are no races?</aside>
</section>
<section>
<h2>What does hardware do?</h2>
<p>We saw a few examples earlier</p>
<aside class="notes">What of simulations? QEMU. DBT (with varying optimization, sometimes entertaining bringup bugs such as unrolling busy-wait loop). Virtual ISAs!</aside>
</section>
<section><h2>Simple example</h2>
<pre class="fragment"><code class="c++" data-noescape>
void inc(std::atomic<int> *y) {
*y += 1;
}
std::atomic<int> x;
void two() {
inc(&x);
inc(&x);
}
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
std::atomic<int> x;
void two() {
x += 2;
}
</code></pre>
<aside class="notes"><p>Adds atomicity but cannot hinder forward progress: correct.</p></aside>
</section>
<section><h2>Similar example</h2>
<pre class="fragment"><code class="c++" data-noescape>
std::atomic<int> x;
void inc(int val) {
x += 1;
x += val;
}
</code></pre>
<pre class="fragment"><code class="x86asm" data-noescape>
_Z3inci:
lock incl x(%rip)
lock addl %edi, x(%rip)
</code></pre>
<aside class="notes"><p>Not going to win a Turing award with this: `inc r/m` versus `add r/m, r`; both with lock prefix; inc doesn’t set carry (sometimes partial flag stall); both 3 bytes; one less register; check out Agner for μops / latency, lock prefix makes this moot. Maybe the compiler would know better after all?</p></aside>
</section>
<section><h2>Opportunities through inlining</h2>
<pre class="fragment"><code class="c++" data-noescape>
template<typename T>
bool silly(std::atomic<T> *x, T expected, T desired) {
x->compare_exchange_strong(expected, desired); // Inlined.
return expected == desired;
}
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
template<typename T>
bool silly(std::atomic<T> *x, T expected, T desired) {
return x->compare_exchange_strong(expected, desired);
}
</code></pre>
<aside class="notes"><p>Generic code ends up with interesting cases such as these. bool is usually a flag… but returning it depends on ABI!</p></aside>
</section>
<section>
<h2>A tricky one</h2>
<p class="fragment">Works for any memory order but <code class="c++">release</code> and <code class="c++">acq_rel</code></p>
<pre class="fragment"><code class="c++" data-noescape>
template<typename T>
bool optme(std::atomic<T> *x, T desired) {
T expected = desired;
return x->compare_exchange_strong(expected, desired,
std::memory_order_seq_cst, std::memory_order_relaxed);
}
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
template<typename T>
bool optme(std::atomic<T> *x, T desired) {
return x->load(std::memory_order_seq_cst) == desired; // †
}
</code></pre>
<p class="fragment"><small>† compiler: mark transformed load as <em>release sequence</em> <sup>‡</sup></small></p>
<p class="fragment"><small>‡ as defined in section 1.10 of the C++ standard</small></p>
</section>
<section>
<h2>Stronger, faster</h2>
<pre class="fragment"><code class="c++" data-noescape>
template<typename T>
T optmetoo(std::atomic<T> *x, T y) {
T z = x->load();
x->store(y);
return z;
}
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
template<typename T>
T optmetoo(std::atomic<T> *x, T y) {
return x->exchange(y);
}
</code></pre>
<h2 class="fragment">better?</h2>
<aside class="notes"><p>May not always pay off: architectures with weaker memory models may benefit from having write-after-read operations to the same location instead of having an atomic exchange.</p></aside>
</section>
<section>
<h1>Interesting problem...</h1>
<img class="fragment" src="wonka.jpg" style="border:none" />
</section>
<section>
<h1>Read ; Modify ; Write</h1>
<p>Hogwild!: A Lock-Free Approach to Parallelizing Stochastic Gradient Descent</p>
</section>
<section>
<h2>Racy</h2>
<pre><code class="c++" data-noescape>
float y;
void g(float a) { y += a; }
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
addss y(%rip), %xmm0
movss %xmm0, y(%rip)
</code></pre>
</section>
<section>
<h2><code>volatile</code></h2>
<pre><code class="c++" data-noescape>
volatile float yv;
void gv(float a) { yv += a; }
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
addss yv(%rip), %xmm0
movss %xmm0, yv(%rip)
</code></pre>
</section>
<section>
<h2>Correct?</h2>
<pre><code class="c++" data-noescape>
std::atomic<float> x;
void f(float a) {
x.store(x.load(std::memory_order_relaxed) + a,
std::memory_order_relaxed);
}
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
movl x(%rip), %eax
movd %eax, %xmm1
addss %xmm0, %xmm1
movd %xmm1, %eax
movl %eax, x(%rip)
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
addss x(%rip), %xmm0
movss %xmm0, x(%rip)
</code></pre>
<p class="fragment">Optimization FTW!</p>
<aside class="notes">Is this correct? All relaxed doesn't guarantee visibility! Add infrequent fence? 3x faster.</aside>
</section>
<section>
<h2>Moar!</h2>
<p class="fragment">Inlining and constant propagation</p>
<p class="fragment"><code class="c++">atomic<T>::fetch_and(~(T)0)</code> → <code class="c++">atomic<T>::load()</code></p>
<p class="fragment">Same for <code class="c++">fetch_or(0)</code> and <code class="c++">fetch_xor(0)</code></p>
<p class="fragment"><code class="c++">atomic<T>::fetch_and(0)</code> → <code class="c++">atomic<T>::store(0)</code></p>
</section>
<section>
<h2>Takeaway</h2>
<p class="fragment">If simple things are hard…</p>
<p class="fragment">…is your inline assembly correct?</p>
<p class="fragment">…will it remain correct?</p>
<p class="fragment">Do you trust your compiler?</p>
<aside class="notes"><p>Sorry to say, you’re already trusting your compiler (or deluding yourself).</p></aside>
</section>
<section>
<p>What if the compiler emits suboptimal code?</p>
<h2 class="fragment">File a bug!</h2>
</section>
<section>
<h1>Sequence lock</h1>
<ul>
<li class="fragment">Get ticket number</li>
<li class="fragment">Get the data</li>
<li class="fragment">Check the ticket again
<ul>
<li>If odd: write was happening</li>
<li>If different: write occurred</li>
<li>If same: no write occurred, data is good</li>
</ul>
</li>
<li class="fragment">If data isn’t good: try again</li>
</ul>
<aside class="notes"><p>Read-mostly; don’t starve writers.</p></aside>
</section>
<section>
<pre><code class="c++" data-noescape>
std::tuple<T, T> reader() {
T d1, d2; unsigned seq0, seq1;
do {
seq0 = seq.load(std::memory_order_acquire);
d1 = data1.load(std::memory_order_relaxed);
d2 = data2.load(std::memory_order_relaxed);
<mark>std::atomic_thread_fence(std::memory_order_acquire);</mark>
<mark>seq1 = seq.load(std::memory_order_relaxed);</mark>
} while (seq0 != seq1 || seq0 & 1);
return {d1, d2};
}
</code></pre>
<pre><code class="c++" data-noescape>
void writer(T d1, T d2) {
unsigned seq0 = seq.load(std::memory_order_relaxed);
seq.store(seq0 + 1, std::memory_order_relaxed);
data1.store(d1, std::memory_order_release);
data2.store(d2, std::memory_order_release);
seq.store(seq0 + 2, std::memory_order_release);
}
</code></pre>
<aside class="notes"><p>Relaxed can be reordered with each other; fence is heavy on some architectures; acquire over-constrains (prevents motion into critical section); not intuitive.</p></aside>
</section>
<section>
<p>We <em>really</em> want a release load</p>
<p class="fragment">(there is no release load)</p>
</section>
<section>
<h2>Read-don’t-modify-write</h2>
<pre class="fragment"><code class="c++" data-noescape>
T d1, d2;
unsigned seq0, seq1;
do {
seq0 = seq.load(std::memory_order_acquire);
d1 = data1.load(std::memory_order_relaxed);
d2 = data2.load(std::memory_order_relaxed);
<mark>seq1 = seq.fetch_add(0, std::memory_order_release);</mark>
} while (seq0 != seq1 || seq0 & 1);
</code></pre>
<aside class="notes"><p>Better for some architectures; can move reads into critical section.</p></aside>
</section>
<section>
<pre class="fragment"><code class="x86asm" data-noescape>
mov 0x200a76(%rip),%edx # seq
mov 0x200a74(%rip),%eax # data1
mov 0x200a72(%rip),%ecx # data2
# acquire fence
mov 0x200a64(%rip),%esi # seq
</code></pre>
<pre class="fragment"><code class="x86asm" data-noescape>
mov 0x2004c6(%rip),%ecx # seq
mov 0x2004bc(%rip),%esi # data1
xor %edx,%edx
mov 0x2004af(%rip),%r8d # data2
lock xadd %edx,0x2004af(%rip) # seq RdMW
</code></pre>
<pre class="fragment"><code class="x86asm" data-noescape>
mov 0x200a46(%rip),%edx # seq
mov 0x200a44(%rip),%eax # data1
mov 0x200a42(%rip),%ecx # data2
mfence # optimized RdMW!
mov 0x200a31(%rip),%esi # seq
</code></pre>
<aside class="notes"><p>x86 `lock xadd` requires exclusive access! Can optimize to `mfence; mov`.</p></aside>
</section>
<section>
<h2>What's better?</h2>
<img src="seqlock.png" style="border:none" />
<aside class="notes"><p>`mfence` is 3.5× slower. On POWER RdMW is faster but doesn't scale with number of threads.</p></aside>
</section>
<section>
<h2>"Normal" compiler optimizations</h2>
<p class="fragment">Dead store elimination?</p>
<p class="fragment">Strength reduction?</p>
<aside class="notes">Careful: avoid doing so across synchronization points (other thread of execution can observe or modify memory, which means that the traditional optimizations have to consider more intervening instructions). DSO: can't just prove atomic store post-dominates and aliases another to eliminate the other store.</aside>
</section>
<section>
<h2><code class="c++">relaxed</code> optimization</h2>
<pre class="fragment"><code class="c++" data-noescape>
std::atomic<int> x, y;
void relaxed() {
x.fetch_add(1, std::memory_order_relaxed);
y.fetch_add(1, std::memory_order_relaxed);
x.fetch_add(1, std::memory_order_relaxed);
y.fetch_add(1, std::memory_order_relaxed);
}
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
std::atomic<int> x, y;
void relaxed() {
x.fetch_add(2, std::memory_order_relaxed);
y.fetch_add(2, std::memory_order_relaxed);
}
</code></pre>
<aside class="notes">Not aware of compilers which do this.</aside>
</section>
<section>
<h2>Progress bar</h2>
<pre class="fragment"><code class="c++" data-noescape>
atomic<int> progress(0);
f() {
for (i = 0; i < 1000000; ++i) {
// Heavy work, no shared memory...
++progress;
}
}
</code></pre>
<pre class="fragment"><code class="c++" data-noescape>
atomic<int> progress(0);
f() {
int my_progress = 0; // register allocated
for (i = 0; i < 1000000; ++i) {
// Heavy work, no shared memory...
++my_progress;
}
progress += my_progress;
}
</code></pre>
<aside class="notes">When should compilers optimize atomics? We added non-normative wording to C++17 to discourage this.</aside>
</section>
<section>
<h2>Disabling reordering / fusing?</h2>
<ul>
<li class="fragment"><code class="c++">asm volatile("":::"memory");</code><code class="fragment c++"> // eek!</code></li>
<li class="fragment"><code class="c++">std::atomic_signal_fence();</code><code class="fragment c++"> // wat?</code></li>
<li class="fragment">Use <code class="c++">volatile</code>? <strong class="fragment">NO!</strong></li>
<li class="fragment">Don't use <code class="c++">relaxed</code>?</li>
<li class="fragment">Synchronize-with?</li>
</ul>
</section>
<section>
<h2>Moar!</h2>
<ul>
<li class="fragment">Tag "non-atomic" functions, optimize around them</li>
<li class="fragment">Interference-free regions</li>
<li class="fragment">Optimize fence positioning</li>
<li class="fragment">Non-escaping thread local (TLS, stack)</li>
<li class="fragment">etc.</li>
</ul>
<aside class="notes">Compilers already know about "read-only" functions.</aside>
</section>
<section>
<h1><code class="c++">std::mutex</code> for sanity</h1>
<ul>
<li class="fragment">easier to use correctly</li>
<li class="fragment">in theory...
<ul>
<li>it could still get optimized</li>
<li>lock: <code class="c++">acquire</code>; unlock: <code class="c++">release</code></li>
</ul>
</li>
<li class="fragment">pthread and kernel call makes this hard</li>
<li class="fragment"><code class="c++">std::synchronic</code> to the rescue!</li>
</ul>
</section>
<section>
<h1><code class="c++">std::mutex</code></h1>
<p class="fragment">Knows better</p>
<aside class="notes">Backoff strategies are HW and OS specific. Atomics don't solve all problems.</aside>
</section>
<section>
<h1><code class="c++">volatile</code></h1>
<p class="fragment">Initial motivation: <code class="c++">getChar()</code> on PDP-11, reading memory-mapped <code>KBD_STAT</code> I/O register</p>
<p class="fragment">K&R: The purpose of <code class="c++">volatile</code> is to force an implementation to suppress optimization that could otherwise occur</p>
</section>
<section>
<h1>What does that mean?</h1>
<ul>
<li class="fragment">Prevent load / store motion?</li>
<li class="fragment">Prevent arithmetic motion?</li>
<li class="fragment">Hardware fence? x86 <code class="x86asm">MFENCE</code>? ARM <code class="x86asm">DMB SY</code>?</li>
<li class="fragment">Shared memory?</li>
</ul>
<aside class="notes">When shared memory is used and the other side is untrusted / adversarial / POB (Plain Old Buggy). c.f. Xen exploit.</code>
</section>
<section>
<h1>It gets better</h1>
</section>
<section>
<h1>Xtensa GCC options</h1>
<p><code>-mserialize-volatile</code></p>
<p><code>-mnoserialize-volatile</code></p>
<p>When this option is enabled, GCC inserts <code>MEMW</code> instructions before <code>volatile</code> memory references to guarantee sequential consistency.</p>
</section>
<section>
<h1>MSVC</h1>
<p>You can use the <code>/volatile</code> compiler switch to modify how the compiler interprets this keyword. If a struct member is marked as <code>volatile</code>, then <code>volatile</code> is propagated to the whole structure. If a structure does not have a length that can be copied on the current architecture by using one instruction, <code>volatile</code> may be completely lost on that structure.</p>
<p class="fragment">clang emulates this with <code>-fms-volatile</code></p>
<aside class="notes">MSVC on ARM does something saner: store release, load acquire.</aside>
</section>
<section>
<h1>What does it mean‽</h1>
<p class="fragment">¯\_(ツ)_/¯</p>
<ul class="fragment">
<li>can tear</li>
<li>each byte touched exactly once</li>
<li>no machine-level ordering</li>
<li>enforces abstract machine ordering with other <code>volatile</code></li>
<li>can't duplicate</li>
<li>can't elide</li>
</ul>
<aside class="notes">Highly compiler + HW dependent. Not "atomic" as in greek.</aside>
</section>
<section>
<h1>Can <code>volatile</code> be lock-free?</h1>
<p class="fragment">¯\_(ツ)_/¯</p>
<aside class="notes">Lock-free usually means cmpxchg available. Touches bytes more than once!</aside>
</section>
<section>
<h1>Can <code>volatile</code> do RMW?</h1>
<p class="fragment">No</p>
</section>
<section>
<h1>Are there portable <code>volatile</code> uses?</h1>
<ul>
<li class="fragment">mark local variables in the same scope as a <code>setjmp</code>, preserve value across <code>longjmp</code></li>
<li class="fragment"><strong>externally modified</strong>: physical memory mapped in multiple virtual addresses</li>
<li class="fragment"><code>volatile sigatomic_t</code> may be used to communicate with a signal handler in the same thread</li>
</ul>
<aside class="notes">THis is pretty debatable! Note for signals: need Plain Old Function, very arbitrary, will change in C++17.</aside>
</section>
<section>
<h1><code>volatile atomic</code></h1>
<p>what's that?</p>
<aside class="notes">Both! Adds atomic as in greek to volatile. Beware lock-free: what happens to address-free with shared mmemory?</aside>
</section>
<section>
<h1>What do compilers do?</h1>
<p>by compilers I mean clang</p>
</section>
<section>
<h1>Standard library</h1>
<p>C's <code>_Atomic</code> ↔ C++'s <code>std::atomic</code></p>
<p class="fragment"><code>_sync_*</code> builtins</p>
<p class="fragment"><code>_atomic_*</code> builtins</p>
<aside class="notes">Compiler runtime has the lock shard. Older library versions were very broken.</aside>
</section>
<section>
<h1>Front-end</h1>
<p>does little besides inlining constant <code>memory_order_*</code></p>
</section>
<section>
<h1>Middle-end</h1>
<ul>
<li class="fragment"><code>load atomic [volatile] <ty>, <ty>* <pointer> [singlethread] <ordering>, align <alignment></code></li>
<li class="fragment"><code>store atomic [volatile] <ty> <value>, <ty>* <pointer> [singlethread] <ordering>, align <alignment></code></li>
</ul>
</section>
<section>
<h1>Middle-end</h1>
<ul>
<li class="fragment"><code>atomicrmw [volatile] <operation> <ty>* <pointer>, <ty> <value> [singlethread] <ordering></code></li>
<li class="fragment"><code>cmpxchg [weak] [volatile] <ty>* <pointer>, <ty> <cmp>, <ty> <new> [singlethread] <success ordering> <failure ordering></code></li>
<li class="fragment"><code>fence [singlethread] <ordering></code></li>
</ul>
</section>
<section>
<h1>IR</h1>
<p><code>isSimple</code>, <code>isVolatile</code>, <code>isAtomic</code>: steer clear</p>
</section>
<section>
<h1>Machine IR</h1>
<p>similar to actual ISA instructions</p>
</section>
<section><h1>Now what?</h1></section>
<section>
<h1>Standards Committee</h1>
<p>Assume optimizations occur, encourage them.</p>
<p>Standardize common practice, enable to-the-metal optimizations.</p>
<p>More libraries: easy to use concurrency & parallelism; hard to get it wrong.</p>
</section>
<section>
<h1>Developers</h1>
<p>Drop assembly</p>
<p>File bugs</p>
<p>Talk to standards committee.</p>
<p>Use tooling: ThreadSanitizer.</p>
</section>
<section>
<h1>Hardware vendors</h1>
<p>Showcase your hardware’s strengths.</p>
</section>
<section>
<h1>Compiler writers</h1>
<p>Get back to work!</p>
</section>
<section>
<h1>Sane Compilers Should Optimize Atomics</h1>
<p>and you should use atomics</p>
<p><a href="https://github.com/jfbastien/no-sane-compiler">github.com/jfbastien/no-sane-compiler</a></p>
<p><a href="https://twitter.com/jfbastien">@jfbastien</a></p>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: false, // Display controls in the bottom right corner
progress: true, // Display a presentation progress bar
history: true, // Push each slide change to the browser history
keyboard: true, // Enable keyboard shortcuts for navigation
overview: true, // Enable the slide overview mode
center: true, // Vertical centering of slides
touch: true,
loop: false,
rtl: false,
shuffle: false,
fragments: true, // Turns fragments on and off globally
help: true, // Flags if we should show a help overlay when the questionmark key is pressed
showNotes: false, // Flags if speaker notes should be visible to all viewers
autoSlide: 0,
autoSlideStoppable: true, // Stop auto-sliding after user input
autoSlideMethod: Reveal.navigateNext,
mouseWheel: false,
hideAddressBar: true,
previewLinks: false, // Opens links in an iframe preview overlay
transition: 'default', // none/fade/slide/convex/concave/zoom
transitionSpeed: 'default', // default/fast/slow
backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom
viewDistance: 3, // Number of slides away from the current that are visible
//parallaxBackgroundImage: 'bg.jpg',
//parallaxBackgroundSize: '2559px 1510px', // CSS syntax, e.g. "2100px 900px"
// Number of pixels to move the parallax background per slide
// - Calculated automatically unless specified
// - Set to 0 to disable movement along an axis
parallaxBackgroundHorizontal: null,
parallaxBackgroundVertical: null,
// More info https://github.com/hakimel/reveal.js#dependencies
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }
]
});
</script>
</body>
</html>