ManagedStatic.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //===-- ManagedStatic.cpp - Static Global wrapper -------------------------===//
  2. //
  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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the ManagedStatic class and llvm_shutdown().
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Support/ManagedStatic.h"
  13. #include "llvm/Config/config.h"
  14. #include "llvm/Support/Threading.h"
  15. #include <cassert>
  16. #include <mutex>
  17. using namespace llvm;
  18. static const ManagedStaticBase *StaticList = nullptr;
  19. static std::recursive_mutex *getManagedStaticMutex() {
  20. static std::recursive_mutex m;
  21. return &m;
  22. }
  23. void ManagedStaticBase::RegisterManagedStatic(void *(*Creator)(),
  24. void (*Deleter)(void*)) const {
  25. assert(Creator);
  26. if (llvm_is_multithreaded()) {
  27. std::lock_guard<std::recursive_mutex> Lock(*getManagedStaticMutex());
  28. if (!Ptr.load(std::memory_order_relaxed)) {
  29. void *Tmp = Creator();
  30. Ptr.store(Tmp, std::memory_order_release);
  31. DeleterFn = Deleter;
  32. // Add to list of managed statics.
  33. Next = StaticList;
  34. StaticList = this;
  35. }
  36. } else {
  37. assert(!Ptr && !DeleterFn && !Next &&
  38. "Partially initialized ManagedStatic!?");
  39. Ptr = Creator();
  40. DeleterFn = Deleter;
  41. // Add to list of managed statics.
  42. Next = StaticList;
  43. StaticList = this;
  44. }
  45. }
  46. void ManagedStaticBase::destroy() const {
  47. assert(DeleterFn && "ManagedStatic not initialized correctly!");
  48. assert(StaticList == this &&
  49. "Not destroyed in reverse order of construction?");
  50. // Unlink from list.
  51. StaticList = Next;
  52. Next = nullptr;
  53. // Destroy memory.
  54. DeleterFn(Ptr);
  55. // Cleanup.
  56. Ptr = nullptr;
  57. DeleterFn = nullptr;
  58. }
  59. /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
  60. /// IMPORTANT: it's only safe to call llvm_shutdown() in single thread,
  61. /// without any other threads executing LLVM APIs.
  62. /// llvm_shutdown() should be the last use of LLVM APIs.
  63. void llvm::llvm_shutdown() {
  64. while (StaticList)
  65. StaticList->destroy();
  66. }