LLVM 22.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"
16#include "llvm/ADT/iterator.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"
27#include <cassert>
28
29using namespace llvm;
30
32 : DiagHandler(std::make_unique<DiagnosticHandler>()),
33 VoidTy(C, Type::VoidTyID), LabelTy(C, Type::LabelTyID),
34 HalfTy(C, Type::HalfTyID), BFloatTy(C, Type::BFloatTyID),
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) {}
41
43#ifndef NDEBUG
44 // Check that any variable location records that fell off the end of a block
45 // when it's terminator was removed were eventually replaced. This assertion
46 // firing indicates that DbgVariableRecords went missing during the lifetime
47 // of the LLVMContext.
48 assert(TrailingDbgRecords.empty() && "DbgRecords in blocks not cleaned");
49#endif
50
51 // NOTE: We need to delete the contents of OwnedModules, but Module's dtor
52 // will call LLVMContextImpl::removeModule, thus invalidating iterators into
53 // the container. Avoid iterators during this operation:
54 while (!OwnedModules.empty())
55 delete *OwnedModules.begin();
56
57#ifndef NDEBUG
58 // Check for metadata references from leaked Values.
59 for (auto &Pair : ValueMetadata)
60 Pair.first->dump();
61 assert(ValueMetadata.empty() && "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 InlineAsms.freeConstants();
111
112 CAZConstants.clear();
113 CPNConstants.clear();
114 CTNConstants.clear();
115 UVConstants.clear();
116 PVConstants.clear();
117 IntZeroConstants.clear();
118 IntOneConstants.clear();
119 IntConstants.clear();
120 IntSplatConstants.clear();
121 FPConstants.clear();
122 FPSplatConstants.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
148namespace llvm {
149
150/// Make MDOperand transparent for hashing.
151///
152/// This overload of an implementation detail of the hashing library makes
153/// MDOperand hash to the same value as a \a Metadata pointer.
154///
155/// Note that overloading \a hash_value() as follows:
156///
157/// \code
158/// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
159/// \endcode
160///
161/// does not cause MDOperand to be transparent. In particular, a bare pointer
162/// doesn't get hashed before it's combined, whereas \a MDOperand would.
163static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
164
165} // end namespace llvm
166
168 unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
169#ifndef NDEBUG
170 {
172 unsigned RawHash = calculateHash(MDs);
173 assert(Hash == RawHash &&
174 "Expected hash of MDOperand to equal hash of Metadata*");
175 }
176#endif
177 return Hash;
178}
179
181 return hash_combine_range(Ops);
182}
183
185 uint32_t NewIdx = BundleTagCache.size();
186 return &*(BundleTagCache.insert(std::make_pair(Tag, NewIdx)).first);
187}
188
190 Tags.resize(BundleTagCache.size());
191 for (const auto &T : BundleTagCache)
192 Tags[T.second] = T.first();
193}
194
196 auto I = BundleTagCache.find(Tag);
197 assert(I != BundleTagCache.end() && "Unknown tag!");
198 return I->second;
199}
200
202 auto NewSSID = SSC.size();
203 assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
204 "Hit the maximum number of synchronization scopes allowed!");
205 return SSC.insert(std::make_pair(SSN, SyncScope::ID(NewSSID))).first->second;
206}
207
209 SmallVectorImpl<StringRef> &SSNs) const {
210 SSNs.resize(SSC.size());
211 for (const auto &SSE : SSC)
212 SSNs[SSE.second] = SSE.first();
213}
214
215std::optional<StringRef>
217 for (const auto &SSE : SSC) {
218 if (SSE.second != Id)
219 continue;
220 return SSE.first();
221 }
222 return std::nullopt;
223}
224
225/// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
226/// singleton OptBisect if not explicitly set.
228 if (!OPG)
230 return *OPG;
231}
232
234 this->OPG = &OPG;
235}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
const Type::TypeID FloatTyID
const Type::TypeID DoubleTyID
#define T
This file declares the interface for bisecting optimizations.
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
List of ValueAsMetadata, to be used as an argument to a dbg.value intrinsic.
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
DenseMap< APFloat, std::unique_ptr< ConstantFP > > FPConstants
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
DenseMap< APInt, std::unique_ptr< ConstantInt > > IntConstants
std::vector< MDNode * > DistinctMDNodes
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
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)
std::unique_ptr< DiagnosticHandler > DiagHandler
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< std::pair< ElementCount, APInt >, std::unique_ptr< ConstantInt > > IntSplatConstants
std::vector< ConstantRangeListAttributeImpl * > ConstantRangeListAttributes
DenseSet< DIArgList *, DIArgListInfo > DIArgLists
std::optional< StringRef > getSyncScopeName(SyncScope::ID Id) const
getSyncScopeName - Returns the name of a SyncScope::ID registered with LLVMContext,...
ArrayConstantsTy ArrayConstants
DenseMap< Value *, ValueAsMetadata * > ValuesAsMetadata
ConstantUniqueMap< InlineAsm > InlineAsms
LLVMContextImpl(LLVMContext &C)
SmallDenseMap< BasicBlock *, DbgMarker * > TrailingDbgRecords
Mapping of blocks to collections of "trailing" DbgVariableRecords.
DenseMap< std::pair< ElementCount, APFloat >, std::unique_ptr< ConstantFP > > FPSplatConstants
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static unsigned calculateHash(MDNode *N, unsigned Offset=0)
Metadata node.
Definition Metadata.h:1078
Tracking metadata reference owned by Metadata.
Definition Metadata.h:900
Root of the metadata hierarchy.
Definition Metadata.h:64
Extensions to this class implement mechanisms to disable passes and individual optimizations at compi...
Definition OptBisect.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:532
static const Metadata * get_hashable_data(const MDOperand &X)
Make MDOperand transparent for hashing.
LLVM_ABI OptPassGate & getGlobalPassGate()
Singleton instance of the OptPassGate class, so multiple pass managers don't need to coordinate their...
Definition OptBisect.cpp:94
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:466
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
#define N
This is the base class for diagnostic handling in LLVM.