Don't #include OSAtomic.h unless we really need it.
[oota-llvm.git] / include / llvm / System / Atomic.h
1 //===- llvm/System/Atomic.h - Atomic Operations -----------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the llvm::sys atomic operations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_SYSTEM_ATOMIC_H
15 #define LLVM_SYSTEM_ATOMIC_H
16
17 #include "llvm/Config/config.h"
18 #include <stdint.h>
19
20 #if defined(__APPLE__)
21 #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ == 0)
22 #include <libkern/OSAtomic.h>
23 #endif
24 #elif LLVM_ON_WIN32
25 #include <windows.h>
26 #endif
27
28
29 namespace llvm {
30   namespace sys {
31     
32 #if !defined(ENABLE_THREADS) || ENABLE_THREADS == 0
33     inline void MemoryFence() {
34       return;
35     }
36     
37     typedef uint32_t cas_flag;
38     inline cas_flag CompareAndSwap(cas_flag* dest, cas_flag exc, cas_flag c) {
39       cas_flag result = *dest;
40       if (result == c)
41         *dest = exc;
42       return result;
43     }
44     
45 #elif __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
46     inline void MemoryFence() {
47       __sync_synchronize();
48     }
49     
50     typedef volatile uint32_t cas_flag;
51     inline cas_flag CompareAndSwap(cas_flag* dest, cas_flag exc, cas_flag c) {
52       return __sync_val_compare_and_swap(dest, exc, c);
53     }
54     
55 #elif defined(__APPLE__)
56     inline void MemoryFence() {
57       OSMemoryBarrier();
58     }
59     
60     typedef volatile int32_t cas_flag;
61     inline cas_flag CompareAndSwap(cas_flag* dest, cas_flag exc, cas_flag c) {
62       cas_flag old = *dest;
63       OSAtomicCompareAndSwap32(c, exc, dest);
64       return old;
65     }
66 #elif defined(LLVM_ON_WIN32)
67 #warning Memory fence implementation requires Windows 2003 or later.
68     inline void MemoryFence() {
69       MemoryBarrier();
70     }
71     
72     typedef volatile long cas_flag;
73     inline cas_flag CompareAndSwap(cas_flag* dest, cas_flag exc, cas_flag c) {
74       return _InterlockedCompareExchange(dest, exc, c);
75     }
76 #else
77 #error No memory atomics implementation for your platform!
78 #endif
79     
80   }
81 }
82
83 #endif