Debian Codegraph @

libphobos/libdruntime/core/internal/atomic.d

raw
1 /**
2 * The core.internal.atomic module comtains the low-level atomic features available in hardware.
3 * This module may be a routing layer for compiler intrinsics.
4 *
5 * Copyright: Copyright Manu Evans 2019.
6 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Authors: Sean Kelly, Alex Rønne Petersen, Manu Evans
8 * Source: $(DRUNTIMESRC core/internal/_atomic.d)
9 */
10
11 module core.internal.atomic;
12
13 import core.atomic : has128BitCAS, MemoryOrder;
14
15 version (DigitalMars)
16 {
17 private
18 {
19 enum : int
20 {
21 AX, BX, CX, DX, DI, SI, R8, R9
22 }
23
24 immutable string[4][8] registerNames = [
25 [ "AL", "AX", "EAX", "RAX" ],
26 [ "BL", "BX", "EBX", "RBX" ],
27 [ "CL", "CX", "ECX", "RCX" ],
28 [ "DL", "DX", "EDX", "RDX" ],
29 [ "DIL", "DI", "EDI", "RDI" ],
30 [ "SIL", "SI", "ESI", "RSI" ],
31 [ "R8B", "R8W", "R8D", "R8" ],
32 [ "R9B", "R9W", "R9D", "R9" ],
33 ];
34
35 template RegIndex(T)
36 {
37 static if (T.sizeof == 1)
38 enum RegIndex = 0;
39 else static if (T.sizeof == 2)
40 enum RegIndex = 1;
41 else static if (T.sizeof == 4)
42 enum RegIndex = 2;
43 else static if (T.sizeof == 8)
44 enum RegIndex = 3;
45 else
46 static assert(false, "Invalid type");
47 }
48
49 enum SizedReg(int reg, T = size_t) = registerNames[reg][RegIndex!T];
50 }
51
52 enum IsAtomicLockFree(T) = T.sizeof <= size_t.sizeof * 2;
53
54 inout(T) atomicLoad(MemoryOrder order = MemoryOrder.seq, T)(inout(T)* src) pure nothrow @nogc @trusted
55 if (CanCAS!T)
56 {
57 static assert(order != MemoryOrder.rel && order != MemoryOrder.acq_rel,
58 "invalid MemoryOrder for atomicLoad()");
59
60 // We place some storage on the stack,
61 // get a pointer to that (which is also stored on the stack)
62 // and then store the result of the load into the storage.
63 // Finally returning it.
64 // Anything other than this is calling convention specific,
65 // and that is very fail heavy.
66 size_t[2] storage = void;
67 size_t* resultValuePtr = cast(size_t*)&storage[0];
68
69 static if (T.sizeof == size_t.sizeof * 2)
70 {
71 version (D_InlineAsm_X86)
72 {
73 asm pure nothrow @nogc @trusted
74 {
75 push EBX; // call preserved
76 push EDI;
77
78 mov EBX, 0;
79 mov ECX, 0;
80 mov EAX, 0;
81 mov EDX, 0;
82
83 mov EDI, src;
84 lock; cmpxchg8b [EDI];
85
86 lea EBX, resultValuePtr;
87 mov EBX, [EBX];
88 mov [EBX], EAX;
89 mov [EBX + size_t.sizeof], EDX;
90
91 pop EDI;
92 pop EBX;
93 }
94 }
95 else version (D_InlineAsm_X86_64)
96 {
97 asm pure nothrow @nogc @trusted
98 {
99 push RBX; // call preserved
100
101 mov RBX, 0;
102 mov RCX, 0;
103 mov RAX, 0;
104 mov RDX, 0;
105
106 mov R8, src;
107 lock; cmpxchg16b [R8];
108
109 lea RBX, resultValuePtr;
110 mov RBX, [RBX];
111 mov [RBX], RAX;
112 mov [RBX + size_t.sizeof], RDX;
113
114 pop RBX;
115 }
116 }
117 else
118 static assert(0, "Operation not supported");
119
120 return *cast(inout(T)*)resultValuePtr;
121 }
122 else static if (needsLoadBarrier!order)
123 {
124 version (D_InlineAsm_X86)
125 {
126 }
127 else version (D_InlineAsm_X86_64)
128 {
129 }
130 else
131 static assert(0, "Operation not supported");
132
133 enum SrcReg = SizedReg!CX;
134 enum ZeroReg = SizedReg!(DX, T);
135 enum ResReg = SizedReg!(AX, T);
136 enum TemporaryReg = SizedReg!(BX);
137
138 mixin (simpleFormat(q{
139 asm pure nothrow @nogc @trusted
140 {
141 push %3; // call preserved
142
143 mov %1, 0;
144 mov %2, 0;
145 mov %0, src;
146 lock; cmpxchg [%0], %1;
147 lea %3, resultValuePtr;
148 mov %3, [%3];
149 mov [%3], %2;
150
151 pop %3;
152 }
153 }, [SrcReg, ZeroReg, ResReg, TemporaryReg]));
154
155 return *cast(inout(T)*)resultValuePtr;
156 }
157 else
158 return *src;
159 }
160
161 void atomicStore(MemoryOrder order = MemoryOrder.seq, T)(T* dest, T value) pure nothrow @nogc @trusted
162 if (CanCAS!T)
163 {
164 static assert(order != MemoryOrder.acq && order != MemoryOrder.acq_rel,
165 "Invalid MemoryOrder for atomicStore()");
166
167 static if (T.sizeof == size_t.sizeof * 2)
168 {
169 version (D_InlineAsm_X86)
170 {
171 asm pure nothrow @nogc @trusted
172 {
173 push EDI;
174 push EBX;
175 lea EDI, value;
176 mov EBX, [EDI];
177 mov ECX, 4[EDI];
178 mov EDI, dest;
179 mov EAX, [EDI];
180 mov EDX, 4[EDI];
181 L1: lock; cmpxchg8b [EDI];
182 jne L1;
183 pop EBX;
184 pop EDI;
185 }
186 }
187 else version (D_InlineAsm_X86_64)
188 {
189 version (Windows)
190 {
191 asm pure nothrow @nogc @trusted
192 {
193 naked;
194 push RBX;
195 mov R8, RDX;
196 mov RAX, [RDX];
197 mov RDX, 8[RDX];
198 mov RBX, [RCX];
199 mov RCX, 8[RCX];
200 L1: lock; cmpxchg16b [R8];
201 jne L1;
202 pop RBX;
203 ret;
204 }
205 }
206 else
207 {
208 asm pure nothrow @nogc @trusted
209 {
210 naked;
211 push RBX;
212 mov RBX, RDI;
213 mov RCX, RSI;
214 mov RDI, RDX;
215 mov RAX, [RDX];
216 mov RDX, 8[RDX];
217 L1: lock; cmpxchg16b [RDI];
218 jne L1;
219 pop RBX;
220 ret;
221 }
222 }
223 }
224 }
225 else static if (needsStoreBarrier!order)
226 atomicExchange!(order, false)(dest, value);
227 else
228 *dest = value;
229 }
230
231 T atomicFetchAdd(MemoryOrder order = MemoryOrder.seq, bool result = true, T)(T* dest, T value) pure nothrow @nogc @trusted
232 if (is(T : ulong))
233 {
234 version (D_InlineAsm_X86)
235 {
236 static assert(T.sizeof <= 4, "64bit atomicFetchAdd not supported on 32bit target." );
237
238 enum DestReg = SizedReg!DX;
239 enum ValReg = SizedReg!(AX, T);
240
241 mixin (simpleFormat(q{
242 asm pure nothrow @nogc @trusted
243 {
244 mov %1, value;
245 mov %0, dest;
246 lock; xadd[%0], %1;
247 }
248 }, [DestReg, ValReg]));
249 }
250 else version (D_InlineAsm_X86_64)
251 {
252 version (Windows)
253 {
254 enum DestReg = SizedReg!DX;
255 enum ValReg = SizedReg!(CX, T);
256 }
257 else
258 {
259 enum DestReg = SizedReg!SI;
260 enum ValReg = SizedReg!(DI, T);
261 }
262 enum ResReg = result ? SizedReg!(AX, T) : null;
263
264 mixin (simpleFormat(q{
265 asm pure nothrow @nogc @trusted
266 {
267 naked;
268 lock; xadd[%0], %1;
269 ?2 mov %2, %1;
270 ret;
271 }
272 }, [DestReg, ValReg, ResReg]));
273 }
274 else
275 static assert (false, "Unsupported architecture.");
276 }
277
278 T atomicFetchSub(MemoryOrder order = MemoryOrder.seq, bool result = true, T)(T* dest, T value) pure nothrow @nogc @trusted
279 if (is(T : ulong))
280 {
281 return atomicFetchAdd(dest, cast(T)-cast(IntOrLong!T)value);
282 }
283
284 T atomicExchange(MemoryOrder order = MemoryOrder.seq, bool result = true, T)(T* dest, T value) pure nothrow @nogc @trusted
285 if (CanCAS!T)
286 {
287 static assert(order != MemoryOrder.acq, "Invalid MemoryOrder for atomicExchange()");
288 // We place some storage on the stack,
289 // this storage and cast it to appropriete type.
290 // This is calling convention agnostic.
291 size_t storage = void;
292
293 version (D_InlineAsm_X86)
294 {
295 static assert(T.sizeof <= 4, "64bit atomicExchange not supported on 32bit target.");
296 }
297 else version (D_InlineAsm_X86_64)
298 {
299 }
300 else
301 static assert(0, "Operation not supported");
302
303 enum DestReg = SizedReg!CX;
304 enum ValReg = SizedReg!(AX, T);
305
306 mixin (simpleFormat(q{
307 asm pure nothrow @nogc @trusted
308 {
309 mov %1, value;
310 mov %0, dest;
311 lock; xchg [%0], %1;
312
313 lea %0, storage;
314 mov [%0], %1;
315 }
316 }, [DestReg, ValReg]));
317
318 return *cast(T*)&storage;
319 }
320
321 alias atomicCompareExchangeWeak = atomicCompareExchangeStrong;
322
323 bool atomicCompareExchangeStrong(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T)(T* dest, T* compare, T value) pure nothrow @nogc @trusted
324 if (CanCAS!T)
325 {
326 static assert(fail != MemoryOrder.rel && fail != MemoryOrder.acq_rel,
327 "Invalid fail MemoryOrder for atomicCompareExchangeStrong()");
328 static assert (succ >= fail, "The first MemoryOrder argument for atomicCompareExchangeStrong() cannot be weaker than the second argument");
329 bool success;
330
331 static if (T.sizeof == size_t.sizeof * 2)
332 {
333 // some values simply cannot be loa'd here, so we'll use an intermediary pointer that we can move instead
334 T* valuePointer = &value;
335
336 version (D_InlineAsm_X86)
337 {
338 asm pure nothrow @nogc @trusted
339 {
340 push EBX; // call preserved
341 push EDI;
342
343 mov EDI, valuePointer; // value
344 mov EBX, [EDI];
345 mov ECX, [EDI + size_t.sizeof];
346 mov EDI, compare; // [compare]
347 mov EAX, [EDI];
348 mov EDX, [EDI + size_t.sizeof];
349
350 mov EDI, dest;
351 lock; cmpxchg8b [EDI];
352
353 setz success;
354 mov EDI, compare;
355 mov [EDI], EAX;
356 mov [EDI + size_t.sizeof], EDX;
357
358 pop EDI;
359 pop EBX;
360 }
361 }
362 else version (D_InlineAsm_X86_64)
363 {
364 asm pure nothrow @nogc @trusted
365 {
366 push RBX; // call preserved
367
368 mov R8, valuePointer; // value
369 mov RBX, [R8];
370 mov RCX, [R8 + size_t.sizeof];
371 mov R8, compare; // [compare]
372 mov RAX, [R8];
373 mov RDX, [R8 + size_t.sizeof];
374
375 mov R8, dest;
376 lock; cmpxchg16b [R8];
377
378 setz success;
379 mov R8, compare;
380 mov [R8], RAX;
381 mov [R8 + size_t.sizeof], RDX;
382
383 pop RBX;
384 }
385 }
386 else
387 static assert(0, "Operation not supported");
388 }
389 else
390 {
391 version (D_InlineAsm_X86)
392 {
393 }
394 else version (D_InlineAsm_X86_64)
395 {
396 }
397 else
398 static assert(0, "Operation not supported");
399
400 enum SrcReg = SizedReg!CX;
401 enum ValueReg = SizedReg!(DX, T);
402 enum CompareReg = SizedReg!(AX, T);
403
404 mixin (simpleFormat(q{
405 asm pure nothrow @nogc @trusted
406 {
407 mov %1, value;
408 mov %0, compare;
409 mov %2, [%0];
410
411 mov %0, dest;
412 lock; cmpxchg [%0], %1;
413
414 setz success;
415 mov %0, compare;
416 mov [%0], %2;
417 }
418 }, [SrcReg, ValueReg, CompareReg]));
419 }
420
421 return success;
422 }
423
424 alias atomicCompareExchangeWeakNoResult = atomicCompareExchangeStrongNoResult;
425
426 bool atomicCompareExchangeStrongNoResult(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T)(T* dest, const T compare, T value) pure nothrow @nogc @trusted
427 if (CanCAS!T)
428 {
429 static assert(fail != MemoryOrder.rel && fail != MemoryOrder.acq_rel,
430 "Invalid fail MemoryOrder for atomicCompareExchangeStrongNoResult()");
431 static assert (succ >= fail, "The first MemoryOrder argument for atomicCompareExchangeStrongNoResult() cannot be weaker than the second argument");
432 bool success;
433
434 static if (T.sizeof == size_t.sizeof * 2)
435 {
436 // some values simply cannot be loa'd here, so we'll use an intermediary pointer that we can move instead
437 T* valuePointer = &value;
438 const(T)* comparePointer = &compare;
439
440 version (D_InlineAsm_X86)
441 {
442 asm pure nothrow @nogc @trusted
443 {
444 push EBX; // call preserved
445 push EDI;
446
447 mov EDI, valuePointer; // value
448 mov EBX, [EDI];
449 mov ECX, [EDI + size_t.sizeof];
450 mov EDI, comparePointer; // compare
451 mov EAX, [EDI];
452 mov EDX, [EDI + size_t.sizeof];
453
454 mov EDI, dest;
455 lock; cmpxchg8b [EDI];
456
457 setz success;
458
459 pop EDI;
460 pop EBX;
461 }
462 }
463 else version (D_InlineAsm_X86_64)
464 {
465 asm pure nothrow @nogc @trusted
466 {
467 push RBX; // call preserved
468
469 mov R8, valuePointer; // value
470 mov RBX, [R8];
471 mov RCX, [R8 + size_t.sizeof];
472 mov R8, comparePointer; // compare
473 mov RAX, [R8];
474 mov RDX, [R8 + size_t.sizeof];
475
476 mov R8, dest;
477 lock; cmpxchg16b [R8];
478
479 setz success;
480
481 pop RBX;
482 }
483 }
484 else
485 static assert(0, "Operation not supported");
486 }
487 else
488 {
489 version (D_InlineAsm_X86)
490 {
491 }
492 else version (D_InlineAsm_X86_64)
493 {
494 }
495 else
496 static assert(0, "Operation not supported");
497
498 enum SrcReg = SizedReg!CX;
499 enum ValueReg = SizedReg!(DX, T);
500 enum CompareReg = SizedReg!(AX, T);
501
502 mixin (simpleFormat(q{
503 asm pure nothrow @nogc @trusted
504 {
505 mov %1, value;
506 mov %2, compare;
507
508 mov %0, dest;
509 lock; cmpxchg [%0], %1;
510
511 setz success;
512 }
513 }, [SrcReg, ValueReg, CompareReg]));
514 }
515
516 return success;
517 }
518
519 void atomicFence(MemoryOrder order = MemoryOrder.seq)() pure nothrow @nogc @trusted
520 {
521 // TODO: `mfence` should only be required for seq_cst operations, but this depends on
522 // the compiler's backend knowledge to not reorder code inappropriately,
523 // so we'll apply it conservatively.
524 static if (order != MemoryOrder.raw)
525 {
526 version (D_InlineAsm_X86)
527 {
528 import core.cpuid;
529
530 // TODO: review this implementation; it seems way overly complicated
531 asm pure nothrow @nogc @trusted
532 {
533 naked;
534
535 call sse2;
536 test AL, AL;
537 jne Lcpuid;
538
539 // Fast path: We have SSE2, so just use mfence.
540 mfence;
541 jmp Lend;
542
543 Lcpuid:
544
545 // Slow path: We use cpuid to serialize. This is
546 // significantly slower than mfence, but is the
547 // only serialization facility we have available
548 // on older non-SSE2 chips.
549 push EBX;
550
551 mov EAX, 0;
552 cpuid;
553
554 pop EBX;
555
556 Lend:
557
558 ret;
559 }
560 }
561 else version (D_InlineAsm_X86_64)
562 {
563 asm pure nothrow @nogc @trusted
564 {
565 naked;
566 mfence;
567 ret;
568 }
569 }
570 else
571 static assert (false, "Unsupported architecture.");
572 }
573 }
574
575 void atomicSignalFence(MemoryOrder order = MemoryOrder.seq)() pure nothrow @nogc @trusted
576 {
577 // no-op, dmd doesn't reorder instructions
578 }
579
580 void pause() pure nothrow @nogc @trusted
581 {
582 version (D_InlineAsm_X86)
583 {
584 asm pure nothrow @nogc @trusted
585 {
586 naked;
587 pause;
588 ret;
589 }
590 }
591 else version (D_InlineAsm_X86_64)
592 {
593 asm pure nothrow @nogc @trusted
594 {
595 naked;
596 pause;
597 ret;
598 }
599 }
600 else
601 {
602 // ARM should `yield`
603 // other architectures? otherwise some sort of nop...
604 }
605 }
606 }
607 else version (GNU)
608 {
609 import gcc.builtins;
610 import gcc.config;
611
612 enum IsAtomicLockFree(T) = __traits(compiles, { enum E = __atomic_is_lock_free(T.sizeof, null); });
613
614 inout(T) atomicLoad(MemoryOrder order = MemoryOrder.seq, T)(inout(T)* src) pure nothrow @nogc @trusted
615 if (CanCAS!T)
616 {
617 static assert(order != MemoryOrder.rel && order != MemoryOrder.acq_rel,
618 "invalid MemoryOrder for atomicLoad()");
619
620 static if (GNU_Have_Atomics || GNU_Have_LibAtomic)
621 {
622 static if (T.sizeof == ubyte.sizeof)
623 {
624 ubyte value = __atomic_load_1(cast(shared)src, order);
625 return *cast(typeof(return)*)&value;
626 }
627 else static if (T.sizeof == ushort.sizeof)
628 {
629 ushort value = __atomic_load_2(cast(shared)src, order);
630 return *cast(typeof(return)*)&value;
631 }
632 else static if (T.sizeof == uint.sizeof)
633 {
634 uint value = __atomic_load_4(cast(shared)src, order);
635 return *cast(typeof(return)*)&value;
636 }
637 else static if (T.sizeof == ulong.sizeof && GNU_Have_64Bit_Atomics)
638 {
639 ulong value = __atomic_load_8(cast(shared)src, order);
640 return *cast(typeof(return)*)&value;
641 }
642 else static if (GNU_Have_LibAtomic)
643 {
644 T value;
645 __atomic_load(T.sizeof, cast(shared)src, cast(void*)&value, order);
646 return *cast(typeof(return)*)&value;
647 }
648 else
649 static assert(0, "Invalid template type specified.");
650 }
651 else
652 {
653 getAtomicMutex.lock();
654 scope(exit) getAtomicMutex.unlock();
655 return *cast(typeof(return)*)&src;
656 }
657 }
658
659 void atomicStore(MemoryOrder order = MemoryOrder.seq, T)(T* dest, T value) pure nothrow @nogc @trusted
660 if (CanCAS!T)
661 {
662 static assert(order != MemoryOrder.acq && order != MemoryOrder.acq_rel,
663 "Invalid MemoryOrder for atomicStore()");
664
665 static if (GNU_Have_Atomics || GNU_Have_LibAtomic)
666 {
667 static if (T.sizeof == ubyte.sizeof)
668 __atomic_store_1(cast(shared)dest, *cast(ubyte*)&value, order);
669 else static if (T.sizeof == ushort.sizeof)
670 __atomic_store_2(cast(shared)dest, *cast(ushort*)&value, order);
671 else static if (T.sizeof == uint.sizeof)
672 __atomic_store_4(cast(shared)dest, *cast(uint*)&value, order);
673 else static if (T.sizeof == ulong.sizeof && GNU_Have_64Bit_Atomics)
674 __atomic_store_8(cast(shared)dest, *cast(ulong*)&value, order);
675 else static if (GNU_Have_LibAtomic)
676 __atomic_store(T.sizeof, cast(shared)dest, cast(void*)&value, order);
677 else
678 static assert(0, "Invalid template type specified.");
679 }
680 else
681 {
682 getAtomicMutex.lock();
683 *dest = value;
684 getAtomicMutex.unlock();
685 }
686 }
687
688 T atomicFetchAdd(MemoryOrder order = MemoryOrder.seq, bool result = true, T)(T* dest, T value) pure nothrow @nogc @trusted
689 if (is(T : ulong))
690 {
691 static if (GNU_Have_Atomics || GNU_Have_LibAtomic)
692 {
693 static if (T.sizeof == ubyte.sizeof)
694 return __atomic_fetch_add_1(cast(shared)dest, value, order);
695 else static if (T.sizeof == ushort.sizeof)
696 return __atomic_fetch_add_2(cast(shared)dest, value, order);
697 else static if (T.sizeof == uint.sizeof)
698 return __atomic_fetch_add_4(cast(shared)dest, value, order);
699 else static if (T.sizeof == ulong.sizeof && GNU_Have_64Bit_Atomics)
700 return __atomic_fetch_add_8(cast(shared)dest, value, order);
701 else static if (GNU_Have_LibAtomic)
702 return __atomic_fetch_add(T.sizeof, cast(shared)dest, cast(void*)&value, order);
703 else
704 static assert(0, "Invalid template type specified.");
705 }
706 else
707 {
708 getAtomicMutex.lock();
709 scope(exit) getAtomicMutex.unlock();
710 T tmp = *dest;
711 *dest += value;
712 return tmp;
713 }
714 }
715
716 T atomicFetchSub(MemoryOrder order = MemoryOrder.seq, bool result = true, T)(T* dest, T value) pure nothrow @nogc @trusted
717 if (is(T : ulong))
718 {
719 static if (GNU_Have_Atomics || GNU_Have_LibAtomic)
720 {
721 static if (T.sizeof == ubyte.sizeof)
722 return __atomic_fetch_sub_1(cast(shared)dest, value, order);
723 else static if (T.sizeof == ushort.sizeof)
724 return __atomic_fetch_sub_2(cast(shared)dest, value, order);
725 else static if (T.sizeof == uint.sizeof)
726 return __atomic_fetch_sub_4(cast(shared)dest, value, order);
727 else static if (T.sizeof == ulong.sizeof && GNU_Have_64Bit_Atomics)
728 return __atomic_fetch_sub_8(cast(shared)dest, value, order);
729 else static if (GNU_Have_LibAtomic)
730 return __atomic_fetch_sub(T.sizeof, cast(shared)dest, cast(void*)&value, order);
731 else
732 static assert(0, "Invalid template type specified.");
733 }
734 else
735 {
736 getAtomicMutex.lock();
737 scope(exit) getAtomicMutex.unlock();
738 T tmp = *dest;
739 *dest -= value;
740 return tmp;
741 }
742 }
743
744 T atomicExchange(MemoryOrder order = MemoryOrder.seq, bool result = true, T)(T* dest, T value) pure nothrow @nogc @trusted
745 if (CanCAS!T)
746 {
747 static assert(order != MemoryOrder.acq, "Invalid MemoryOrder for atomicExchange()");
748
749 static if (GNU_Have_Atomics || GNU_Have_LibAtomic)
750 {
751 static if (T.sizeof == byte.sizeof)
752 {
753 ubyte res = __atomic_exchange_1(cast(shared)dest, *cast(ubyte*)&value, order);
754 return *cast(typeof(return)*)&res;
755 }
756 else static if (T.sizeof == short.sizeof)
757 {
758 ushort res = __atomic_exchange_2(cast(shared)dest, *cast(ushort*)&value, order);
759 return *cast(typeof(return)*)&res;
760 }
761 else static if (T.sizeof == int.sizeof)
762 {
763 uint res = __atomic_exchange_4(cast(shared)dest, *cast(uint*)&value, order);
764 return *cast(typeof(return)*)&res;
765 }
766 else static if (T.sizeof == long.sizeof && GNU_Have_64Bit_Atomics)
767 {
768 ulong res = __atomic_exchange_8(cast(shared)dest, *cast(ulong*)&value, order);
769 return *cast(typeof(return)*)&res;
770 }
771 else static if (GNU_Have_LibAtomic)
772 {
773 T res = void;
774 __atomic_exchange(T.sizeof, cast(shared)dest, cast(void*)&value, &res, order);
775 return res;
776 }
777 else
778 static assert(0, "Invalid template type specified.");
779 }
780 else
781 {
782 getAtomicMutex.lock();
783 scope(exit) getAtomicMutex.unlock();
784
785 T res = *dest;
786 *dest = value;
787 return res;
788 }
789 }
790
791 bool atomicCompareExchangeWeak(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T)(T* dest, T* compare, T value) pure nothrow @nogc @trusted
792 if (CanCAS!T)
793 {
794 return atomicCompareExchangeImpl!(succ, fail, true)(dest, compare, value);
795 }
796
797 bool atomicCompareExchangeStrong(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T)(T* dest, T* compare, T value) pure nothrow @nogc @trusted
798 if (CanCAS!T)
799 {
800 return atomicCompareExchangeImpl!(succ, fail, false)(dest, compare, value);
801 }
802
803 bool atomicCompareExchangeStrongNoResult(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T)(T* dest, const T compare, T value) pure nothrow @nogc @trusted
804 if (CanCAS!T)
805 {
806 return atomicCompareExchangeImpl!(succ, fail, false)(dest, cast(T*)&compare, value);
807 }
808
809 bool atomicCompareExchangeWeakNoResult(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, T)(T* dest, const T compare, T value) pure nothrow @nogc @trusted
810 if (CanCAS!T)
811 {
812 return atomicCompareExchangeImpl!(succ, fail, true)(dest, cast(T*)&compare, value);
813 }
814
815 private bool atomicCompareExchangeImpl(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq, bool weak, T)(T* dest, T* compare, T value) pure nothrow @nogc @trusted
816 if (CanCAS!T)
817 {
818 static assert(fail != MemoryOrder.rel && fail != MemoryOrder.acq_rel,
819 "Invalid fail MemoryOrder for atomicCompareExchange()");
820 static assert (succ >= fail, "The first MemoryOrder argument for atomicCompareExchange() cannot be weaker than the second argument");
821
822 bool res = void;
823
824 static if (GNU_Have_Atomics || GNU_Have_LibAtomic)
825 {
826 static if (T.sizeof == byte.sizeof)
827 res = __atomic_compare_exchange_1(cast(shared)dest, compare, *cast(ubyte*)&value,
828 weak, succ, fail);
829 else static if (T.sizeof == short.sizeof)
830 res = __atomic_compare_exchange_2(cast(shared)dest, compare, *cast(ushort*)&value,
831 weak, succ, fail);
832 else static if (T.sizeof == int.sizeof)
833 res = __atomic_compare_exchange_4(cast(shared)dest, compare, *cast(uint*)&value,
834 weak, succ, fail);
835 else static if (T.sizeof == long.sizeof && GNU_Have_64Bit_Atomics)
836 res = __atomic_compare_exchange_8(cast(shared)dest, compare, *cast(ulong*)&value,
837 weak, succ, fail);
838 else static if (GNU_Have_LibAtomic)
839 res = __atomic_compare_exchange(T.sizeof, cast(shared)dest, compare, cast(void*)&value,
840 succ, fail);
841 else
842 static assert(0, "Invalid template type specified.");
843 }
844 else
845 {
846 static if (T.sizeof == byte.sizeof)
847 alias U = byte;
848 else static if (T.sizeof == short.sizeof)
849 alias U = short;
850 else static if (T.sizeof == int.sizeof)
851 alias U = int;
852 else static if (T.sizeof == long.sizeof)
853 alias U = long;
854 else
855 static assert(0, "Invalid template type specified.");
856
857 getAtomicMutex.lock();
858 scope(exit) getAtomicMutex.unlock();
859
860 if (*cast(U*)dest == *cast(U*)&compare)
861 {
862 *dest = value;
863 res = true;
864 }
865 else
866 {
867 *compare = *dest;
868 res = false;
869 }
870 }
871
872 return res;
873 }
874
875 void atomicFence(MemoryOrder order = MemoryOrder.seq)() pure nothrow @nogc @trusted
876 {
877 static if (GNU_Have_Atomics || GNU_Have_LibAtomic)
878 __atomic_thread_fence(order);
879 else
880 {
881 getAtomicMutex.lock();
882 getAtomicMutex.unlock();
883 }
884 }
885
886 void atomicSignalFence(MemoryOrder order = MemoryOrder.seq)() pure nothrow @nogc @trusted
887 {
888 __atomic_signal_fence(order);
889 }
890
891 void pause() pure nothrow @nogc @trusted
892 {
893 version (X86)
894 {
895 __builtin_ia32_pause();
896 }
897 else version (X86_64)
898 {
899 __builtin_ia32_pause();
900 }
901 else
902 {
903 // Other architectures? Some sort of nop or barrier.
904 }
905 }
906
907 static if (!GNU_Have_Atomics && !GNU_Have_LibAtomic)
908 {
909 // Use system mutex for atomics, faking the purity of the functions so
910 // that they can be used in pure/nothrow/@safe code.
911 extern (C) private pure @trusted @nogc nothrow
912 {
913 static if (GNU_Thread_Model == ThreadModel.Posix)
914 {
915 import core.sys.posix.sys.types : pthread_mutex_t, pthread_mutexattr_t;
916 alias atomicMutexHandle = pthread_mutex_t;
917
918 pragma(mangle, "pthread_mutex_init") int fakePureMutexInit(pthread_mutex_t*, pthread_mutexattr_t*);
919 pragma(mangle, "pthread_mutex_lock") int fakePureMutexLock(pthread_mutex_t*);
920 pragma(mangle, "pthread_mutex_unlock") int fakePureMutexUnlock(pthread_mutex_t*);
921 }
922 else static if (GNU_Thread_Model == ThreadModel.Win32)
923 {
924 import core.sys.windows.winbase : CRITICAL_SECTION;
925 alias atomicMutexHandle = CRITICAL_SECTION;
926
927 pragma(mangle, "InitializeCriticalSection") int fakePureMutexInit(CRITICAL_SECTION*);
928 pragma(mangle, "EnterCriticalSection") void fakePureMutexLock(CRITICAL_SECTION*);
929 pragma(mangle, "LeaveCriticalSection") int fakePureMutexUnlock(CRITICAL_SECTION*);
930 }
931 else
932 {
933 alias atomicMutexHandle = int;
934 }
935 }
936
937 // Implements lock/unlock operations.
938 private struct AtomicMutex
939 {
940 int lock() pure @trusted @nogc nothrow
941 {
942 static if (GNU_Thread_Model == ThreadModel.Posix)
943 {
944 if (!_inited)
945 {
946 fakePureMutexInit(&_handle, null);
947 _inited = true;
948 }
949 return fakePureMutexLock(&_handle);
950 }
951 else
952 {
953 static if (GNU_Thread_Model == ThreadModel.Win32)
954 {
955 if (!_inited)
956 {
957 fakePureMutexInit(&_handle);
958 _inited = true;
959 }
960 fakePureMutexLock(&_handle);
961 }
962 return 0;
963 }
964 }
965
966 int unlock() pure @trusted @nogc nothrow
967 {
968 static if (GNU_Thread_Model == ThreadModel.Posix)
969 return fakePureMutexUnlock(&_handle);
970 else
971 {
972 static if (GNU_Thread_Model == ThreadModel.Win32)
973 fakePureMutexUnlock(&_handle);
974 return 0;
975 }
976 }
977
978 private:
979 atomicMutexHandle _handle;
980 bool _inited;
981 }
982
983 // Internal static mutex reference.
984 private AtomicMutex* _getAtomicMutex() @trusted @nogc nothrow
985 {
986 __gshared AtomicMutex mutex;
987 return &mutex;
988 }
989
990 // Pure alias for _getAtomicMutex.
991 pragma(mangle, _getAtomicMutex.mangleof)
992 private AtomicMutex* getAtomicMutex() pure @trusted @nogc nothrow @property;
993 }
994 }
995
996 private:
997
998 version (Windows)
999 {
1000 enum RegisterReturn(T) = is(T : U[], U) || is(T : R delegate(A), R, A...);
1001 }
1002
1003 enum CanCAS(T) = (__traits(isScalar, T) && // check to see if it is some kind of basic type like an integer/float/pointer
1004 T.sizeof <= size_t.sizeof * 2) || // make sure if it is, that it is no more than 2 words
1005 is(T == class) ||
1006 is(T == interface) ||
1007 is(T : U[], U) ||
1008 is(T : R delegate(A), R, A...) ||
1009 (is(T == struct) && __traits(isPOD, T) &&
1010 (T.sizeof <= size_t.sizeof*2 || // no more than 2 words
1011 (T.sizeof == 16 && has128BitCAS)) && // or supports 128-bit CAS
1012 (T.sizeof & (T.sizeof - 1)) == 0 // is power of 2
1013 );
1014
1015 template IntOrLong(T)
1016 {
1017 static if (T.sizeof > 4)
1018 alias IntOrLong = long;
1019 else
1020 alias IntOrLong = int;
1021 }
1022
1023 // NOTE: x86 loads implicitly have acquire semantics so a memory
1024 // barrier is only necessary on releases.
1025 template needsLoadBarrier( MemoryOrder ms )
1026 {
1027 enum bool needsLoadBarrier = ms == MemoryOrder.seq;
1028 }
1029
1030
1031 // NOTE: x86 stores implicitly have release semantics so a memory
1032 // barrier is only necessary on acquires.
1033 template needsStoreBarrier( MemoryOrder ms )
1034 {
1035 enum bool needsStoreBarrier = ms == MemoryOrder.seq;
1036 }
1037
1038 // this is a helper to build asm blocks
1039 string simpleFormat(string format, scope string[] args)
1040 {
1041 string result;
1042 outer: while (format.length)
1043 {
1044 foreach (i; 0 .. format.length)
1045 {
1046 if (format[i] == '%' || format[i] == '?')
1047 {
1048 bool isQ = format[i] == '?';
1049 result ~= format[0 .. i++];
1050 assert (i < format.length, "Invalid format string");
1051 if (format[i] == '%' || format[i] == '?')
1052 {
1053 assert(!isQ, "Invalid format string");
1054 result ~= format[i++];
1055 }
1056 else
1057 {
1058 int index = 0;
1059 assert (format[i] >= '0' && format[i] <= '9', "Invalid format string");
1060 while (i < format.length && format[i] >= '0' && format[i] <= '9')
1061 index = index * 10 + (ubyte(format[i++]) - ubyte('0'));
1062 if (!isQ)
1063 result ~= args[index];
1064 else if (!args[index])
1065 {
1066 size_t j = i;
1067 for (; j < format.length;)
1068 {
1069 if (format[j++] == '\n')
1070 break;
1071 }
1072 i = j;
1073 }
1074 }
1075 format = format[i .. $];
1076 continue outer;
1077 }
1078 }
1079 result ~= format;
1080 break;
1081 }
1082 return result;
1083 }