Have llvm_start_multithreaded return a bool indicating whether multithreaded
[oota-llvm.git] / lib / Support / ManagedStatic.cpp
1 //===-- ManagedStatic.cpp - Static Global wrapper -------------------------===//
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 implements the ManagedStatic class and llvm_shutdown().
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/ManagedStatic.h"
15 #include "llvm/Config/config.h"
16 #include "llvm/System/Atomic.h"
17 #include "llvm/System/Mutex.h"
18 #include <cassert>
19 using namespace llvm;
20
21 static const ManagedStaticBase *StaticList = 0;
22
23 static sys::Mutex* ManagedStaticMutex = 0;
24
25 void ManagedStaticBase::RegisterManagedStatic(void *(*Creator)(),
26                                               void (*Deleter)(void*)) const {
27   if (ManagedStaticMutex) {
28     ManagedStaticMutex->acquire();
29
30     if (Ptr == 0) {
31       void* tmp = Creator ? Creator() : 0;
32
33       sys::MemoryFence();
34       Ptr = tmp;
35       DeleterFn = Deleter;
36       
37       // Add to list of managed statics.
38       Next = StaticList;
39       StaticList = this;
40     }
41
42     ManagedStaticMutex->release();
43   } else {
44     assert(Ptr == 0 && DeleterFn == 0 && Next == 0 &&
45            "Partially initialized ManagedStatic!?");
46     Ptr = Creator ? Creator() : 0;
47     DeleterFn = Deleter;
48   
49     // Add to list of managed statics.
50     Next = StaticList;
51     StaticList = this;
52   }
53 }
54
55 void ManagedStaticBase::destroy() const {
56   assert(DeleterFn && "ManagedStatic not initialized correctly!");
57   assert(StaticList == this &&
58          "Not destroyed in reverse order of construction?");
59   // Unlink from list.
60   StaticList = Next;
61   Next = 0;
62
63   // Destroy memory.
64   DeleterFn(Ptr);
65   
66   // Cleanup.
67   Ptr = 0;
68   DeleterFn = 0;
69 }
70
71 bool llvm::llvm_start_multithreaded() {
72 #if LLVM_MULTITHREADED
73   assert(ManagedStaticMutex == 0 && "Multithreaded LLVM already initialized!");
74   ManagedStaticMutex = new sys::Mutex(true);
75   return true;
76 #else
77   return false;
78 #endif
79 }
80
81 /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
82 void llvm::llvm_shutdown() {
83   while (StaticList)
84     StaticList->destroy();
85
86   if (ManagedStaticMutex) {
87     delete ManagedStaticMutex;
88     ManagedStaticMutex = 0;
89   }
90 }
91