LLVM 18.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
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
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();
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.
119 E = AttrsSetNodes.end(); I != E; ) {
121 delete &*Elem;
122 }
123
124 // Destroy MetadataAsValues.
125 {
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
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.
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
165}
166
167namespace 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.
182static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
183
184} // end namespace llvm
185
187 unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
188#ifndef NDEBUG
189 {
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
200 return hash_combine_range(Ops.begin(), Ops.end());
201}
202
204 uint32_t NewIdx = BundleTagCache.size();
205 return &*(BundleTagCache.insert(std::make_pair(Tag, NewIdx)).first);
206}
207
209 Tags.resize(BundleTagCache.size());
210 for (const auto &T : BundleTagCache)
211 Tags[T.second] = T.first();
212}
213
215 auto I = BundleTagCache.find(Tag);
216 assert(I != BundleTagCache.end() && "Unknown tag!");
217 return I->second;
218}
219
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
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.
237 if (!OPG)
239 return *OPG;
240}
241
243 this->OPG = &OPG;
244}
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")
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#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:154
iterator begin() const
Definition: ArrayRef.h:153
ConstantArray - Constant Array Declarations.
Definition: Constants.h:408
This class represents an Operation in the Expression.
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
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:24
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:93
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
value_type pop_back_val()
Definition: SetVector.h:285
iterator begin() const
Definition: SmallPtrSet.h:404
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
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:205
iterator find(StringRef Key)
Definition: StringMap.h:218
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:287
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
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:330
@ 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
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
This is the base class for diagnostic handling in LLVM.