78 Context.addModule(
this);
82 Context.removeModule(
this);
91 auto *DeclareIntrinsicFn =
94 "Debug declare intrinsic should have had uses removed.");
95 DeclareIntrinsicFn->eraseFromParent();
96 auto *ValueIntrinsicFn =
99 "Debug value intrinsic should have had uses removed.");
100 ValueIntrinsicFn->eraseFromParent();
101 auto *AssignIntrinsicFn =
104 "Debug assign intrinsic should have had uses removed.");
105 AssignIntrinsicFn->eraseFromParent();
108 "Debug label intrinsic should have had uses removed.");
109 LabelntrinsicFn->eraseFromParent();
112std::unique_ptr<RandomNumberGenerator>
128 return std::unique_ptr<RandomNumberGenerator>(
177 if (!New->isIntrinsic())
209 bool AllowLocal)
const {
212 if (AllowLocal || !Result->hasLocalLinkage())
229 GV = CreateGlobalCallback();
230 assert(GV &&
"The CreateGlobalCallback is expected to create a global");
273 NMD->setParent(
this);
275 if (
Name ==
"llvm.module.flags")
285 if (NMD == ModuleFlags)
286 ModuleFlags =
nullptr;
291 if (
ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
292 uint64_t Val = Behavior->getLimitedValue();
305 if (!ModFlags)
return;
309 auto *MFBConstant = mdconst::extract<ConstantInt>(Flag->getOperand(0));
310 auto MFB =
static_cast<ModFlagBehavior>(MFBConstant->getLimitedValue());
311 MDString *Key = cast<MDString>(Flag->getOperand(1));
312 Metadata *Val = Flag->getOperand(2);
324 if (Key == cast<MDString>(Flag->getOperand(1))->getString())
325 return Flag->getOperand(2);
357 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
360 assert(Node->getNumOperands() == 3 &&
361 "Invalid number of operands for module flag!");
362 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
363 isa<MDString>(Node->getOperand(1)) &&
364 "Invalid operand types for module flag!");
373 if (cast<MDString>(Flag->getOperand(1))->getString() == Key) {
374 Flag->replaceOperandWith(2, Val);
387 setModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
395 return cast<DICompileUnit>(CUs->
getOperand(Idx));
398 return cast<DICompileUnit>(CUs->getOperand(
Idx));
401void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
402 while (CUs && (Idx < CUs->getNumOperands()) &&
428 "Module already has a GVMaterializer. Call materializeAll"
429 " to clear it out before setting another one.");
430 Materializer.reset(GVM);
437 return Materializer->materialize(GV);
443 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
444 return M->materializeModule();
450 return Materializer->materializeMetadata();
462 return Materializer->getIdentifiedStructTypes();
464 std::vector<StructType *> Ret;
466 SrcStructTypes.
run(*
this,
true);
467 Ret.assign(SrcStructTypes.
begin(), SrcStructTypes.
end());
473 auto Encode = [&BaseName](
unsigned Suffix) {
474 return (
Twine(BaseName) +
"." +
Twine(Suffix)).str();
479 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
480 if (!UinItInserted.second)
481 return Encode(UinItInserted.first->second);
488 auto NiidItInserted = CurrentIntrinsicIds.
insert({BaseName, 0});
489 unsigned Count = NiidItInserted.first->second;
495 NewName = Encode(Count);
499 UniquedIntrinsicNames[{Id, Proto}] = Count;
504 FunctionType *FT = dyn_cast<FunctionType>(
F->getValueType());
505 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
509 UinItInserted.first->second = Count;
516 NiidItInserted.first->second = Count + 1;
530 F.dropAllReferences();
533 GV.dropAllReferences();
536 GA.dropAllReferences();
539 GIF.dropAllReferences();
544 cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"NumRegisterParameters"));
547 return cast<ConstantInt>(Val->getValue())->getZExtValue();
551 auto *Val = cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"Dwarf Version"));
554 return cast<ConstantInt>(Val->getValue())->getZExtValue();
558 auto *Val = cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"DWARF64"));
559 return Val && cast<ConstantInt>(Val->getValue())->isOne();
563 auto *Val = cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"CodeView"));
566 return cast<ConstantInt>(Val->getValue())->getZExtValue();
570 unsigned NumInstrs = 0;
572 NumInstrs +=
F.getInstructionCount();
578 Entry.second.Name = &Entry;
579 return &Entry.second;
583 auto *Val = cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"PIC Level"));
589 cast<ConstantInt>(Val->getValue())->getZExtValue());
599 auto *Val = cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"PIE Level"));
605 cast<ConstantInt>(Val->getValue())->getZExtValue());
613 auto *Val = cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"Code Model"));
619 cast<ConstantInt>(Val->getValue())->getZExtValue());
632 cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"Large Data Threshold"));
637 return cast<ConstantInt>(Val->getValue())->getZExtValue();
662 auto *Val = cast_or_null<ConstantAsMetadata>(MF);
666 return cast<ConstantInt>(Val->getValue())->getZExtValue();
674 OwnedMemoryBuffer = std::move(MB);
678 auto *Val = cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"RtLibUseGOT"));
679 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
687 auto *Val = cast_or_null<ConstantAsMetadata>(
690 return cast<ConstantInt>(Val->getValue())->getZExtValue() > 0;
699 if (
auto *Val = cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"uwtable")))
700 return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue());
709 auto *Val = cast_or_null<ConstantAsMetadata>(
getModuleFlag(
"frame-pointer"));
711 Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
720 if (
auto *MDS = dyn_cast_or_null<MDString>(MD))
721 return MDS->getString();
732 if (
auto *MDS = dyn_cast_or_null<MDString>(MD))
733 return MDS->getString();
744 if (
auto *MDS = dyn_cast_or_null<MDString>(MD))
745 return MDS->getString();
756 if (
auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
757 return CI->getSExtValue();
767 if (
auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
768 return CI->getZExtValue();
774 if (
auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
775 return CI->getZExtValue();
785 Entries.push_back(V.getMajor());
786 if (
auto Minor = V.getMinor()) {
787 Entries.push_back(*Minor);
788 if (
auto Subminor = V.getSubminor())
789 Entries.push_back(*Subminor);
802 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
805 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
808 auto getVersionComponent = [&](
unsigned Index) -> std::optional<unsigned> {
809 if (
Index >= Arr->getNumElements())
811 return (
unsigned)Arr->getElementAsInteger(
Index);
813 auto Major = getVersionComponent(0);
817 if (
auto Minor = getVersionComponent(1)) {
819 if (
auto Subminor = getVersionComponent(2)) {
832 const char *
Name = CompilerUsed ?
"llvm.compiler.used" :
"llvm.used";
857 double Ratio = (double)BlockCount / NumCounts;
866 if (
const auto *MD =
getModuleFlag(
"darwin.target_variant.triple"))
867 return cast<MDString>(MD)->getString();
This file defines the StringMap class.
This file contains the simple types necessary to represent the attributes associated with functions a...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
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.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
static VersionTuple getSDKVersionMD(Metadata *MD)
static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name)
cl::opt< bool > UseNewDbgInfoFormat
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
unsigned getProgramAddressSpace() const
Lightweight error class with error context and mandatory checking.
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...
Class to represent function types.
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.
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
void getOperandBundleTags(SmallVectorImpl< StringRef > &Result) const
getOperandBundleTags - Populate client supplied SmallVector with the bundle tags registered in this L...
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
getMDKindNames - Populate client supplied SmallVector with the name for custom metadata IDs registere...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDString * get(LLVMContext &Context, StringRef Str)
Class to hold module path string table and global value map, and encapsulate methods for operating on...
DICompileUnit * operator*() const
DICompileUnit * operator->() const
A Module instance is used to store all the information related to an LLVM module.
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.
void eraseNamedMDNode(NamedMDNode *MDNode)
Remove MDNode from the list and delete it.
ModFlagBehavior
This enumeration defines the supported behaviors of module flags.
@ Warning
Emits a warning if two values disagree.
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
@ ModFlagBehaviorFirstVal
@ Min
Takes the min of the two values, which are required to be integers.
@ Max
Takes the max of the two values, which are required to be integers.
llvm::Error materializeAll()
Make sure all GlobalValues in this Module are fully read and clear the Materializer.
LLVMContext & getContext() const
Get the global data context.
void setOverrideStackAlignment(unsigned Align)
void setDirectAccessExternalData(bool Value)
unsigned getMaxTLSAlignment() const
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.
iterator_range< ifunc_iterator > ifuncs()
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.
iterator_range< iterator > functions()
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 code model (tiny, small, kernel, medium or large model)
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)
iterator_range< alias_iterator > aliases()
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.
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.
iterator_range< global_iterator > globals()
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)
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
unsigned getNumberRegisterParameters() const
Returns the Number of Register ParametersDwarf Version by checking module flags.
void insertNamedMDNode(NamedMDNode *MDNode)
Insert MDNode at the end of the alias list and take ownership.
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 code model (tiny, small, kernel, medium or large)
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.
const ValueSymbolTable & getValueSymbolTable() const
Get the symbol table of global variable and function identifiers.
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.
bool isMaterialized() const
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.
Constant * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
std::optional< CodeModel::Model > getCodeModel() const
Returns the code model (tiny, small, kernel, medium or large model)
NamedMDNode * getModuleFlagsMetadata() const
Returns the NamedMDNode in the module that represents module-level flags.
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)
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.
StringRef getName() const
MDNode * getOperand(unsigned i) const
iterator_range< op_iterator > operands()
void addOperand(MDNode *M)
void setPartialProfileRatio(double R)
Metadata * getMD(LLVMContext &Context, bool AddPartialField=true, bool AddPartialProfileRatioField=true)
Return summary information as metadata.
uint32_t getNumCounts() const
bool isPartialProfile() const
static 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.
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
StringRef - Represent a constant reference to a string, i.e.
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)
The instances of the Type class are immutable: once they are created, they are never changed.
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
This class provides a symbol table of name/value pairs.
unsigned size() const
The number of name/type pairs is returned.
LLVM Value Representation.
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.
@ C
The default llvm calling convention, compatible with C.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
@ None
No unwind table requested.
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.
Description of the encoding of one expression Op.