1 //===-- ManagedStatic.cpp - Static Global wrapper -------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the ManagedStatic class and llvm_shutdown().
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/ManagedStatic.h"
14 #include "llvm/Config/config.h"
15 #include "llvm/Support/Mutex.h"
16 #include "llvm/Support/MutexGuard.h"
17 #include "llvm/Support/Threading.h"
21 static const ManagedStaticBase
*StaticList
= nullptr;
22 static sys::Mutex
*ManagedStaticMutex
= nullptr;
23 static llvm::once_flag mutex_init_flag
;
25 static void initializeMutex() {
26 ManagedStaticMutex
= new sys::Mutex();
29 static sys::Mutex
* getManagedStaticMutex() {
30 llvm::call_once(mutex_init_flag
, initializeMutex
);
31 return ManagedStaticMutex
;
34 void ManagedStaticBase::RegisterManagedStatic(void *(*Creator
)(),
35 void (*Deleter
)(void*)) const {
37 if (llvm_is_multithreaded()) {
38 MutexGuard
Lock(*getManagedStaticMutex());
40 if (!Ptr
.load(std::memory_order_relaxed
)) {
41 void *Tmp
= Creator();
43 Ptr
.store(Tmp
, std::memory_order_release
);
46 // Add to list of managed statics.
51 assert(!Ptr
&& !DeleterFn
&& !Next
&&
52 "Partially initialized ManagedStatic!?");
56 // Add to list of managed statics.
62 void ManagedStaticBase::destroy() const {
63 assert(DeleterFn
&& "ManagedStatic not initialized correctly!");
64 assert(StaticList
== this &&
65 "Not destroyed in reverse order of construction?");
78 /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
79 void llvm::llvm_shutdown() {
80 MutexGuard
Lock(*getManagedStaticMutex());
83 StaticList
->destroy();