xref: /freebsd/contrib/llvm-project/llvm/lib/IR/LLVMContextImpl.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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/TypeSize.h"
31 #include <cassert>
32 #include <utility>
33 
34 using namespace llvm;
35 
LLVMContextImpl(LLVMContext & C)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 
~LLVMContextImpl()47 LLVMContextImpl::~LLVMContextImpl() {
48 #ifndef NDEBUG
49   // Check that any variable location records that fell off the end of a block
50   // when it's terminator was removed were eventually replaced. This assertion
51   // firing indicates that DbgVariableRecords went missing during the lifetime
52   // of the LLVMContext.
53   assert(TrailingDbgRecords.empty() && "DbgRecords in blocks not cleaned");
54 #endif
55 
56   // NOTE: We need to delete the contents of OwnedModules, but Module's dtor
57   // will call LLVMContextImpl::removeModule, thus invalidating iterators into
58   // the container. Avoid iterators during this operation:
59   while (!OwnedModules.empty())
60     delete *OwnedModules.begin();
61 
62 #ifndef NDEBUG
63   // Check for metadata references from leaked Values.
64   for (auto &Pair : ValueMetadata)
65     Pair.first->dump();
66   assert(ValueMetadata.empty() && "Values with metadata have been leaked");
67 #endif
68 
69   // Drop references for MDNodes.  Do this before Values get deleted to avoid
70   // unnecessary RAUW when nodes are still unresolved.
71   for (auto *I : DistinctMDNodes)
72     I->dropAllReferences();
73 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
74   for (auto *I : CLASS##s)                                                     \
75     I->dropAllReferences();
76 #include "llvm/IR/Metadata.def"
77 
78   // Also drop references that come from the Value bridges.
79   for (auto &Pair : ValuesAsMetadata)
80     Pair.second->dropUsers();
81   for (auto &Pair : MetadataAsValues)
82     Pair.second->dropUse();
83   // Do not untrack ValueAsMetadata references for DIArgLists, as they have
84   // already been more efficiently untracked above.
85   for (DIArgList *AL : DIArgLists) {
86     AL->dropAllReferences(/* Untrack */ false);
87     delete AL;
88   }
89   DIArgLists.clear();
90 
91   // Destroy MDNodes.
92   for (MDNode *I : DistinctMDNodes)
93     I->deleteAsSubclass();
94 
95   for (auto *ConstantRangeListAttribute : ConstantRangeListAttributes)
96     ConstantRangeListAttribute->~ConstantRangeListAttributeImpl();
97 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
98   for (CLASS * I : CLASS##s)                                                   \
99     delete I;
100 #include "llvm/IR/Metadata.def"
101 
102   // Free the constants.
103   for (auto *I : ExprConstants)
104     I->dropAllReferences();
105   for (auto *I : ArrayConstants)
106     I->dropAllReferences();
107   for (auto *I : StructConstants)
108     I->dropAllReferences();
109   for (auto *I : VectorConstants)
110     I->dropAllReferences();
111   ExprConstants.freeConstants();
112   ArrayConstants.freeConstants();
113   StructConstants.freeConstants();
114   VectorConstants.freeConstants();
115   InlineAsms.freeConstants();
116 
117   CAZConstants.clear();
118   CPNConstants.clear();
119   CTNConstants.clear();
120   UVConstants.clear();
121   PVConstants.clear();
122   IntZeroConstants.clear();
123   IntOneConstants.clear();
124   IntConstants.clear();
125   IntSplatConstants.clear();
126   FPConstants.clear();
127   FPSplatConstants.clear();
128   CDSConstants.clear();
129 
130   // Destroy attribute node lists.
131   for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
132          E = AttrsSetNodes.end(); I != E; ) {
133     FoldingSetIterator<AttributeSetNode> Elem = I++;
134     delete &*Elem;
135   }
136 
137   // Destroy MetadataAsValues.
138   {
139     SmallVector<MetadataAsValue *, 8> MDVs;
140     MDVs.reserve(MetadataAsValues.size());
141     for (auto &Pair : MetadataAsValues)
142       MDVs.push_back(Pair.second);
143     MetadataAsValues.clear();
144     for (auto *V : MDVs)
145       delete V;
146   }
147 
148   // Destroy ValuesAsMetadata.
149   for (auto &Pair : ValuesAsMetadata)
150     delete Pair.second;
151 }
152 
dropTriviallyDeadConstantArrays()153 void LLVMContextImpl::dropTriviallyDeadConstantArrays() {
154   SmallSetVector<ConstantArray *, 4> WorkList;
155 
156   // When ArrayConstants are of substantial size and only a few in them are
157   // dead, starting WorkList with all elements of ArrayConstants can be
158   // wasteful. Instead, starting WorkList with only elements that have empty
159   // uses.
160   for (ConstantArray *C : ArrayConstants)
161     if (C->use_empty())
162       WorkList.insert(C);
163 
164   while (!WorkList.empty()) {
165     ConstantArray *C = WorkList.pop_back_val();
166     if (C->use_empty()) {
167       for (const Use &Op : C->operands()) {
168         if (auto *COp = dyn_cast<ConstantArray>(Op))
169           WorkList.insert(COp);
170       }
171       C->destroyConstant();
172     }
173   }
174 }
175 
dropTriviallyDeadConstantArrays()176 void Module::dropTriviallyDeadConstantArrays() {
177   Context.pImpl->dropTriviallyDeadConstantArrays();
178 }
179 
180 namespace llvm {
181 
182 /// Make MDOperand transparent for hashing.
183 ///
184 /// This overload of an implementation detail of the hashing library makes
185 /// MDOperand hash to the same value as a \a Metadata pointer.
186 ///
187 /// Note that overloading \a hash_value() as follows:
188 ///
189 /// \code
190 ///     size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
191 /// \endcode
192 ///
193 /// does not cause MDOperand to be transparent.  In particular, a bare pointer
194 /// doesn't get hashed before it's combined, whereas \a MDOperand would.
get_hashable_data(const MDOperand & X)195 static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
196 
197 } // end namespace llvm
198 
calculateHash(MDNode * N,unsigned Offset)199 unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
200   unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
201 #ifndef NDEBUG
202   {
203     SmallVector<Metadata *, 8> MDs(drop_begin(N->operands(), Offset));
204     unsigned RawHash = calculateHash(MDs);
205     assert(Hash == RawHash &&
206            "Expected hash of MDOperand to equal hash of Metadata*");
207   }
208 #endif
209   return Hash;
210 }
211 
calculateHash(ArrayRef<Metadata * > Ops)212 unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
213   return hash_combine_range(Ops.begin(), Ops.end());
214 }
215 
getOrInsertBundleTag(StringRef Tag)216 StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
217   uint32_t NewIdx = BundleTagCache.size();
218   return &*(BundleTagCache.insert(std::make_pair(Tag, NewIdx)).first);
219 }
220 
getOperandBundleTags(SmallVectorImpl<StringRef> & Tags) const221 void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
222   Tags.resize(BundleTagCache.size());
223   for (const auto &T : BundleTagCache)
224     Tags[T.second] = T.first();
225 }
226 
getOperandBundleTagID(StringRef Tag) const227 uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
228   auto I = BundleTagCache.find(Tag);
229   assert(I != BundleTagCache.end() && "Unknown tag!");
230   return I->second;
231 }
232 
getOrInsertSyncScopeID(StringRef SSN)233 SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
234   auto NewSSID = SSC.size();
235   assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
236          "Hit the maximum number of synchronization scopes allowed!");
237   return SSC.insert(std::make_pair(SSN, SyncScope::ID(NewSSID))).first->second;
238 }
239 
getSyncScopeNames(SmallVectorImpl<StringRef> & SSNs) const240 void LLVMContextImpl::getSyncScopeNames(
241     SmallVectorImpl<StringRef> &SSNs) const {
242   SSNs.resize(SSC.size());
243   for (const auto &SSE : SSC)
244     SSNs[SSE.second] = SSE.first();
245 }
246 
247 /// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
248 /// singleton OptBisect if not explicitly set.
getOptPassGate() const249 OptPassGate &LLVMContextImpl::getOptPassGate() const {
250   if (!OPG)
251     OPG = &getGlobalPassGate();
252   return *OPG;
253 }
254 
setOptPassGate(OptPassGate & OPG)255 void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
256   this->OPG = &OPG;
257 }
258