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