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