1//===- MergeFunctions.cpp - Merge identical functions ---------------------===// 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 7//===----------------------------------------------------------------------===// 9// This pass looks for equivalent functions that are mergable and folds them. 11// Order relation is defined on set of functions. It was made through 12// special function comparison procedure that returns 13// 0 when functions are equal, 14// -1 when Left function is less than right function, and 15// 1 for opposite case. We need total-ordering, so we need to maintain 16// four properties on the functions set: 17// a <= a (reflexivity) 18// if a <= b and b <= a then a = b (antisymmetry) 19// if a <= b and b <= c then a <= c (transitivity). 20// for all a and b: a <= b or b <= a (totality). 22// Comparison iterates through each instruction in each basic block. 23// Functions are kept on binary tree. For each new function F we perform 24// lookup in binary tree. 25// In practice it works the following way: 26// -- We define Function* container class with custom "operator<" (FunctionPtr). 27// -- "FunctionPtr" instances are stored in std::set collection, so every 28// std::set::insert operation will give you result in log(N) time. 30// As an optimization, a hash of the function structure is calculated first, and 31// two functions are only compared if they have the same hash. This hash is 32// cheap to compute, and has the property that if function F == G according to 33// the comparison function, then hash(F) == hash(G). This consistency property 34// is critical to ensuring all possible merging opportunities are exploited. 35// Collisions in the hash affect the speed of the pass but not the correctness 36// or determinism of the resulting transformation. 38// When a match is found the functions are folded. If both functions are 39// overridable, we move the functionality into a new internal function and 40// leave two overridable thunks to it. 42//===----------------------------------------------------------------------===// 46// * virtual functions. 48// Many functions have their address taken by the virtual function table for 49// the object they belong to. However, as long as it's only used for a lookup 50// and call, this is irrelevant, and we'd like to fold such functions. 52// * be smarter about bitcasts. 54// In order to fold functions, we will sometimes add either bitcast instructions 55// or bitcast constant expressions. Unfortunately, this can confound further 56// analysis since the two functions differ where one has a bitcast and the 57// other doesn't. We should learn to look through bitcasts. 59// * Compare complex types with pointer types inside. 60// * Compare cross-reference cases. 61// * Compare complex expressions. 63// All the three issues above could be described as ability to prove that 64// fA == fB == fC == fE == fF == fG in example below: 83// Simplest cross-reference case (fA <--> fB) was implemented in previous 84// versions of MergeFunctions, though it presented only in two function pairs 85// in test-suite (that counts >50k functions) 86// Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A) 87// could cover much more cases. 89//===----------------------------------------------------------------------===// 131#define DEBUG_TYPE "mergefunc" 133STATISTIC(NumFunctionsMerged,
"Number of functions merged");
134STATISTIC(NumThunksWritten,
"Number of thunks generated");
135STATISTIC(NumAliasesWritten,
"Number of aliases generated");
136STATISTIC(NumDoubleWeak,
"Number of new functions created");
140cl::desc(
"How many functions in a module could be used for " 141"MergeFunctions to pass a basic correctness check. " 142"'0' disables this check. Works only with '-debug' key."),
145// Under option -mergefunc-preserve-debug-info we: 146// - Do not create a new function for a thunk. 147// - Retain the debug info for a thunk's parameters (and associated 148// instructions for the debug info) from the entry block. 149// Note: -debug will display the algorithm at work. 150// - Create debug-info for the call (to the shared implementation) made by 151// a thunk and its return value. 152// - Erase the rest of the function, retaining the (minimally sized) entry 153// block to create a thunk. 154// - Preserve a thunk's call site to point to the thunk even when both occur 155// within the same translation unit, to aid debugability. Note that this 156// behaviour differs from the underlying -mergefunc implementation which 157// modifies the thunk's call site to point to the shared implementation 158// when both occur within the same translation unit. 162cl::desc(
"Preserve debug info in thunk when mergefunc " 163"transformations are made."));
168cl::desc(
"Allow mergefunc to create aliases"));
177// Note the hash is recalculated potentially multiple times, but it is cheap. 183 /// Replace the reference to the function F by the function G, assuming their 184 /// implementations are equal. 190/// MergeFunctions finds functions which will generate identical machine code, 191/// by considering all pointer types to be equivalent. Once identified, 192/// MergeFunctions will fold them by replacing a call to one to a call to a 193/// bitcast of the other. 196 MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) {
199template <
typename FuncContainer>
boolrun(FuncContainer &Functions);
205// The function comparison operator is provided here so that FunctionNodes do 206// not need to become larger with another pointer. 207classFunctionNodeCmp {
213bool operator()(
const FunctionNode &LHS,
const FunctionNode &RHS)
const{
214// Order first by hashes, then full function comparison. 215if (
LHS.getHash() !=
RHS.getHash())
216returnLHS.getHash() <
RHS.getHash();
218return FCmp.compare() < 0;
221usingFnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
225 /// A work queue of functions that may have been modified and should be 227 std::vector<WeakTrackingVH> Deferred;
229 /// Set of values marked as used in llvm.used and llvm.compiler.used. 233 /// Checks the rules of order relation introduced among functions set. 234 /// Returns true, if check has been passed, and false if failed. 235bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
238 /// Insert a ComparableFunction into the FnTree, or merge it away if it's 239 /// equal to one that's already present. 242 /// Remove a Function from the FnTree and queue it up for a second sweep of 246 /// Find the functions that use this Value and remove them from FnTree and 247 /// queue the functions. 248void removeUsers(
Value *V);
250 /// Replace all direct calls of Old with calls of New. Will bitcast New if 251 /// necessary to make types match. 254 /// Merge two equivalent functions. Upon completion, G may be deleted, or may 255 /// be converted into a thunk. In either case, it should never be visited 259 /// Fill PDIUnrelatedWL with instructions from the entry block that are 260 /// unrelated to parameter related debug info. 261 /// \param PDVRUnrelatedWL The equivalent non-intrinsic debug records. 263 filterInstsUnrelatedToPDI(
BasicBlock *GEntryBlock,
264 std::vector<Instruction *> &PDIUnrelatedWL,
265 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
267 /// Erase the rest of the CFG (i.e. barring the entry block). 270 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the 271 /// parameter debug info, from the entry block. 272 /// \param PDVRUnrelatedWL contains the equivalent set of non-instruction 273 /// debug-info records. 275 eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL,
276 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
278 /// Replace G with a simple tail call to bitcast(F). Also (unless 279 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F), 283// Replace G with an alias to F (deleting function G) 286// Replace G with an alias to F if possible, or a thunk to F if possible. 287// Returns false if neither is the case. 290 /// Replace function F with function G in the function tree. 291void replaceFunctionInTree(
const FunctionNode &FN,
Function *
G);
293 /// The set of all distinct functions. Use the insert() and remove() methods 294 /// to modify it. The map allows efficient lookup and deferring of Functions. 297// Map functions to the iterators of the FunctionNode which contains them 298// in the FnTree. This must be updated carefully whenever the FnTree is 299// modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid 300// dangling iterators into FnTree. The invariant that preserves this is that 301// there is exactly one mapping F -> FN for each FunctionNode FN in FnTree. 304 /// Deleted-New functions mapping 307}
// end anonymous namespace 323 MF.getUsed().insert(UsedV.
begin(), UsedV.
end());
330return MF.runOnFunctions(
F);
334bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
336unsigned TripleNumber = 0;
339dbgs() <<
"MERGEFUNC-VERIFY: Started for first " << Max <<
" functions.\n";
342for (std::vector<WeakTrackingVH>::iterator
I = Worklist.begin(),
344I != E && i < Max; ++
I, ++i) {
346for (std::vector<WeakTrackingVH>::iterator J =
I; J != E && j < Max;
353// If F1 <= F2, then F2 >= F1, otherwise report failure. 355dbgs() <<
"MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
357dbgs() << *F1 <<
'\n' << *F2 <<
'\n';
365for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
366 ++k, ++K, ++TripleNumber) {
374bool Transitive =
true;
376if (Res1 != 0 && Res1 == Res4) {
377// F1 > F2, F2 > F3 => F1 > F3 378 Transitive = Res3 == Res1;
379 }
elseif (Res3 != 0 && Res3 == -Res4) {
380// F1 > F3, F3 > F2 => F1 > F2 381 Transitive = Res3 == Res1;
382 }
elseif (Res4 != 0 && -Res3 == Res4) {
383// F2 > F3, F3 > F1 => F2 > F1 384 Transitive = Res4 == -Res1;
388dbgs() <<
"MERGEFUNC-VERIFY: Non-transitive; triple: " 389 << TripleNumber <<
"\n";
390dbgs() <<
"Res1, Res3, Res4: " << Res1 <<
", " << Res3 <<
", " 392dbgs() << *F1 <<
'\n' << *F2 <<
'\n' << *F3 <<
'\n';
399dbgs() <<
"MERGEFUNC-VERIFY: " << (Valid ?
"Passed." :
"Failed.") <<
"\n";
406/// Check whether \p F has an intrinsic which references 407/// distinct metadata as an operand. The most common 408/// instance of this would be CFI checks for function-local types. 411for (
constInstruction &
I : BB.instructionsWithoutDebug()) {
412if (!isa<IntrinsicInst>(&
I))
416auto *MDL = dyn_cast<MetadataAsValue>(
Op);
419if (
MDNode *
N = dyn_cast<MDNode>(MDL->getMetadata()))
428/// Check whether \p F is eligible for function merging. 430return !
F.isDeclaration() && !
F.hasAvailableExternallyLinkage() &&
437template <
typename FuncContainer>
bool MergeFunctions::run(FuncContainer &M) {
440// All functions in the module, ordered by hash. Functions with a unique 441// hash value are easily eliminated. 442 std::vector<std::pair<stable_hash, Function *>> HashedFuncs;
443for (
auto &Func : M) {
452auto S = HashedFuncs.begin();
453for (
autoI = HashedFuncs.begin(), IE = HashedFuncs.end();
I != IE; ++
I) {
454// If the hash value matches the previous value or the next one, we must 455// consider merging it. Otherwise it is dropped and never considered again. 456if ((
I != S && std::prev(
I)->first ==
I->first) ||
457 (std::next(
I) != IE && std::next(
I)->first ==
I->first)) {
463 std::vector<WeakTrackingVH> Worklist;
464 Deferred.swap(Worklist);
469LLVM_DEBUG(
dbgs() <<
"size of worklist: " << Worklist.size() <<
'\n');
471// Insert functions and merge them. 476if (!
F->isDeclaration() && !
F->hasAvailableExternallyLinkage()) {
477 Changed |= insert(
F);
481 }
while (!Deferred.empty());
484 FNodesInTree.clear();
485 GlobalNumbers.
clear();
493 [[maybe_unused]]
bool MergeResult = this->
run(
F);
494assert(MergeResult == !DelToNewMap.empty());
495return this->DelToNewMap;
498// Replace direct callers of Old with New. 501CallBase *CB = dyn_cast<CallBase>(
U.getUser());
503// Do not copy attributes from the called function to the call-site. 504// Function comparison ensures that the attributes are the same up to 505// type congruences in byval(), in which case we need to keep the byval 506// type of the call-site, not the callee function. 513// Helper for writeThunk, 514// Selects proper bitcast operation, 515// but a bit simpler then CastInst::getCastOpcode. 517Type *SrcTy = V->getType();
540// Erase the instructions in PDIUnrelatedWL as they are unrelated to the 541// parameter debug info, from the entry block. 542void MergeFunctions::eraseInstsUnrelatedToPDI(
543 std::vector<Instruction *> &PDIUnrelatedWL,
544 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
546dbgs() <<
" Erasing instructions (in reverse order of appearance in " 547"entry block) unrelated to parameter debug info from entry " 549while (!PDIUnrelatedWL.empty()) {
555 PDIUnrelatedWL.pop_back();
558while (!PDVRUnrelatedWL.empty()) {
564 PDVRUnrelatedWL.pop_back();
567LLVM_DEBUG(
dbgs() <<
" } // Done erasing instructions unrelated to parameter " 568"debug info from entry block. \n");
571// Reduce G to its entry block. 572void MergeFunctions::eraseTail(
Function *
G) {
573 std::vector<BasicBlock *> WorklistBB;
575 BB.dropAllReferences();
576 WorklistBB.push_back(&BB);
578while (!WorklistBB.empty()) {
585// We are interested in the following instructions from the entry block as being 586// related to parameter debug info: 587// - @llvm.dbg.declare 588// - stores from the incoming parameters to locations on the stack-frame 589// - allocas that create these locations on the stack-frame 591// - the entry block's terminator 592// The rest are unrelated to debug info for the parameters; fill up 593// PDIUnrelatedWL with such instructions. 594void MergeFunctions::filterInstsUnrelatedToPDI(
595BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL,
596 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
597 std::set<Instruction *> PDIRelated;
598 std::set<DbgVariableRecord *> PDVRRelated;
600// Work out whether a dbg.value intrinsic or an equivalent DbgVariableRecord 601// is a parameter to be preserved. 602auto ExamineDbgValue = [](
auto *DbgVal,
auto &Container) {
611 Container.insert(DbgVal);
619auto ExamineDbgDeclare = [&PDIRelated](
auto *DbgDecl,
auto &Container) {
627AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DbgDecl->getAddress());
632if (
StoreInst *SI = dyn_cast<StoreInst>(U)) {
633if (
Value *Arg =
SI->getValueOperand()) {
634if (isa<Argument>(Arg)) {
638 PDIRelated.insert(AI);
642 PDIRelated.insert(SI);
646 Container.insert(DbgDecl);
673// Examine DbgVariableRecords as they happen "before" the instruction. Are 674// they connected to parameters? 677 ExamineDbgValue(&DVR, PDVRRelated);
680 ExamineDbgDeclare(&DVR, PDVRRelated);
684if (
auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
685 ExamineDbgValue(DVI, PDIRelated);
686 }
elseif (
auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
687 ExamineDbgDeclare(DDI, PDIRelated);
688 }
elseif (BI->isTerminator() && &*BI == GEntryBlock->
getTerminator()) {
692 PDIRelated.insert(&*BI);
701 <<
" Report parameter debug info related/related instructions: {\n");
703auto IsPDIRelated = [](
auto *Rec,
auto &Container,
auto &UnrelatedCont) {
704if (Container.find(Rec) == Container.end()) {
708 UnrelatedCont.push_back(Rec);
716// Collect the set of unrelated instructions and debug records. 719 IsPDIRelated(&DVR, PDVRRelated, PDVRUnrelatedWL);
720 IsPDIRelated(&
I, PDIRelated, PDIUnrelatedWL);
725/// Whether this function may be replaced by a forwarding thunk. 730// Don't merge tiny functions using a thunk, since it can just end up 731// making the function larger. 733if (
F->front().sizeWithoutDebug() < 2) {
735 <<
" is too small to bother creating a thunk for\n");
742/// Copy all metadata of a specific kind from one function to another. 746From->getMetadata(Kind, MDs);
751// Replace G with a simple tail call to bitcast(F). Also (unless 752// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F), 753// delete G. Under MergeFunctionsPDI, we use G itself for creating 754// the thunk as we preserve the debug info (and associated instructions) 755// from G's entry block pertaining to G's incoming arguments which are 756// passed on as corresponding arguments in the call that G makes to F. 757// For better debugability, under MergeFunctionsPDI, we do not modify G's 758// call sites to point to F even when within the same translation unit. 761 std::vector<Instruction *> PDIUnrelatedWL;
762 std::vector<DbgVariableRecord *> PDVRUnrelatedWL;
766LLVM_DEBUG(
dbgs() <<
"writeThunk: (MergeFunctionsPDI) Do not create a new " 767"function as thunk; retain original: " 768 <<
G->getName() <<
"()\n");
769 GEntryBlock = &
G->getEntryBlock();
771dbgs() <<
"writeThunk: (MergeFunctionsPDI) filter parameter related " 773 <<
G->getName() <<
"() {\n");
774 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL, PDVRUnrelatedWL);
779G->getAddressSpace(),
"",
G->getParent());
795CallInst *CI = Builder.CreateCall(
F, Args);
803if (
H->getReturnType()->isVoidTy()) {
804 RI = Builder.CreateRetVoid();
806 RI = Builder.CreateRet(
createCast(Builder, CI,
H->getReturnType()));
820dbgs() <<
"writeThunk: (MergeFunctionsPDI) No DISubprogram for " 821 <<
G->getName() <<
"()\n");
824 eraseInstsUnrelatedToPDI(PDIUnrelatedWL, PDVRUnrelatedWL);
826dbgs() <<
"} // End of parameter related debug info filtering for: " 827 <<
G->getName() <<
"()\n");
831// Ensure CFI type metadata is propagated to the new function. 835G->replaceAllUsesWith(NewG);
843// Whether this function may be replaced by an alias 848// We should only see linkages supported by aliases here 849assert(
F->hasLocalLinkage() ||
F->hasExternalLinkage()
850 ||
F->hasWeakLinkage() ||
F->hasLinkOnceLinkage());
854// Replace G with an alias to F (deleting function G) 858G->getLinkage(),
"",
F,
G->getParent());
865F->setAlignment(std::nullopt);
867 GA->setVisibility(
G->getVisibility());
871G->replaceAllUsesWith(GA);
878// Replace G with an alias to F if possible, or a thunk to F if 879// profitable. Returns false if neither is the case. 892// Merge two equivalent functions. Upon completion, Function G is deleted. 894if (
F->isInterposable()) {
897// Both writeThunkOrAlias() calls below must succeed, either because we can 898// create aliases for G and NewF, or because a thunk for F is profitable. 899// F here has the same signature as NewF below, so that's what we check. 904// Make them both thunks to the same internal function. 906F->getAddressSpace(),
"",
F->getParent());
910// Ensure CFI type metadata is propagated to the new function. 914F->replaceAllUsesWith(NewF);
916// We collect alignment before writeThunkOrAlias that overwrites NewF and 921 writeThunkOrAlias(
F,
G);
922 writeThunkOrAlias(
F, NewF);
924if (NewFAlign || GAlign)
927F->setAlignment(std::nullopt);
930 ++NumFunctionsMerged;
932// For better debugability, under MergeFunctionsPDI, we do not modify G's 933// call sites to point to F even when within the same translation unit. 935// Functions referred to by llvm.used/llvm.compiler.used are special: 936// there are uses of the symbol name that are not visible to LLVM, 937// usually from inline asm. 938if (
G->hasGlobalUnnamedAddr() && !
Used.contains(
G)) {
939// G might have been a key in our GlobalNumberState, and it's illegal 940// to replace a key in ValueMap<GlobalValue *> with a non-global. 942// If G's address is not significant, replace it entirely. 944G->replaceAllUsesWith(
F);
946// Redirect direct callers of G to F. (See note on MergeFunctionsPDI 948 replaceDirectCallers(
G,
F);
952// If G was internal then we may have replaced all uses of G with F. If so, 953// stop here and delete G. There's no need for a thunk. (See note on 954// MergeFunctionsPDI above). 957 ++NumFunctionsMerged;
961if (writeThunkOrAlias(
F,
G)) {
962 ++NumFunctionsMerged;
967/// Replace function F by function G. 968void MergeFunctions::replaceFunctionInTree(
const FunctionNode &FN,
972"The two functions must be equal");
974autoI = FNodesInTree.find(
F);
975assert(
I != FNodesInTree.end() &&
"F should be in FNodesInTree");
976assert(FNodesInTree.count(
G) == 0 &&
"FNodesInTree should not contain G");
978 FnTreeType::iterator IterToFNInFnTree =
I->second;
979assert(&(*IterToFNInFnTree) == &FN &&
"F should map to FN in FNodesInTree.");
980// Remove F -> FN and insert G -> FN 981 FNodesInTree.erase(
I);
982 FNodesInTree.insert({
G, IterToFNInFnTree});
983// Replace F with G in FN, which is stored inside the FnTree. 987// Ordering for functions that are equal under FunctionComparator 989if (
F->isInterposable() !=
G->isInterposable()) {
990// Strong before weak, because the weak function may call the strong 991// one, but not the other way around. 992return !
F->isInterposable();
994if (
F->hasLocalLinkage() !=
G->hasLocalLinkage()) {
995// External before local, because we definitely have to keep the external 996// function, but may be able to drop the local one. 997return !
F->hasLocalLinkage();
999// Impose a total order (by name) on the replacement of functions. This is 1000// important when operating on more than one module independently to prevent 1001// cycles of thunks calling each other when the modules are linked together. 1002returnF->getName() <=
G->getName();
1005// Insert a ComparableFunction into the FnTree, or merge it away if equal to one 1006// that was already inserted. 1007bool MergeFunctions::insert(
Function *NewFunction) {
1008 std::pair<FnTreeType::iterator, bool>
Result =
1009 FnTree.insert(FunctionNode(NewFunction));
1012assert(FNodesInTree.count(NewFunction) == 0);
1013 FNodesInTree.insert({NewFunction,
Result.first});
1019const FunctionNode &OldF = *
Result.first;
1022// Swap the two functions. 1024 replaceFunctionInTree(*
Result.first, NewFunction);
1026assert(OldF.getFunc() !=
F &&
"Must have swapped the functions.");
1030 <<
" == " << NewFunction->
getName() <<
'\n');
1033 mergeTwoFunctions(OldF.getFunc(), DeleteF);
1034 this->DelToNewMap.insert({DeleteF, OldF.getFunc()});
1038// Remove a function from FnTree. If it was already in FnTree, add 1039// it to Deferred so that we'll look at it in the next round. 1040void MergeFunctions::remove(
Function *
F) {
1041autoI = FNodesInTree.find(
F);
1042if (
I != FNodesInTree.end()) {
1044 FnTree.erase(
I->second);
1045// I->second has been invalidated, remove it from the FNodesInTree map to 1046// preserve the invariant. 1047 FNodesInTree.erase(
I);
1048 Deferred.emplace_back(
F);
1052// For each instruction used by the value, remove() the function that contains 1053// the instruction. This should happen right before a call to RAUW. 1054void MergeFunctions::removeUsers(
Value *V) {
1055for (
User *U :
V->users())
1056if (
auto *
I = dyn_cast<Instruction>(U))
BlockVerifier::State From
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Value * createCast(IRBuilder<> &Builder, Value *V, Type *DestTy)
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static bool canCreateAliasFor(Function *F)
static bool isEligibleForMerging(Function &F)
Check whether F is eligible for function merging.
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 canCreateThunkFor(Function *F)
Whether this function may be replaced by a forwarding thunk.
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 bool hasDistinctMetadataIntrinsic(const Function &F)
Check whether F has an intrinsic which references distinct metadata as an operand.
Function * asPtr(Function *Fn)
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 bool isFuncOrderCorrect(const Function *F, const Function *G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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)
an instruction to allocate memory on the stack
A container for analyses that lazily runs them and caches their results.
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
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.
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 if the block is well formed or null if the block is not well forme...
const Instruction & back() const
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 class represents an Operation in the Expression.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
void print(raw_ostream &O, bool IsForDebug=false) const
bool isDbgDeclare() const
FunctionComparator - Compares two functions to determine whether or not they will generate machine co...
int compare()
Test whether the two functions have equivalent behaviour.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
bool IsNewDbgInfoFormat
Is this function using intrinsics to record the position of debugging information,...
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
static 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...
GlobalNumberState assigns an integer to each global value in the program, which is used by the compar...
void erase(GlobalValue *Global)
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
void setComdat(Comdat *C)
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
@ PrivateLinkage
Like Internal, but omit from symbol table.
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const Function * getFunction() const
Return the function this instruction belongs to.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
LLVMContext & getContext() const
static DenseMap< Function *, Function * > runOnFunctions(ArrayRef< Function * > F)
static bool runOnModule(Module &M)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
A Module instance is used to store all the information related to an LLVM module.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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.
Return a value (possibly void), from a function.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
StringRef - Represent a constant reference to a string, i.e.
The instances of the Type class are immutable: once they are created, they are never changed.
Type * getStructElementType(unsigned N) const
bool isPointerTy() const
True if this is an instance of PointerType.
unsigned getStructNumElements() const
bool isStructTy() const
True if this is an instance of StructType.
bool isIntegerTy() const
True if this is an instance of IntegerType.
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
iterator_range< user_iterator > users()
iterator_range< use_iterator > uses()
StringRef getName() const
Return a constant reference to the value's name.
void takeName(Value *V)
Transfer the name from V to this value.
Value handle that is nullable, but tries to track the Value.
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.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
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)
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...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
stable_hash StructuralHash(const Function &F, bool DetailedHash=false)
Returns a hash of the function F.
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::...