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/StringMapEntry.h"
16#include "llvm/ADT/iterator.h"
17#include "llvm/IR/DiagnosticHandler.h"
18#include "llvm/IR/LLVMRemarkStreamer.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/OptBisect.h"
21#include "llvm/IR/Type.h"
22#include "llvm/IR/Use.h"
23#include "llvm/IR/User.h"
24#include "llvm/Remarks/RemarkStreamer.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/ErrorHandling.h"
27#include <cassert>
28
29using namespace llvm;
30
31LLVMContextImpl::LLVMContextImpl(LLVMContext &C)
32 : DiagHandler(std::make_unique<DiagnosticHandler>()),
33 VoidTy(C, Type::VoidTyID), LabelTy(C, Type::LabelTyID),
34 HalfTy(C, Type::HalfTyID), BFloatTy(C, Type::BFloatTyID),
35 FloatTy(C, Type::FloatTyID), DoubleTy(C, Type::DoubleTyID),
36 MetadataTy(C, Type::MetadataTyID), TokenTy(C, Type::TokenTyID),
37 X86_FP80Ty(C, Type::X86_FP80TyID), FP128Ty(C, Type::FP128TyID),
38 PPC_FP128Ty(C, Type::PPC_FP128TyID), X86_AMXTy(C, Type::X86_AMXTyID),
39 Int1Ty(C, 1), Int8Ty(C, 8), Int16Ty(C, 16), Int32Ty(C, 32),
40 Int64Ty(C, 64), Int128Ty(C, 128), Byte1Ty(C, 1), Byte8Ty(C, 8),
41 Byte16Ty(C, 16), Byte32Ty(C, 32), Byte64Ty(C, 64), Byte128Ty(C, 128) {}
42
43LLVMContextImpl::~LLVMContextImpl() {
44#ifndef NDEBUG
45 // Check that any variable location records that fell off the end of a block
46 // when it's terminator was removed were eventually replaced. This assertion
47 // firing indicates that DbgVariableRecords went missing during the lifetime
48 // of the LLVMContext.
49 assert(TrailingDbgRecords.empty() && "DbgRecords in blocks not cleaned");
50#endif
51
52 // NOTE: We need to delete the contents of OwnedModules, but Module's dtor
53 // will call LLVMContextImpl::removeModule, thus invalidating iterators into
54 // the container. Avoid iterators during this operation:
55 while (!OwnedModules.empty())
56 delete *OwnedModules.begin();
57
58#ifndef NDEBUG
59 // Check for metadata references from leaked Values.
60 assert((Metadatas.empty() || MetadataRecycleSize + 1 == Metadatas.size()) &&
61 "Values with metadata have been leaked");
62#endif
63
64 // Drop references for MDNodes. Do this before Values get deleted to avoid
65 // unnecessary RAUW when nodes are still unresolved.
66 for (auto *I : DistinctMDNodes)
67 I->dropAllReferences();
68#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
69 for (auto *I : CLASS##s) \
70 I->dropAllReferences();
71#include "llvm/IR/Metadata.def"
72
73 // Also drop references that come from the Value bridges.
74 for (auto &Pair : ValuesAsMetadata)
75 Pair.second->dropUsers();
76 for (auto &Pair : MetadataAsValues)
77 Pair.second->dropUse();
78 // Do not untrack ValueAsMetadata references for DIArgLists, as they have
79 // already been more efficiently untracked above.
80 for (DIArgList *AL : DIArgLists) {
81 AL->dropAllReferences(/* Untrack */ false);
82 delete AL;
83 }
84 DIArgLists.clear();
85
86 // Destroy MDNodes.
87 for (MDNode *I : DistinctMDNodes)
88 I->deleteAsSubclass();
89
90 for (auto *ConstantRangeListAttribute : ConstantRangeListAttributes)
91 ConstantRangeListAttribute->~ConstantRangeListAttributeImpl();
92#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
93 for (CLASS * I : CLASS##s) \
94 delete I;
95#include "llvm/IR/Metadata.def"
96
97 // Free the constants.
98 for (auto *I : ExprConstants)
99 I->dropAllReferences();
100 for (auto *I : ArrayConstants)
101 I->dropAllReferences();
102 for (auto *I : StructConstants)
103 I->dropAllReferences();
104 for (auto *I : VectorConstants)
105 I->dropAllReferences();
106 ExprConstants.freeConstants();
107 ArrayConstants.freeConstants();
108 StructConstants.freeConstants();
109 VectorConstants.freeConstants();
110 ConstantPtrAuths.freeConstants();
111 InlineAsms.freeConstants();
112
113 CAZConstants.clear();
114 CPNConstants.clear();
115 CTNConstants.clear();
116 UVConstants.clear();
117 PVConstants.clear();
118 IntZeroConstants.clear();
119 IntOneConstants.clear();
120 IntConstants.clear();
121 IntSplatConstants.clear();
122 ByteZeroConstants.clear();
123 ByteOneConstants.clear();
124 ByteConstants.clear();
125 ByteSplatConstants.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(N: MetadataAsValues.size());
141 for (auto &Pair : MetadataAsValues)
142 MDVs.push_back(Elt: 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
153namespace llvm {
154
155/// Make MDOperand transparent for hashing.
156///
157/// This overload of an implementation detail of the hashing library makes
158/// MDOperand hash to the same value as a \a Metadata pointer.
159///
160/// Note that overloading \a hash_value() as follows:
161///
162/// \code
163/// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
164/// \endcode
165///
166/// does not cause MDOperand to be transparent. In particular, a bare pointer
167/// doesn't get hashed before it's combined, whereas \a MDOperand would.
168static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
169
170} // end namespace llvm
171
172unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
173 unsigned Hash = hash_combine_range(first: N->op_begin() + Offset, last: N->op_end());
174#ifndef NDEBUG
175 {
176 SmallVector<Metadata *, 8> MDs(drop_begin(N->operands(), Offset));
177 unsigned RawHash = calculateHash(MDs);
178 assert(Hash == RawHash &&
179 "Expected hash of MDOperand to equal hash of Metadata*");
180 }
181#endif
182 return Hash;
183}
184
185unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
186 return hash_combine_range(R&: Ops);
187}
188
189StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
190 uint32_t NewIdx = BundleTagCache.size();
191 return &*(BundleTagCache.insert(KV: std::make_pair(x&: Tag, y&: NewIdx)).first);
192}
193
194void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
195 Tags.resize(N: BundleTagCache.size());
196 for (const auto &T : BundleTagCache)
197 Tags[T.second] = T.first();
198}
199
200uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
201 auto I = BundleTagCache.find(Key: Tag);
202 assert(I != BundleTagCache.end() && "Unknown tag!");
203 return I->second;
204}
205
206SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
207 auto NewSSID = SSC.size();
208 assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
209 "Hit the maximum number of synchronization scopes allowed!");
210 return SSC.insert(KV: std::make_pair(x&: SSN, y: SyncScope::ID(NewSSID))).first->second;
211}
212
213void LLVMContextImpl::getSyncScopeNames(
214 SmallVectorImpl<StringRef> &SSNs) const {
215 SSNs.resize(N: SSC.size());
216 for (const auto &SSE : SSC)
217 SSNs[SSE.second] = SSE.first();
218}
219
220std::optional<StringRef>
221LLVMContextImpl::getSyncScopeName(SyncScope::ID Id) const {
222 for (const auto &SSE : SSC) {
223 if (SSE.second != Id)
224 continue;
225 return SSE.first();
226 }
227 return std::nullopt;
228}
229
230/// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
231/// singleton OptBisect if not explicitly set.
232OptPassGate &LLVMContextImpl::getOptPassGate() const {
233 if (!OPG)
234 OPG = &getGlobalPassGate();
235 return *OPG;
236}
237
238void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
239 this->OPG = &OPG;
240}
241