146#define DEBUG_TYPE "mergefunc"
148STATISTIC(NumFunctionsMerged,
"Number of functions merged");
149STATISTIC(NumThunksWritten,
"Number of thunks generated");
150STATISTIC(NumAliasesWritten,
"Number of aliases generated");
151STATISTIC(NumDoubleWeak,
"Number of new functions created");
155 cl::desc(
"How many functions in a module could be used for "
156 "MergeFunctions to pass a basic correctness check. "
157 "'0' disables this check. Works only with '-debug' key."),
177 cl::desc(
"Preserve debug info in thunk when mergefunc "
178 "transformations are made."));
183 cl::desc(
"Allow mergefunc to create aliases"));
195 Function *getFunc()
const {
return F; }
209class MergeFunctions {
212 : FnTree(FunctionNodeCmp(&GlobalNumbers)), FAM(FAM) {}
214 template <
typename FuncContainer>
bool run(FuncContainer &Functions);
217 SmallPtrSet<GlobalValue *, 4> &getUsed();
222 class FunctionNodeCmp {
223 GlobalNumberState* GlobalNumbers;
226 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
228 bool operator()(
const FunctionNode &
LHS,
const FunctionNode &
RHS)
const {
230 if (
LHS.getHash() !=
RHS.getHash())
231 return LHS.getHash() <
RHS.getHash();
232 FunctionComparator FCmp(
LHS.getFunc(),
RHS.getFunc(), GlobalNumbers);
233 return FCmp.compare() < 0;
236 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
238 GlobalNumberState GlobalNumbers;
242 std::vector<WeakTrackingVH> Deferred;
245 SmallPtrSet<GlobalValue *, 4> Used;
250 bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
263 void removeUsers(
Value *V);
284 filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
285 std::vector<Instruction *> &PDIUnrelatedWL,
286 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
296 eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL,
297 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
313 void replaceFunctionInTree(
const FunctionNode &FN,
Function *
G);
324 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
327 DenseMap<Function *, Function *> DelToNewMap;
344 MergeFunctions MF(
FAM);
348 MF.getUsed().insert_range(UsedV);
360 MergeFunctions MF(
FAM);
361 return MF.runOnFunctions(Funcs);
365bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
367 unsigned TripleNumber = 0;
370 dbgs() <<
"MERGEFUNC-VERIFY: Started for first " << Max <<
" functions.\n";
373 for (std::vector<WeakTrackingVH>::iterator
I = Worklist.begin(),
375 I != E && i < Max; ++
I, ++i) {
377 for (std::vector<WeakTrackingVH>::iterator J =
I; J != E && j < Max;
386 dbgs() <<
"MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
388 dbgs() << *F1 <<
'\n' << *F2 <<
'\n';
396 for (std::vector<WeakTrackingVH>::iterator
K = J;
K !=
E && k < Max;
397 ++k, ++
K, ++TripleNumber) {
405 bool Transitive =
true;
407 if (Res1 != 0 && Res1 == Res4) {
409 Transitive = Res3 == Res1;
410 }
else if (Res3 != 0 && Res3 == -Res4) {
412 Transitive = Res3 == Res1;
413 }
else if (Res4 != 0 && -Res3 == Res4) {
415 Transitive = Res4 == -Res1;
419 dbgs() <<
"MERGEFUNC-VERIFY: Non-transitive; triple: "
420 << TripleNumber <<
"\n";
421 dbgs() <<
"Res1, Res3, Res4: " << Res1 <<
", " << Res3 <<
", "
423 dbgs() << *F1 <<
'\n' << *F2 <<
'\n' << *F3 <<
'\n';
430 dbgs() <<
"MERGEFUNC-VERIFY: " << (
Valid ?
"Passed." :
"Failed.") <<
"\n";
461 return !
F.isDeclaration() && !
F.hasAvailableExternallyLinkage() &&
462 !
F.hasFnAttribute(Attribute::NoIPA) &&
463 !
F.hasFnAttribute(
"oracle-function") &&
470template <
typename FuncContainer>
bool MergeFunctions::run(FuncContainer &M) {
475 std::vector<std::pair<stable_hash, Function *>> HashedFuncs;
476 for (
auto &Func : M) {
485 auto S = HashedFuncs.begin();
486 for (
auto I = HashedFuncs.begin(), IE = HashedFuncs.end();
I != IE; ++
I) {
489 if ((
I != S && std::prev(
I)->first ==
I->first) ||
490 (std::next(
I) != IE && std::next(
I)->first ==
I->first)) {
496 std::vector<WeakTrackingVH> Worklist;
497 Deferred.swap(Worklist);
502 LLVM_DEBUG(
dbgs() <<
"size of worklist: " << Worklist.size() <<
'\n');
509 if (!
F->isDeclaration() && !
F->hasAvailableExternallyLinkage() &&
510 !
F->hasFnAttribute(Attribute::NoIPA)) {
514 LLVM_DEBUG(
dbgs() <<
"size of FnTree: " << FnTree.size() <<
'\n');
515 }
while (!Deferred.empty());
518 FNodesInTree.clear();
519 GlobalNumbers.
clear();
527 [[maybe_unused]]
bool MergeResult = this->
run(Funcs);
528 assert(MergeResult == !DelToNewMap.empty());
529 return this->DelToNewMap;
537 if (!New->getSubprogram())
541 if (!CB || !CB->isCallee(&U) || CB->getDebugLoc())
566void MergeFunctions::eraseInstsUnrelatedToPDI(
567 std::vector<Instruction *> &PDIUnrelatedWL,
568 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
570 dbgs() <<
" Erasing instructions (in reverse order of appearance in "
571 "entry block) unrelated to parameter debug info from entry "
573 while (!PDIUnrelatedWL.empty()) {
578 I->eraseFromParent();
579 PDIUnrelatedWL.pop_back();
582 while (!PDVRUnrelatedWL.empty()) {
588 PDVRUnrelatedWL.pop_back();
591 LLVM_DEBUG(
dbgs() <<
" } // Done erasing instructions unrelated to parameter "
592 "debug info from entry block. \n");
596void MergeFunctions::eraseTail(
Function *
G) {
597 std::vector<BasicBlock *> WorklistBB;
599 BB.dropAllReferences();
600 WorklistBB.push_back(&BB);
602 while (!WorklistBB.empty()) {
605 WorklistBB.pop_back();
618void MergeFunctions::filterInstsUnrelatedToPDI(
619 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL,
620 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
621 std::set<Instruction *> PDIRelated;
622 std::set<DbgVariableRecord *> PDVRRelated;
635 PDVRRelated.insert(DbgVal);
643 auto ExamineDbgDeclare = [&PDIRelated,
658 if (
Value *Arg =
SI->getValueOperand()) {
663 PDIRelated.insert(AI);
667 PDIRelated.insert(
SI);
671 PDVRRelated.insert(DbgDecl);
702 ExamineDbgValue(&DVR);
705 ExamineDbgDeclare(&DVR);
709 if (BI->isTerminator() && &*BI == GEntryBlock->
getTerminator()) {
713 PDIRelated.insert(&*BI);
722 <<
" Report parameter debug info related/related instructions: {\n");
724 auto IsPDIRelated = [](
auto *Rec,
auto &Container,
auto &UnrelatedCont) {
725 if (Container.find(Rec) == Container.end()) {
729 UnrelatedCont.push_back(Rec);
740 IsPDIRelated(&DVR, PDVRRelated, PDVRUnrelatedWL);
741 IsPDIRelated(&
I, PDIRelated, PDIUnrelatedWL);
751 if (
F->hasKernelCallingConv())
756 if (
F->size() == 1) {
757 if (
F->front().size() < 2) {
759 <<
" is too small to bother creating a thunk for\n");
784 std::optional<uint64_t> GEntryCount =
G->getEntryCount();
786 std::vector<Instruction *> PDIUnrelatedWL;
787 std::vector<DbgVariableRecord *> PDVRUnrelatedWL;
791 LLVM_DEBUG(
dbgs() <<
"writeThunk: (MergeFunctionsPDI) Do not create a new "
792 "function as thunk; retain original: "
793 <<
G->getName() <<
"()\n");
794 GEntryBlock = &
G->getEntryBlock();
796 dbgs() <<
"writeThunk: (MergeFunctionsPDI) filter parameter related "
798 <<
G->getName() <<
"() {\n");
799 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL, PDVRUnrelatedWL);
804 G->getAddressSpace(),
"",
G->getParent());
815 Args.push_back(Builder.CreateAggregateCast(&AI, FFTy->getParamType(i)));
819 CallInst *CI = Builder.CreateCall(
F, Args);
827 if (
H->getReturnType()->isVoidTy()) {
828 RI = Builder.CreateRetVoid();
830 RI = Builder.CreateRet(Builder.CreateAggregateCast(CI,
H->getReturnType()));
844 dbgs() <<
"writeThunk: (MergeFunctionsPDI) No DISubprogram for "
845 <<
G->getName() <<
"()\n");
848 eraseInstsUnrelatedToPDI(PDIUnrelatedWL, PDVRUnrelatedWL);
850 dbgs() <<
"} // End of parameter related debug info filtering for: "
851 <<
G->getName() <<
"()\n");
862 G->replaceAllUsesWith(NewG);
863 G->eraseFromParent();
876 assert(
F->hasLocalLinkage() ||
F->hasExternalLinkage()
877 ||
F->hasWeakLinkage() ||
F->hasLinkOnceLinkage());
883 if (!GA.hasLocalLinkage() && GA.getAliaseeObject() ==
F)
891 if (!
F->getParent()->getTargetTriple().isOSBinFormatCOFF())
893 return F->hasName() && !
F->hasLocalLinkage();
901 G->getLinkage(),
"",
F,
G->getParent());
905 if (FAlign || GAlign)
908 F->setAlignment(std::nullopt);
910 GA->setVisibility(
G->getVisibility());
914 G->replaceAllUsesWith(GA);
915 G->eraseFromParent();
930 std::optional<uint64_t> FEntryCount =
F.getEntryCount();
931 std::optional<uint64_t> GEntryCount =
G.getEntryCount();
933 if (!FEntryCount && !GEntryCount && AllImports.
empty())
940 if (FEntryCount || GEntryCount)
942 GEntryCount ? *GEntryCount :
uint64_t{0});
943 F.setEntryCount(Sum, AllImports.
empty() ?
nullptr : &AllImports);
952 if (!ShouldErase && !ShouldAlias && !ShouldThunk)
956 G->eraseFromParent();
974 return F->hasWeakODRLinkage() ||
F->hasLinkOnceODRLinkage();
989 if (Weight == 0 || TotalWeight == 0 || BlockCount == 0)
991 APInt Num(128, BlockCount);
992 Num *=
APInt(128, Weight);
993 APInt Den(128, TotalWeight);
994 Num = (Num + Den.
lshr(1)).
udiv(Den);
996 "scaleToBlockCount: result exceeds uint64_t; Weight > TotalWeight?");
1008 if (!HasDst && !HasSrc)
1014 uint64_t DstTotal = 0, SrcTotal = 0;
1020 assert((!HasDst || !HasSrc || DstWeights.
size() == SrcWeights.
size()) &&
1021 "equivalent branch/select instructions must have matching weight "
1023 size_t NumWeights = HasDst ? DstWeights.
size() : SrcWeights.
size();
1025 MergedWeights.
reserve(NumWeights);
1026 for (
size_t I = 0;
I < NumWeights; ++
I) {
1027 uint64_t DstW = HasDst ? DstWeights[
I] : 0;
1028 uint64_t SrcW = HasSrc ? SrcWeights[
I] : 0;
1048 for (
const InstrProfValueData &VD : VDs)
1049 Merged[VD.Value] =
SaturatingAdd(Merged[VD.Value], VD.Count);
1059 if (!HasDst && !HasSrc)
1068 if (HasDst && HasSrc && DstKind && SrcKind &&
1069 DstKind->getZExtValue() != SrcKind->getZExtValue()) {
1074 const ConstantInt *KindCI = DstKind ? DstKind : SrcKind;
1099 llvm::sort(VDs, [](
const InstrProfValueData &
A,
const InstrProfValueData &
B) {
1100 return A.Count >
B.Count;
1120 DstI.andIRFlags(&SrcI);
1122 MDNode *DstProf = DstI.getMetadata(LLVMContext::MD_prof);
1123 MDNode *SrcProf = SrcI.getMetadata(LLVMContext::MD_prof);
1134 const Instruction *SrcTerm = SrcBB->getTerminator();
1147 std::optional<uint64_t> FEntryCount =
F->getEntryCount();
1154 "if G is ODR, F must also be ODR due to ordering");
1166 F->getAddressSpace(),
"",
F->getParent());
1170 F->setComdat(
nullptr);
1176 F->replaceAllUsesWith(NewF);
1181 replaceDirectCallers(
G,
F);
1183 replaceDirectCallers(NewF,
F);
1191 mergeInstrAnnotations(
F,
G);
1194 writeThunkOrAliasIfNeeded(
F,
G);
1199 writeThunkOrAliasIfNeeded(
F, NewF);
1201 if (NewFAlign || GAlign)
1204 F->setAlignment(std::nullopt);
1207 ++NumFunctionsMerged;
1216 if (
G->hasGlobalUnnamedAddr() && !
Used.contains(
G) &&
1224 G->replaceAllUsesWith(
F);
1228 replaceDirectCallers(
G,
F);
1232 mergeInstrAnnotations(
F,
G);
1239 G->eraseFromParent();
1240 ++NumFunctionsMerged;
1244 if (writeThunkOrAliasIfNeeded(
F,
G))
1245 ++NumFunctionsMerged;
1250void MergeFunctions::replaceFunctionInTree(
const FunctionNode &FN,
1254 "The two functions must be equal");
1256 auto I = FNodesInTree.find(
F);
1257 assert(
I != FNodesInTree.end() &&
"F should be in FNodesInTree");
1258 assert(FNodesInTree.count(
G) == 0 &&
"FNodesInTree should not contain G");
1260 FnTreeType::iterator IterToFNInFnTree =
I->second;
1261 assert(&(*IterToFNInFnTree) == &FN &&
"F should map to FN in FNodesInTree.");
1263 FNodesInTree.erase(
I);
1264 FNodesInTree.insert({
G, IterToFNInFnTree});
1277 if (
F->isInterposable() !=
G->isInterposable()) {
1280 return !
F->isInterposable();
1283 if (
F->hasLocalLinkage() !=
G->hasLocalLinkage()) {
1286 return !
F->hasLocalLinkage();
1292 return F->getName() <=
G->getName();
1297bool MergeFunctions::insert(
Function *NewFunction) {
1298 std::pair<FnTreeType::iterator, bool>
Result =
1299 FnTree.insert(FunctionNode(NewFunction));
1302 assert(FNodesInTree.count(NewFunction) == 0);
1303 FNodesInTree.insert({NewFunction,
Result.first});
1309 const FunctionNode &OldF = *
Result.first;
1314 replaceFunctionInTree(*
Result.first, NewFunction);
1316 assert(OldF.getFunc() !=
F &&
"Must have swapped the functions.");
1321 Function *OldFunc = OldF.getFunc();
1324 <<
" == " << NewFunction->
getName() <<
'\n');
1327 mergeTwoFunctions(OldFunc, DeleteF);
1328 this->DelToNewMap.insert({DeleteF, OldFunc});
1334void MergeFunctions::remove(
Function *
F) {
1335 auto I = FNodesInTree.find(
F);
1336 if (
I != FNodesInTree.end()) {
1338 FnTree.erase(
I->second);
1341 FNodesInTree.erase(
I);
1342 Deferred.emplace_back(
F);
1348void MergeFunctions::removeUsers(
Value *V) {
1349 for (
User *U :
V->users())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static void mergeEntryCountsAndImportsInto(Function &F, Function &G)
static uint64_t getBlockCountForMerging(const BlockFrequencyInfo &BFI, const BasicBlock *BB)
static void mergeValueProfileOnInstructions(Instruction *DstI, const Instruction *SrcI)
static bool canCreateAliasFor(Function *F)
static bool isEligibleForMerging(Function &F)
Check whether F is eligible for function merging.
static bool isODR(const Function *F)
Returns true if F is either weak_odr or linkonce_odr.
static cl::opt< unsigned > NumFunctionsForVerificationCheck("mergefunc-verify", cl::desc("How many functions in a module could be used for " "MergeFunctions to pass a basic correctness check. " "'0' disables this check. Works only with '-debug' key."), cl::init(0), cl::Hidden)
static bool hasNonLocalAlias(const Function *F)
static DenseSet< GlobalValue::GUID > unionImportGUIDs(const Function &F, const Function &G)
static bool canCreateThunkFor(Function *F)
Whether this function may be replaced by a forwarding thunk.
static bool canBeAliasee(const Function *F)
A COFF weak external must name its target, and a local symbol has no name the linker can agree on acr...
static void addMissingCallLocations(Function *Old, Function *New)
static cl::opt< bool > MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden, cl::init(false), cl::desc("Preserve debug info in thunk when mergefunc " "transformations are made."))
static uint64_t scaleToBlockCount(uint64_t Weight, uint64_t TotalWeight, uint64_t BlockCount)
static bool hasDistinctMetadataIntrinsic(const Function &F)
Check whether F has an intrinsic which references distinct metadata as an operand.
Function * asPtr(Function *Fn)
static void addValueProfile(const Instruction &I, InstrProfValueKind Kind, DenseMap< uint64_t, uint64_t > &Merged)
static void copyMetadataIfPresent(Function *From, Function *To, StringRef Kind)
Copy all metadata of a specific kind from one function to another.
static cl::opt< bool > MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden, cl::init(false), cl::desc("Allow mergefunc to create aliases"))
static void mergeBranchWeightsOnInstructions(Instruction *DstI, const Instruction *SrcI, const BlockFrequencyInfo &DstBFI, const BlockFrequencyInfo &SrcBFI)
static bool isFuncOrderCorrect(const Function *F, const Function *G)
FunctionAnalysisManager FAM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains the declarations for profiling metadata utility functions.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Class for arbitrary precision integers.
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
unsigned getActiveBits() const
Compute the number of active bits in the value.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
an instruction to allocate memory on the stack
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents an incoming formal argument to a Function.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
Get the first element.
bool empty() const
Check if the array is empty.
Value handle that asserts if the Value is deleted.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
Analysis pass which computes BranchProbabilityInfo.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
void setAttributes(AttributeList A)
Set the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
Subprogram description. Uses SubclassData1.
LLVM_ABI void eraseFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
bool isDbgDeclare() const
Implements a dense probed hash-table based set.
FunctionComparator - Compares two functions to determine whether or not they will generate machine co...
LLVM_ABI int compare()
Test whether the two functions have equivalent behaviour.
Class to represent function types.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
MaybeAlign getAlign() const
Returns the alignment of the given function.
void setEntryCount(uint64_t Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
void erase(GlobalValue *Global)
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
Module * getParent()
Get the module that this global value is contained inside of...
@ PrivateLinkage
Like Internal, but omit from symbol table.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const MDOperand & getOperand(unsigned I) const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
LLVMContext & getContext() const
static LLVM_ABI bool runOnModule(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static LLVM_ABI DenseMap< Function *, Function * > runOnFunctions(ArrayRef< Function * > Funcs, ModuleAnalysisManager &AM)
A Module instance is used to store all the information related to an LLVM module.
Class to represent pointers.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & abandon()
Mark an analysis as abandoned.
Return a value (possibly void), from a function.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(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.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Value handle that is nullable, but tries to track the Value.
std::pair< iterator, bool > insert(const ValueT &V)
const ParentTy * getParent() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
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.
void stable_sort(R &&Range)
LLVM_ABI bool extractProfTotalWeight(const MDNode *ProfileData, uint64_t &TotalWeights)
Retrieve the total of all weights from MD_prof data.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
uint64_t stable_hash
An opaque object representing a stable hash code.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
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_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI stable_hash StructuralHash(const Function &F, bool DetailedHash=false)
Returns a hash of the function F.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
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 ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Function object to check whether the first component of a container supported by std::get (like std::...