1 //===-- llvm/Support/ManagedStatic.h - Static Global wrapper ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ManagedStatic class and the llvm_shutdown() function.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_MANAGED_STATIC_H
15 #define LLVM_SUPPORT_MANAGED_STATIC_H
17 #include "llvm/System/Atomic.h"
21 /// object_creator - Helper method for ManagedStatic.
23 void* object_creator() {
27 /// object_deleter - Helper method for ManagedStatic.
30 void object_deleter(void *Ptr) {
34 /// ManagedStaticBase - Common base class for ManagedStatic instances.
35 class ManagedStaticBase {
37 // This should only be used as a static variable, which guarantees that this
38 // will be zero initialized.
40 mutable void (*DeleterFn)(void*);
41 mutable const ManagedStaticBase *Next;
43 void RegisterManagedStatic(void *(*creator)(), void (*deleter)(void*)) const;
45 /// isConstructed - Return true if this object has not been created yet.
46 bool isConstructed() const { return Ptr != 0; }
51 /// ManagedStatic - This transparently changes the behavior of global statics to
52 /// be lazily constructed on demand (good for reducing startup times of dynamic
53 /// libraries that link in LLVM components) and for making destruction be
54 /// explicit through the llvm_shutdown() function call.
57 class ManagedStatic : public ManagedStaticBase {
64 if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>);
66 return *static_cast<C*>(Ptr);
71 if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>);
73 return static_cast<C*>(Ptr);
75 const C &operator*() const {
78 if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>);
80 return *static_cast<C*>(Ptr);
82 const C *operator->() const {
85 if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>);
87 return static_cast<C*>(Ptr);
91 template<void (*CleanupFn)(void*)>
92 class ManagedCleanup : public ManagedStaticBase {
94 void Register() { RegisterManagedStatic(0, CleanupFn); }
98 /// llvm_start_multithreaded - Allocate and initialize structures needed to
99 /// make LLVM safe for multithreading.
100 void llvm_start_multithreaded();
102 /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
103 void llvm_shutdown();
106 /// llvm_shutdown_obj - This is a simple helper class that calls
107 /// llvm_shutdown() when it is destroyed.
108 struct llvm_shutdown_obj {
109 llvm_shutdown_obj() { }
110 explicit llvm_shutdown_obj(bool multithreaded) {
111 if (multithreaded) llvm_start_multithreaded();
113 ~llvm_shutdown_obj() { llvm_shutdown(); }