LLVMContextImpl.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. //===- LLVMContextImpl.cpp - Implement LLVMContextImpl --------------------===//
  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 opaque LLVMContextImpl.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "LLVMContextImpl.h"
  13. #include "AttributeImpl.h"
  14. #include "llvm/ADT/SetVector.h"
  15. #include "llvm/ADT/StringMapEntry.h"
  16. #include "llvm/ADT/iterator.h"
  17. #include "llvm/ADT/iterator_range.h"
  18. #include "llvm/IR/DiagnosticHandler.h"
  19. #include "llvm/IR/LLVMRemarkStreamer.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/IR/OptBisect.h"
  22. #include "llvm/IR/Type.h"
  23. #include "llvm/IR/Use.h"
  24. #include "llvm/IR/User.h"
  25. #include "llvm/Remarks/RemarkStreamer.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Compiler.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/TypeSize.h"
  30. #include <cassert>
  31. #include <utility>
  32. using namespace llvm;
  33. static cl::opt<bool>
  34. OpaquePointersCL("opaque-pointers", cl::desc("Use opaque pointers"),
  35. cl::init(true));
  36. LLVMContextImpl::LLVMContextImpl(LLVMContext &C)
  37. : DiagHandler(std::make_unique<DiagnosticHandler>()),
  38. VoidTy(C, Type::VoidTyID), LabelTy(C, Type::LabelTyID),
  39. HalfTy(C, Type::HalfTyID), BFloatTy(C, Type::BFloatTyID),
  40. FloatTy(C, Type::FloatTyID), DoubleTy(C, Type::DoubleTyID),
  41. MetadataTy(C, Type::MetadataTyID), TokenTy(C, Type::TokenTyID),
  42. X86_FP80Ty(C, Type::X86_FP80TyID), FP128Ty(C, Type::FP128TyID),
  43. PPC_FP128Ty(C, Type::PPC_FP128TyID), X86_MMXTy(C, Type::X86_MMXTyID),
  44. X86_AMXTy(C, Type::X86_AMXTyID), Int1Ty(C, 1), Int8Ty(C, 8),
  45. Int16Ty(C, 16), Int32Ty(C, 32), Int64Ty(C, 64), Int128Ty(C, 128) {
  46. if (OpaquePointersCL.getNumOccurrences()) {
  47. OpaquePointers = OpaquePointersCL;
  48. }
  49. }
  50. LLVMContextImpl::~LLVMContextImpl() {
  51. // NOTE: We need to delete the contents of OwnedModules, but Module's dtor
  52. // will call LLVMContextImpl::removeModule, thus invalidating iterators into
  53. // the container. Avoid iterators during this operation:
  54. while (!OwnedModules.empty())
  55. delete *OwnedModules.begin();
  56. #ifndef NDEBUG
  57. // Check for metadata references from leaked Values.
  58. for (auto &Pair : ValueMetadata)
  59. Pair.first->dump();
  60. assert(ValueMetadata.empty() && "Values with metadata have been leaked");
  61. #endif
  62. // Drop references for MDNodes. Do this before Values get deleted to avoid
  63. // unnecessary RAUW when nodes are still unresolved.
  64. for (auto *I : DistinctMDNodes) {
  65. // We may have DIArgList that were uniqued, and as it has a custom
  66. // implementation of dropAllReferences, it needs to be explicitly invoked.
  67. if (auto *AL = dyn_cast<DIArgList>(I)) {
  68. AL->dropAllReferences();
  69. continue;
  70. }
  71. I->dropAllReferences();
  72. }
  73. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  74. for (auto *I : CLASS##s) \
  75. I->dropAllReferences();
  76. #include "llvm/IR/Metadata.def"
  77. // Also drop references that come from the Value bridges.
  78. for (auto &Pair : ValuesAsMetadata)
  79. Pair.second->dropUsers();
  80. for (auto &Pair : MetadataAsValues)
  81. Pair.second->dropUse();
  82. // Destroy MDNodes.
  83. for (MDNode *I : DistinctMDNodes)
  84. I->deleteAsSubclass();
  85. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  86. for (CLASS * I : CLASS##s) \
  87. delete I;
  88. #include "llvm/IR/Metadata.def"
  89. // Free the constants.
  90. for (auto *I : ExprConstants)
  91. I->dropAllReferences();
  92. for (auto *I : ArrayConstants)
  93. I->dropAllReferences();
  94. for (auto *I : StructConstants)
  95. I->dropAllReferences();
  96. for (auto *I : VectorConstants)
  97. I->dropAllReferences();
  98. ExprConstants.freeConstants();
  99. ArrayConstants.freeConstants();
  100. StructConstants.freeConstants();
  101. VectorConstants.freeConstants();
  102. InlineAsms.freeConstants();
  103. CAZConstants.clear();
  104. CPNConstants.clear();
  105. CTNConstants.clear();
  106. UVConstants.clear();
  107. PVConstants.clear();
  108. IntConstants.clear();
  109. FPConstants.clear();
  110. CDSConstants.clear();
  111. // Destroy attribute node lists.
  112. for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
  113. E = AttrsSetNodes.end(); I != E; ) {
  114. FoldingSetIterator<AttributeSetNode> Elem = I++;
  115. delete &*Elem;
  116. }
  117. // Destroy MetadataAsValues.
  118. {
  119. SmallVector<MetadataAsValue *, 8> MDVs;
  120. MDVs.reserve(MetadataAsValues.size());
  121. for (auto &Pair : MetadataAsValues)
  122. MDVs.push_back(Pair.second);
  123. MetadataAsValues.clear();
  124. for (auto *V : MDVs)
  125. delete V;
  126. }
  127. // Destroy ValuesAsMetadata.
  128. for (auto &Pair : ValuesAsMetadata)
  129. delete Pair.second;
  130. }
  131. void LLVMContextImpl::dropTriviallyDeadConstantArrays() {
  132. SmallSetVector<ConstantArray *, 4> WorkList;
  133. // When ArrayConstants are of substantial size and only a few in them are
  134. // dead, starting WorkList with all elements of ArrayConstants can be
  135. // wasteful. Instead, starting WorkList with only elements that have empty
  136. // uses.
  137. for (ConstantArray *C : ArrayConstants)
  138. if (C->use_empty())
  139. WorkList.insert(C);
  140. while (!WorkList.empty()) {
  141. ConstantArray *C = WorkList.pop_back_val();
  142. if (C->use_empty()) {
  143. for (const Use &Op : C->operands()) {
  144. if (auto *COp = dyn_cast<ConstantArray>(Op))
  145. WorkList.insert(COp);
  146. }
  147. C->destroyConstant();
  148. }
  149. }
  150. }
  151. void Module::dropTriviallyDeadConstantArrays() {
  152. Context.pImpl->dropTriviallyDeadConstantArrays();
  153. }
  154. namespace llvm {
  155. /// Make MDOperand transparent for hashing.
  156. ///
  157. /// This overload of an implementation detail of the hashing library makes
  158. /// MDOperand hash to the same value as a \a Metadata pointer.
  159. ///
  160. /// Note that overloading \a hash_value() as follows:
  161. ///
  162. /// \code
  163. /// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
  164. /// \endcode
  165. ///
  166. /// does not cause MDOperand to be transparent. In particular, a bare pointer
  167. /// doesn't get hashed before it's combined, whereas \a MDOperand would.
  168. static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
  169. } // end namespace llvm
  170. unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
  171. unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
  172. #ifndef NDEBUG
  173. {
  174. SmallVector<Metadata *, 8> MDs(drop_begin(N->operands(), Offset));
  175. unsigned RawHash = calculateHash(MDs);
  176. assert(Hash == RawHash &&
  177. "Expected hash of MDOperand to equal hash of Metadata*");
  178. }
  179. #endif
  180. return Hash;
  181. }
  182. unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
  183. return hash_combine_range(Ops.begin(), Ops.end());
  184. }
  185. StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
  186. uint32_t NewIdx = BundleTagCache.size();
  187. return &*(BundleTagCache.insert(std::make_pair(Tag, NewIdx)).first);
  188. }
  189. void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
  190. Tags.resize(BundleTagCache.size());
  191. for (const auto &T : BundleTagCache)
  192. Tags[T.second] = T.first();
  193. }
  194. uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
  195. auto I = BundleTagCache.find(Tag);
  196. assert(I != BundleTagCache.end() && "Unknown tag!");
  197. return I->second;
  198. }
  199. SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
  200. auto NewSSID = SSC.size();
  201. assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
  202. "Hit the maximum number of synchronization scopes allowed!");
  203. return SSC.insert(std::make_pair(SSN, SyncScope::ID(NewSSID))).first->second;
  204. }
  205. void LLVMContextImpl::getSyncScopeNames(
  206. SmallVectorImpl<StringRef> &SSNs) const {
  207. SSNs.resize(SSC.size());
  208. for (const auto &SSE : SSC)
  209. SSNs[SSE.second] = SSE.first();
  210. }
  211. /// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
  212. /// singleton OptBisect if not explicitly set.
  213. OptPassGate &LLVMContextImpl::getOptPassGate() const {
  214. if (!OPG)
  215. OPG = &getGlobalPassGate();
  216. return *OPG;
  217. }
  218. void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
  219. this->OPG = &OPG;
  220. }
  221. bool LLVMContextImpl::getOpaquePointers() {
  222. if (LLVM_UNLIKELY(!OpaquePointers))
  223. OpaquePointers = OpaquePointersCL;
  224. return *OpaquePointers;
  225. }
  226. void LLVMContextImpl::setOpaquePointers(bool OP) {
  227. assert((!OpaquePointers || *OpaquePointers == OP) &&
  228. "Cannot change opaque pointers mode once set");
  229. OpaquePointers = OP;
  230. }