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/Threading.h"
20 static const ManagedStaticBase
*StaticList
= nullptr;
21 static std::recursive_mutex
*ManagedStaticMutex
= nullptr;
22 static llvm::once_flag mutex_init_flag
;
24 static void initializeMutex() {
25 ManagedStaticMutex
= new std::recursive_mutex();
28 static std::recursive_mutex
*getManagedStaticMutex() {
29 llvm::call_once(mutex_init_flag
, initializeMutex
);
30 return ManagedStaticMutex
;
33 void ManagedStaticBase::RegisterManagedStatic(void *(*Creator
)(),
34 void (*Deleter
)(void*)) const {
36 if (llvm_is_multithreaded()) {
37 std::lock_guard
<std::recursive_mutex
> Lock(*getManagedStaticMutex());
39 if (!Ptr
.load(std::memory_order_relaxed
)) {
40 void *Tmp
= Creator();
42 Ptr
.store(Tmp
, std::memory_order_release
);
45 // Add to list of managed statics.
50 assert(!Ptr
&& !DeleterFn
&& !Next
&&
51 "Partially initialized ManagedStatic!?");
55 // Add to list of managed statics.
61 void ManagedStaticBase::destroy() const {
62 assert(DeleterFn
&& "ManagedStatic not initialized correctly!");
63 assert(StaticList
== this &&
64 "Not destroyed in reverse order of construction?");
77 /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
78 void llvm::llvm_shutdown() {
79 std::lock_guard
<std::recursive_mutex
> Lock(*getManagedStaticMutex());
82 StaticList
->destroy();