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