LLVM 17.0.0git
LLVMContextImpl.cpp
Go to the documentation of this file.
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"
17#include "llvm/ADT/iterator.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"
31#include <cassert>
32#include <utility>
33
34using namespace llvm;
35
36static cl::opt<bool>
37 OpaquePointersCL("opaque-pointers", cl::desc("Use opaque pointers"),
38 cl::init(true));
39
41 : DiagHandler(std::make_unique<DiagnosticHandler>()),
42 VoidTy(C, Type::VoidTyID), LabelTy(C, Type::LabelTyID),
43 HalfTy(C, Type::HalfTyID), BFloatTy(C, Type::BFloatTyID),
44 FloatTy(C, Type::FloatTyID), DoubleTy(C, Type::DoubleTyID),
45 MetadataTy(C, Type::MetadataTyID), TokenTy(C, Type::TokenTyID),
46 X86_FP80Ty(C, Type::X86_FP80TyID), FP128Ty(C, Type::FP128TyID),
47 PPC_FP128Ty(C, Type::PPC_FP128TyID), X86_MMXTy(C, Type::X86_MMXTyID),
48 X86_AMXTy(C, Type::X86_AMXTyID), Int1Ty(C, 1), Int8Ty(C, 8),
49 Int16Ty(C, 16), Int32Ty(C, 32), Int64Ty(C, 64), Int128Ty(C, 128) {
50 if (OpaquePointersCL.getNumOccurrences()) {
51 OpaquePointers = OpaquePointersCL;
52 }
53}
54
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 // We may have DIArgList that were uniqued, and as it has a custom
73 // implementation of dropAllReferences, it needs to be explicitly invoked.
74 if (auto *AL = dyn_cast<DIArgList>(I)) {
75 AL->dropAllReferences();
76 continue;
77 }
78 I->dropAllReferences();
79 }
80#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
81 for (auto *I : CLASS##s) \
82 I->dropAllReferences();
83#include "llvm/IR/Metadata.def"
84
85 // Also drop references that come from the Value bridges.
86 for (auto &Pair : ValuesAsMetadata)
87 Pair.second->dropUsers();
88 for (auto &Pair : MetadataAsValues)
89 Pair.second->dropUse();
90
91 // Destroy MDNodes.
92 for (MDNode *I : DistinctMDNodes)
93 I->deleteAsSubclass();
94#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
95 for (CLASS * I : CLASS##s) \
96 delete I;
97#include "llvm/IR/Metadata.def"
98
99 // Free the constants.
100 for (auto *I : ExprConstants)
101 I->dropAllReferences();
102 for (auto *I : ArrayConstants)
103 I->dropAllReferences();
104 for (auto *I : StructConstants)
105 I->dropAllReferences();
106 for (auto *I : VectorConstants)
107 I->dropAllReferences();
108 ExprConstants.freeConstants();
112 InlineAsms.freeConstants();
113
114 CAZConstants.clear();
115 CPNConstants.clear();
116 CTNConstants.clear();
117 UVConstants.clear();
118 PVConstants.clear();
119 IntZeroConstants.clear();
120 IntOneConstants.clear();
121 IntConstants.clear();
122 FPConstants.clear();
123 CDSConstants.clear();
124
125 // Destroy attribute node lists.
127 E = AttrsSetNodes.end(); I != E; ) {
129 delete &*Elem;
130 }
131
132 // Destroy MetadataAsValues.
133 {
135 MDVs.reserve(MetadataAsValues.size());
136 for (auto &Pair : MetadataAsValues)
137 MDVs.push_back(Pair.second);
138 MetadataAsValues.clear();
139 for (auto *V : MDVs)
140 delete V;
141 }
142
143 // Destroy ValuesAsMetadata.
144 for (auto &Pair : ValuesAsMetadata)
145 delete Pair.second;
146}
147
150
151 // When ArrayConstants are of substantial size and only a few in them are
152 // dead, starting WorkList with all elements of ArrayConstants can be
153 // wasteful. Instead, starting WorkList with only elements that have empty
154 // uses.
156 if (C->use_empty())
157 WorkList.insert(C);
158
159 while (!WorkList.empty()) {
160 ConstantArray *C = WorkList.pop_back_val();
161 if (C->use_empty()) {
162 for (const Use &Op : C->operands()) {
163 if (auto *COp = dyn_cast<ConstantArray>(Op))
164 WorkList.insert(COp);
165 }
166 C->destroyConstant();
167 }
168 }
169}
170
173}
174
175namespace llvm {
176
177/// Make MDOperand transparent for hashing.
178///
179/// This overload of an implementation detail of the hashing library makes
180/// MDOperand hash to the same value as a \a Metadata pointer.
181///
182/// Note that overloading \a hash_value() as follows:
183///
184/// \code
185/// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
186/// \endcode
187///
188/// does not cause MDOperand to be transparent. In particular, a bare pointer
189/// doesn't get hashed before it's combined, whereas \a MDOperand would.
190static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
191
192} // end namespace llvm
193
195 unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
196#ifndef NDEBUG
197 {
199 unsigned RawHash = calculateHash(MDs);
200 assert(Hash == RawHash &&
201 "Expected hash of MDOperand to equal hash of Metadata*");
202 }
203#endif
204 return Hash;
205}
206
208 return hash_combine_range(Ops.begin(), Ops.end());
209}
210
212 uint32_t NewIdx = BundleTagCache.size();
213 return &*(BundleTagCache.insert(std::make_pair(Tag, NewIdx)).first);
214}
215
217 Tags.resize(BundleTagCache.size());
218 for (const auto &T : BundleTagCache)
219 Tags[T.second] = T.first();
220}
221
223 auto I = BundleTagCache.find(Tag);
224 assert(I != BundleTagCache.end() && "Unknown tag!");
225 return I->second;
226}
227
229 auto NewSSID = SSC.size();
230 assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
231 "Hit the maximum number of synchronization scopes allowed!");
232 return SSC.insert(std::make_pair(SSN, SyncScope::ID(NewSSID))).first->second;
233}
234
236 SmallVectorImpl<StringRef> &SSNs) const {
237 SSNs.resize(SSC.size());
238 for (const auto &SSE : SSC)
239 SSNs[SSE.second] = SSE.first();
240}
241
242/// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
243/// singleton OptBisect if not explicitly set.
245 if (!OPG)
247 return *OPG;
248}
249
251 this->OPG = &OPG;
252}
253
255 if (LLVM_UNLIKELY(!OpaquePointers))
256 OpaquePointers = OpaquePointersCL;
257 return *OpaquePointers;
258}
259
261 assert((!OpaquePointers || *OpaquePointers == OP) &&
262 "Cannot change opaque pointers mode once set");
263 OpaquePointers = OP;
264}
This file defines the StringMapEntry class - it is intended to be a low dependency implementation det...
This file defines various helper methods and classes used by LLVMContextImpl for creating and managin...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:210
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static cl::opt< bool > OpaquePointersCL("opaque-pointers", cl::desc("Use opaque pointers"), cl::init(true))
#define I(x, y, z)
Definition: MD5.cpp:58
const Type::TypeID FloatTyID
const Type::TypeID DoubleTyID
Module.h This file contains the declarations for the Module class.
IntegerType * Int32Ty
This file declares the interface for bisecting optimizations.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements a set that has insertion order iteration characteristics.
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
Definition: TextStub.cpp:1080
This defines the Use class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:152
iterator begin() const
Definition: ArrayRef.h:151
ConstantArray - Constant Array Declarations.
Definition: Constants.h:408
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntOneConstants
void getSyncScopeNames(SmallVectorImpl< StringRef > &SSNs) const
getSyncScopeNames - Populates client supplied SmallVector with synchronization scope names registered...
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntZeroConstants
DenseMap< Metadata *, MetadataAsValue * > MetadataAsValues
SmallPtrSet< Module *, 4 > OwnedModules
OwnedModules - The set of modules instantiated in this context, and which will be automatically delet...
DenseMap< PointerType *, std::unique_ptr< ConstantPointerNull > > CPNConstants
DenseMap< Type *, std::unique_ptr< ConstantAggregateZero > > CAZConstants
DenseMap< Type *, std::unique_ptr< PoisonValue > > PVConstants
std::vector< MDNode * > DistinctMDNodes
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
void dropTriviallyDeadConstantArrays()
Destroy the ConstantArrays if they are not used.
void setOptPassGate(OptPassGate &)
Set the object which can disable optional passes and individual optimizations at compile time.
VectorConstantsTy VectorConstants
DenseMap< Type *, std::unique_ptr< UndefValue > > UVConstants
OptPassGate & getOptPassGate() const
Access the object which can disable optional passes and individual optimizations at compile time.
DenseMap< const Value *, MDAttachments > ValueMetadata
Collection of metadata used in this context.
StringMapEntry< uint32_t > * getOrInsertBundleTag(StringRef Tag)
StringMap< uint32_t > BundleTagCache
A set of interned tags for operand bundles.
StringMap< std::unique_ptr< ConstantDataSequential > > CDSConstants
StructConstantsTy StructConstants
void getOperandBundleTags(SmallVectorImpl< StringRef > &Tags) const
FoldingSet< AttributeSetNode > AttrsSetNodes
void setOpaquePointers(bool OP)
DenseMap< TargetExtType *, std::unique_ptr< ConstantTargetNone > > CTNConstants
ConstantUniqueMap< ConstantExpr > ExprConstants
uint32_t getOperandBundleTagID(StringRef Tag) const
StringMap< SyncScope::ID > SSC
A set of interned synchronization scopes.
DenseMap< APFloat, std::unique_ptr< ConstantFP >, DenseMapAPFloatKeyInfo > FPConstants
ArrayConstantsTy ArrayConstants
DenseMap< Value *, ValueAsMetadata * > ValuesAsMetadata
ConstantUniqueMap< InlineAsm > InlineAsms
DenseMap< APInt, std::unique_ptr< ConstantInt >, DenseMapAPIntKeyInfo > IntConstants
LLVMContextImpl(LLVMContext &C)
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:69
static unsigned calculateHash(MDNode *N, unsigned Offset=0)
Metadata node.
Definition: Metadata.h:950
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:772
Root of the metadata hierarchy.
Definition: Metadata.h:61
void dropTriviallyDeadConstantArrays()
Destroy ConstantArrays in LLVMContext if they are not used.
Extensions to this class implement mechanisms to disable passes and individual optimizations at compi...
Definition: OptBisect.h:26
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:152
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:83
value_type pop_back_val()
Definition: SetVector.h:236
iterator begin() const
Definition: SmallPtrSet.h:403
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:312
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
void reserve(size_type N)
Definition: SmallVector.h:667
void resize(size_type N)
Definition: SmallVector.h:642
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
unsigned size() const
Definition: StringMap.h:95
iterator end()
Definition: StringMap.h:204
iterator find(StringRef Key)
Definition: StringMap.h:217
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:286
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:413
@ Offset
Definition: DWP.cpp:440
static const Metadata * get_hashable_data(const MDOperand &X)
Make MDOperand transparent for hashing.
OptPassGate & getGlobalPassGate()
Singleton instance of the OptBisect class, so multiple pass managers don't need to coordinate their u...
Definition: OptBisect.cpp:54
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:491
Definition: BitVector.h:858
#define N
#define OP(n)
Definition: regex2.h:73
This is the base class for diagnostic handling in LLVM.