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