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