75 ModuleID(
std::string(MID)), SourceFileName(
std::string(MID)) {
76 Context.addModule(
this);
80 assert(&Context == &
Other.Context &&
"Module must be in the same Context");
84 ModuleID = std::move(
Other.ModuleID);
85 SourceFileName = std::move(
Other.SourceFileName);
88 GlobalList.splice(GlobalList.begin(),
Other.GlobalList);
91 FunctionList.splice(FunctionList.begin(),
Other.FunctionList);
94 AliasList.splice(AliasList.begin(),
Other.AliasList);
97 IFuncList.splice(IFuncList.begin(),
Other.IFuncList);
100 NamedMDList.splice(NamedMDList.begin(),
Other.NamedMDList);
101 GlobalScopeAsm = std::move(
Other.GlobalScopeAsm);
102 OwnedMemoryBuffer = std::move(
Other.OwnedMemoryBuffer);
103 Materializer = std::move(
Other.Materializer);
104 TargetTriple = std::move(
Other.TargetTriple);
106 CurrentIntrinsicIds = std::move(
Other.CurrentIntrinsicIds);
107 UniquedIntrinsicNames = std::move(
Other.UniquedIntrinsicNames);
108 ModuleFlags = std::move(
Other.ModuleFlags);
109 Context.addModule(
this);
114 Context.removeModule(
this);
117 FunctionList.clear();
123 if (
auto *DeclareIntrinsicFn =
125 assert((!isMaterialized() || DeclareIntrinsicFn->hasZeroLiveUses()) &&
126 "Debug declare intrinsic should have had uses removed.");
127 DeclareIntrinsicFn->eraseFromParent();
129 if (
auto *ValueIntrinsicFn =
131 assert((!isMaterialized() || ValueIntrinsicFn->hasZeroLiveUses()) &&
132 "Debug value intrinsic should have had uses removed.");
133 ValueIntrinsicFn->eraseFromParent();
135 if (
auto *AssignIntrinsicFn =
137 assert((!isMaterialized() || AssignIntrinsicFn->hasZeroLiveUses()) &&
138 "Debug assign intrinsic should have had uses removed.");
139 AssignIntrinsicFn->eraseFromParent();
141 if (
auto *LabelntrinsicFn =
143 assert((!isMaterialized() || LabelntrinsicFn->hasZeroLiveUses()) &&
144 "Debug label intrinsic should have had uses removed.");
145 LabelntrinsicFn->eraseFromParent();
149std::unique_ptr<RandomNumberGenerator>
165 return std::unique_ptr<RandomNumberGenerator>(
177 return getValueSymbolTable().size();
183 return Context.getMDKindID(Name);
190 return Context.getMDKindNames(Result);
194 return Context.getOperandBundleTags(Result);
207 AttributeList AttributeList) {
213 DL.getProgramAddressSpace(), Name,
this);
214 if (!
New->isIntrinsic())
215 New->setAttributes(AttributeList);
224 return getOrInsertFunction(Name, Ty, AttributeList());
246 bool AllowLocal)
const {
249 if (AllowLocal || !
Result->hasLocalLinkage())
263 GV = CreateGlobalCallback();
264 assert(GV &&
"The CreateGlobalCallback is expected to create a global");
297 return NamedMDSymTab.lookup(Name);
307 NMD->setParent(
this);
308 insertNamedMDNode(NMD);
309 if (Name ==
"llvm.module.flags")
318 NamedMDSymTab.erase(NMD->
getName());
319 if (NMD == ModuleFlags)
320 ModuleFlags =
nullptr;
321 eraseNamedMDNode(NMD);
326 uint64_t Val = Behavior->getLimitedValue();
327 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
328 MFB =
static_cast<ModFlagBehavior
>(Val);
338 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
339 if (!ModFlags)
return;
344 auto MFB =
static_cast<ModFlagBehavior
>(MFBConstant->getLimitedValue());
347 Flags.push_back(ModuleFlagEntry(MFB,
Key, Val));
354 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
359 return Flag->getOperand(2);
370 return getOrInsertNamedMetadata(
"llvm.module.flags");
382 getOrInsertModuleFlagsMetadata()->addOperand(
MDNode::get(Context,
Ops));
391 addModuleFlag(Behavior,
Key, ConstantInt::get(
Int32Ty, Val));
395 "Invalid number of operands for module flag!");
398 "Invalid operand types for module flag!");
399 getOrInsertModuleFlagsMetadata()->addOperand(
Node);
404 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
408 Flag->replaceOperandWith(2, Val);
412 addModuleFlag(Behavior,
Key, Val);
421 setModuleFlag(Behavior,
Key, ConstantInt::get(
Int32Ty, Val));
435void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
436 while (CUs && (Idx < CUs->getNumOperands()) &&
462 "Module already has a GVMaterializer. Call materializeAll"
463 " to clear it out before setting another one.");
464 Materializer.reset(GVM);
471 return Materializer->materialize(GV);
477 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
478 return M->materializeModule();
485 return Materializer->materializeMetadata();
497 return Materializer->getIdentifiedStructTypes();
499 std::vector<StructType *>
Ret;
501 SrcStructTypes.
run(*
this,
true);
502 Ret.assign(SrcStructTypes.
begin(), SrcStructTypes.
end());
508 auto Encode = [&BaseName](
unsigned Suffix) {
509 return (
Twine(BaseName) +
"." +
Twine(Suffix)).str();
514 auto UinItInserted = UniquedIntrinsicNames.insert({{
Id, Proto}, 0});
515 if (!UinItInserted.second)
516 return Encode(UinItInserted.first->second);
523 auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
524 unsigned Count = NiidItInserted.first->second;
530 NewName = Encode(
Count);
534 UniquedIntrinsicNames[{
Id, Proto}] =
Count;
540 auto UinItInserted = UniquedIntrinsicNames.insert({{
Id, FT},
Count});
544 UinItInserted.first->second =
Count;
551 NiidItInserted.first->second =
Count + 1;
565 F.dropAllReferences();
571 GA.dropAllReferences();
574 GIF.dropAllReferences();
605 unsigned NumInstrs = 0;
607 NumInstrs +=
F.getInstructionCount();
612 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name,
Comdat())).first;
613 Entry.second.Name = &Entry;
614 return &Entry.second;
630 addModuleFlag(ModFlagBehavior::Min,
"PIC Level", PL);
644 addModuleFlag(ModFlagBehavior::Max,
"PIE Level", PL);
662 addModuleFlag(ModFlagBehavior::Error,
"Code Model", CL);
678 addModuleFlag(ModFlagBehavior::Error,
"Large Data Threshold",
684 setModuleFlag(ModFlagBehavior::Error,
"CSProfileSummary", M);
686 setModuleFlag(ModFlagBehavior::Error,
"ProfileSummary", M);
690 return (IsCS ? getModuleFlag(
"CSProfileSummary")
691 : getModuleFlag(
"ProfileSummary"));
695 Metadata *MF = getModuleFlag(
"SemanticInterposition");
705 addModuleFlag(ModFlagBehavior::Error,
"SemanticInterposition",
SI);
709 OwnedMemoryBuffer = std::move(MB);
718 addModuleFlag(ModFlagBehavior::Max,
"RtLibUseGOT", 1);
723 getModuleFlag(
"direct-access-external-data"));
730 addModuleFlag(ModFlagBehavior::Max,
"direct-access-external-data", Value);
740 addModuleFlag(ModFlagBehavior::Max,
"uwtable",
uint32_t(Kind));
750 addModuleFlag(ModFlagBehavior::Max,
"frame-pointer",
static_cast<int>(Kind));
754 Metadata *MD = getModuleFlag(
"stack-protector-guard");
756 return MDS->getString();
762 addModuleFlag(ModFlagBehavior::Error,
"stack-protector-guard",
ID);
766 Metadata *MD = getModuleFlag(
"stack-protector-guard-reg");
768 return MDS->getString();
774 addModuleFlag(ModFlagBehavior::Error,
"stack-protector-guard-reg",
ID);
778 Metadata *MD = getModuleFlag(
"stack-protector-guard-symbol");
780 return MDS->getString();
786 addModuleFlag(ModFlagBehavior::Error,
"stack-protector-guard-symbol",
ID);
790 Metadata *MD = getModuleFlag(
"stack-protector-guard-offset");
792 return CI->getSExtValue();
797 addModuleFlag(ModFlagBehavior::Error,
"stack-protector-guard-offset",
Offset);
801 Metadata *MD = getModuleFlag(
"override-stack-alignment");
803 return CI->getZExtValue();
808 Metadata *MD = getModuleFlag(
"MaxTLSAlign");
810 return CI->getZExtValue();
815 addModuleFlag(ModFlagBehavior::Error,
"override-stack-alignment",
Align);
821 if (
auto Minor = V.getMinor()) {
823 if (
auto Subminor = V.getSubminor())
843 auto getVersionComponent = [&](
unsigned Index) -> std::optional<unsigned> {
844 if (Index >= Arr->getNumElements())
846 return (
unsigned)Arr->getElementAsInteger(Index);
848 auto Major = getVersionComponent(0);
852 if (
auto Minor = getVersionComponent(1)) {
854 if (
auto Subminor = getVersionComponent(2)) {
867 const char *
Name = CompilerUsed ?
"llvm.compiler.used" :
"llvm.used";
873 for (Value *
Op :
Init->operands()) {
881 if (
auto *SummaryMD = getProfileSummary(
false)) {
888 uint64_t BlockCount = Index.getBlockCount();
892 double Ratio = (double)BlockCount / NumCounts;
901 if (
const auto *MD = getModuleFlag(
"darwin.target_variant.triple"))
907 addModuleFlag(ModFlagBehavior::Warning,
"darwin.target_variant.triple",
912 return getSDKVersionMD(getModuleFlag(
"darwin.target_variant.SDK Version"));
921 if (
auto *TargetABIMD =
923 TargetABI = TargetABIMD->getString();
928 Metadata *MD = getModuleFlag(
"winx64-eh-unwindv2");
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
Lower uses of LDS variables from non kernel functions
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_EXPORT_TEMPLATE
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Machine Check Debug Module
static Constant * getOrInsertGlobal(Module &M, StringRef Name, Type *Ty)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
static VersionTuple getSDKVersionMD(Metadata *MD)
static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name)
This file defines the SmallString class.
This file defines the SmallVector class.
Defines the llvm::VersionTuple class, which represents a version in the form major[....
ConstantArray - Constant Array Declarations.
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
This is the shared class of boolean and integer constants.
This is an important base class in LLVM.
A parsed version of the target data layout string in and methods for querying it.
static ErrorSuccess success()
Create a success value.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
@ ExternalLinkage
Externally visible function.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
This is an important class for using LLVM in a threaded context.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Class to hold module path string table and global value map, and encapsulate methods for operating on...
LLVM_ABI DICompileUnit * operator*() const
LLVM_ABI DICompileUnit * operator->() const
void setStackProtectorGuardSymbol(StringRef Symbol)
void setSemanticInterposition(bool)
Set whether semantic interposition is to be respected.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
@ Warning
Emits a warning if two values disagree.
llvm::Error materializeAll()
Make sure all GlobalValues in this Module are fully read and clear the Materializer.
WinX64EHUnwindV2Mode getWinX64EHUnwindV2Mode() const
Get how unwind v2 (epilog) information should be generated for x64 Windows.
void setOverrideStackAlignment(unsigned Align)
void setDirectAccessExternalData(bool Value)
unsigned getMaxTLSAlignment() const
StringRef getTargetABIFromMD()
Returns target-abi from MDString, null if target-abi is absent.
void setOwnedMemoryBuffer(std::unique_ptr< MemoryBuffer > MB)
Take ownership of the given memory buffer.
void setMaterializer(GVMaterializer *GVM)
Sets the GVMaterializer to GVM.
llvm::Error materialize(GlobalValue *GV)
Make sure the GlobalValue is fully read.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
void setCodeModel(CodeModel::Model CL)
Set the code model (tiny, small, kernel, medium or large)
StringRef getStackProtectorGuardSymbol() const
Get/set a symbol to use as the stack protector guard.
bool getSemanticInterposition() const
Returns whether semantic interposition is to be respected.
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
Populate client supplied SmallVector with the name for custom metadata IDs registered in this LLVMCon...
Module(StringRef ModuleID, LLVMContext &C)
The Module constructor.
void removeDebugIntrinsicDeclarations()
Used when printing this module in the new debug info format; removes all declarations of debug intrin...
void setRtLibUseGOT()
Set that PLT should be avoid for RTLib calls.
llvm::Error materializeMetadata()
NamedMDNode * getOrInsertModuleFlagsMetadata()
Returns the NamedMDNode in the module that represents module-level flags.
void eraseNamedMetadata(NamedMDNode *NMD)
Remove the given NamedMDNode from this module and delete it.
unsigned getNumNamedValues() const
Return the number of global values in the module.
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
void setFramePointer(FramePointerKind Kind)
std::optional< uint64_t > getLargeDataThreshold() const
Returns the large data threshold.
StringRef getStackProtectorGuard() const
Get/set what kind of stack protector guard to use.
bool getRtLibUseGOT() const
Returns true if PLT should be avoided for RTLib calls.
void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val)
Like addModuleFlag but replaces the old module flag if it already exists.
UWTableKind getUwtable() const
Get/set whether synthesized functions should get the uwtable attribute.
void dropAllReferences()
This function causes all the subinstructions to "let go" of all references that they are maintaining.
void setStackProtectorGuard(StringRef Kind)
void setProfileSummary(Metadata *M, ProfileSummary::Kind Kind)
Attach profile summary metadata to this module.
void setUwtable(UWTableKind Kind)
unsigned getCodeViewFlag() const
Returns the CodeView Version by checking module flags.
void setPartialSampleProfileRatio(const ModuleSummaryIndex &Index)
Set the partial sample profile ratio in the profile summary module flag, if applicable.
Module & operator=(Module &&Other)
Move assignment.
std::string getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id, const FunctionType *Proto)
Return a unique name for an intrinsic whose mangling is based on an unnamed type.
~Module()
The module destructor. This will dropAllReferences.
FramePointerKind getFramePointer() const
Get/set whether synthesized functions should get the "frame-pointer" attribute.
unsigned getOverrideStackAlignment() const
Get/set the stack alignment overridden from the default.
void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val)
Add a module-level flag to the module-level flags metadata.
void setStackProtectorGuardReg(StringRef Reg)
PICLevel::Level getPICLevel() const
Returns the PIC level (small or large model)
std::unique_ptr< RandomNumberGenerator > createRNG(const StringRef Name) const
Get a RandomNumberGenerator salted for use with this module.
std::vector< StructType * > getIdentifiedStructTypes() const
void setDarwinTargetVariantTriple(StringRef T)
Set the target variant triple which is a string describing a variant of the target host platform.
void setPICLevel(PICLevel::Level PL)
Set the PIC level (small or large model)
unsigned getNumberRegisterParameters() const
Returns the Number of Register ParametersDwarf Version by checking module flags.
GlobalIFunc * getNamedIFunc(StringRef Name) const
Return the global ifunc in the module with the specified name, of arbitrary type.
StringRef getStackProtectorGuardReg() const
Get/set which register to use as the stack protector guard register.
unsigned getDwarfVersion() const
Returns the Dwarf Version by checking module flags.
void setDataLayout(StringRef Desc)
Set the data layout.
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
void setLargeDataThreshold(uint64_t Threshold)
Set the large data threshold.
bool isDwarf64() const
Returns the DWARF format by checking module flags.
static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB)
Checks if Metadata represents a valid ModFlagBehavior, and stores the converted result in MFB.
void setStackProtectorGuardOffset(int Offset)
iterator_range< global_object_iterator > global_objects()
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in the module.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
void getOperandBundleTags(SmallVectorImpl< StringRef > &Result) const
Populate client supplied SmallVector with the bundle tags registered in this LLVMContext.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
std::optional< CodeModel::Model > getCodeModel() const
Returns the code model (tiny, small, kernel, medium or large model)
VersionTuple getDarwinTargetVariantSDKVersion() const
Get the target variant version build SDK version metadata.
void setPIELevel(PIELevel::Level PL)
Set the PIE level (small or large model)
GlobalVariable * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
VersionTuple getSDKVersion() const
Get the build SDK version metadata.
GlobalAlias * getNamedAlias(StringRef Name) const
Return the global alias in the module with the specified name, of arbitrary type.
void setDarwinTargetVariantSDKVersion(VersionTuple Version)
Set the target variant version build SDK version metadata.
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
StringRef getDarwinTargetVariantTriple() const
Get the target variant triple which is a string describing a variant of the target host platform.
void setSDKVersion(const VersionTuple &V)
Attach a build SDK version metadata to this module.
iterator_range< global_value_iterator > global_values()
int getStackProtectorGuardOffset() const
Get/set what offset from the stack protector to use.
bool getDirectAccessExternalData() const
Get/set whether referencing global variables can use direct access relocations on ELF targets.
Metadata * getProfileSummary(bool IsCS) const
Returns profile summary metadata.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI StringRef getName() const
iterator_range< op_iterator > operands()
void setPartialProfileRatio(double R)
LLVM_ABI Metadata * getMD(LLVMContext &Context, bool AddPartialField=true, bool AddPartialProfileRatioField=true)
Return summary information as metadata.
uint32_t getNumCounts() const
bool isPartialProfile() const
static LLVM_ABI ProfileSummary * getFromMD(Metadata *MD)
Construct profile summary from metdata.
A random number generator.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
TypeFinder - Walk over a module, identifying all of the types that are used by the module.
void run(const Module &M, bool onlyNamed)
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
void dropAllReferences()
Drop all references to operands.
This class provides a symbol table of name/value pairs.
Represents a version number in the form major[.minor[.subminor[.build]]].
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, bool > hasa(Y &&MD)
Check whether Metadata has a Value.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Context & getContext() const
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
auto cast_or_null(const Y &Val)
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
auto dyn_cast_or_null(const Y &Val)
@ None
No unwind table requested.
FunctionAddr VTableAddr Count
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Implement std::hash so that hash_code can be used in STL containers.
This struct is a compact representation of a valid (non-zero power of two) alignment.