133 using namespace llvm;
135 #define DEBUG_TYPE "mergefunc" 137 STATISTIC(NumFunctionsMerged,
"Number of functions merged");
138 STATISTIC(NumThunksWritten,
"Number of thunks generated");
139 STATISTIC(NumDoubleWeak,
"Number of new functions created");
143 cl::desc(
"How many functions in module could be used for " 144 "MergeFunctions pass sanity check. " 145 "'0' disables this check. Works only with '-debug' key."),
165 cl::desc(
"Preserve debug info in thunk when mergefunc " 166 "transformations are made."));
188 void release() { F =
nullptr; }
200 :
ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)) {
204 bool runOnModule(
Module &M)
override;
209 class FunctionNodeCmp {
215 bool operator()(
const FunctionNode &LHS,
const FunctionNode &RHS)
const {
217 if (LHS.getHash() != RHS.getHash())
218 return LHS.getHash() < RHS.getHash();
223 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
229 std::vector<WeakTrackingVH> Deferred;
234 bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
247 void removeUsers(
Value *V);
260 void filterInstsUnrelatedToPDI(
BasicBlock *GEntryBlock,
261 std::vector<Instruction *> &PDIUnrelatedWL);
268 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
276 void replaceFunctionInTree(
const FunctionNode &FN,
Function *
G);
294 INITIALIZE_PASS(MergeFunctions,
"mergefunc",
"Merge Functions",
false,
false)
297 return new MergeFunctions();
301 bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
303 unsigned TripleNumber = 0;
306 dbgs() <<
"MERGEFUNC-SANITY: Started for first " << Max <<
" functions.\n";
309 for (std::vector<WeakTrackingVH>::iterator
I = Worklist.begin(),
311 I !=
E && i < Max; ++
I, ++i) {
313 for (std::vector<WeakTrackingVH>::iterator J =
I; J !=
E && j < Max;
322 dbgs() <<
"MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
324 dbgs() << *F1 <<
'\n' << *F2 <<
'\n';
332 for (std::vector<WeakTrackingVH>::iterator K = J; K !=
E && k < Max;
333 ++k, ++K, ++TripleNumber) {
341 bool Transitive =
true;
343 if (Res1 != 0 && Res1 == Res4) {
345 Transitive = Res3 == Res1;
346 }
else if (Res3 != 0 && Res3 == -Res4) {
348 Transitive = Res3 == Res1;
349 }
else if (Res4 != 0 && -Res3 == Res4) {
351 Transitive = Res4 == -Res1;
355 dbgs() <<
"MERGEFUNC-SANITY: Non-transitive; triple: " 356 << TripleNumber <<
"\n";
357 dbgs() <<
"Res1, Res3, Res4: " << Res1 <<
", " << Res3 <<
", " 359 dbgs() << *F1 <<
'\n' << *F2 <<
'\n' << *F3 <<
'\n';
366 dbgs() <<
"MERGEFUNC-SANITY: " << (Valid ?
"Passed." :
"Failed.") <<
"\n";
373 bool MergeFunctions::runOnModule(
Module &M) {
377 bool Changed =
false;
381 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
384 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
390 HashedFuncs.begin(), HashedFuncs.end(),
391 [](
const std::pair<FunctionComparator::FunctionHash, Function *> &a,
392 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
393 return a.first < b.first;
396 auto S = HashedFuncs.begin();
397 for (
auto I = HashedFuncs.begin(),
IE = HashedFuncs.end();
I !=
IE; ++
I) {
400 if ((
I != S && std::prev(
I)->
first ==
I->first) ||
401 (std::next(
I) !=
IE && std::next(
I)->first ==
I->first) ) {
407 std::vector<WeakTrackingVH> Worklist;
408 Deferred.swap(Worklist);
413 LLVM_DEBUG(
dbgs() <<
"size of worklist: " << Worklist.size() <<
'\n');
421 Changed |= insert(F);
424 LLVM_DEBUG(
dbgs() <<
"size of FnTree: " << FnTree.size() <<
'\n');
425 }
while (!Deferred.empty());
428 GlobalNumbers.
clear();
440 if (CS && CS.isCallee(U)) {
455 for (
unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++)
456 NewArgAttrs.
push_back(NewPAL.getParamAttributes(argIdx));
460 NewPAL.getRetAttributes(),
463 remove(CS.getInstruction()->getParent()->getParent());
499 void MergeFunctions::eraseInstsUnrelatedToPDI(
500 std::vector<Instruction *> &PDIUnrelatedWL) {
502 dbgs() <<
" Erasing instructions (in reverse order of appearance in " 503 "entry block) unrelated to parameter debug info from entry " 505 while (!PDIUnrelatedWL.empty()) {
513 LLVM_DEBUG(
dbgs() <<
" } // Done erasing instructions unrelated to parameter " 514 "debug info from entry block. \n");
518 void MergeFunctions::eraseTail(
Function *
G) {
519 std::vector<BasicBlock *> WorklistBB;
522 BBI->dropAllReferences();
523 WorklistBB.push_back(&*BBI);
525 while (!WorklistBB.empty()) {
541 void MergeFunctions::filterInstsUnrelatedToPDI(
542 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
543 std::set<Instruction *> PDIRelated;
546 if (
auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
555 PDIRelated.insert(&*BI);
561 }
else if (
auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
569 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
576 if (dyn_cast<Argument>(
Arg)) {
580 PDIRelated.insert(AI);
584 PDIRelated.insert(
SI);
588 PDIRelated.insert(&*BI);
611 }
else if (dyn_cast<TerminatorInst>(BI) == GEntryBlock->
getTerminator()) {
615 PDIRelated.insert(&*BI);
624 <<
" Report parameter debug info related/related instructions: {\n");
629 if (PDIRelated.find(I) == PDIRelated.end()) {
633 PDIUnrelatedWL.push_back(I);
646 if (F->
size() == 1) {
649 <<
" is too small to bother creating a thunk for\n");
666 std::vector<Instruction *> PDIUnrelatedWL;
670 LLVM_DEBUG(
dbgs() <<
"writeThunk: (MergeFunctionsPDI) Do not create a new " 671 "function as thunk; retain original: " 675 dbgs() <<
"writeThunk: (MergeFunctionsPDI) filter parameter related " 678 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
679 GEntryBlock->getTerminator()->eraseFromParent();
697 CallInst *CI = Builder.CreateCall(F, Args);
703 RI = Builder.CreateRetVoid();
717 dbgs() <<
"writeThunk: (MergeFunctionsPDI) No DISubprogram for " 721 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
723 dbgs() <<
"} // End of parameter related debug info filtering for: " 762 ++NumFunctionsMerged;
770 GlobalNumbers.
erase(G);
777 replaceDirectCallers(G, F);
786 ++NumFunctionsMerged;
795 ++NumFunctionsMerged;
800 void MergeFunctions::replaceFunctionInTree(
const FunctionNode &FN,
804 "The two functions must be equal");
806 auto I = FNodesInTree.find(F);
807 assert(
I != FNodesInTree.end() &&
"F should be in FNodesInTree");
808 assert(FNodesInTree.count(G) == 0 &&
"FNodesInTree should not contain G");
810 FnTreeType::iterator IterToFNInFnTree =
I->second;
811 assert(&(*IterToFNInFnTree) == &FN &&
"F should map to FN in FNodesInTree.");
813 FNodesInTree.erase(
I);
814 FNodesInTree.insert({
G, IterToFNInFnTree});
821 bool MergeFunctions::insert(
Function *NewFunction) {
822 std::pair<FnTreeType::iterator, bool>
Result =
823 FnTree.insert(FunctionNode(NewFunction));
826 assert(FNodesInTree.count(NewFunction) == 0);
827 FNodesInTree.insert({NewFunction, Result.first});
833 const FunctionNode &OldF = *Result.first;
840 if ((OldF.getFunc()->isInterposable() && !NewFunction->
isInterposable()) ||
841 (OldF.getFunc()->isInterposable() == NewFunction->
isInterposable() &&
842 OldF.getFunc()->getName() > NewFunction->
getName())) {
845 replaceFunctionInTree(*Result.first, NewFunction);
847 assert(OldF.getFunc() != F &&
"Must have swapped the functions.");
851 <<
" == " << NewFunction->
getName() <<
'\n');
854 mergeTwoFunctions(OldF.getFunc(), DeleteF);
861 auto I = FNodesInTree.find(F);
862 if (
I != FNodesInTree.end()) {
864 FnTree.erase(
I->second);
867 FNodesInTree.erase(
I);
868 Deferred.emplace_back(F);
874 void MergeFunctions::removeUsers(
Value *V) {
875 std::vector<Value *> Worklist;
876 Worklist.push_back(V);
879 while (!Worklist.empty()) {
880 Value *V = Worklist.back();
885 remove(
I->getParent()->getParent());
886 }
else if (isa<GlobalValue>(U)) {
888 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
890 if (!Visited.
insert(UU).second)
891 Worklist.push_back(UU);
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getAlignment() const
void push_back(const T &Elt)
bool hasLocalLinkage() const
DILocation * get() const
Get the underlying DILocation.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
static Value * createCast(IRBuilder<> &Builder, Value *V, Type *DestTy)
Compute iterated dominance frontiers using a linear time algorithm.
Type * getParamType(unsigned i) const
Parameter type accessors.
A Module instance is used to store all the information related to an LLVM module. ...
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
ModulePass * createMergeFunctionsPass()
createMergeFunctionsPass - This pass discovers identical functions and collapses them.
This class represents a function call, abstracting a target machine's calling convention.
bool hasAvailableExternallyLinkage() const
Like Internal, but omit from symbol table.
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
STATISTIC(NumFunctions, "Total number of functions")
Type * getStructElementType(unsigned N) const
This defines the Use class.
void setAlignment(unsigned Align)
iterator begin()
Instruction iterator methods.
uint64_t FunctionHash
Hash a function.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
A Use represents the edge between a Value definition and its users.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
AttributeList getAttributes() const
Return the attribute list for this Function.
An instruction for storing to memory.
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
void initializeMergeFunctionsPass(PassRegistry &)
void erase(GlobalValue *Global)
static cl::opt< unsigned > NumFunctionsForSanityCheck("mergefunc-sanity", cl::desc("How many functions in module could be used for " "MergeFunctions pass sanity check. " "'0' disables this check. Works only with '-debug' key."), cl::init(0), cl::Hidden)
static FunctionHash functionHash(Function &)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
initializer< Ty > init(const Ty &Val)
Type * getReturnType() const
Returns the type of the ret val.
FunctionComparator - Compares two functions to determine whether or not they will generate machine co...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
DISubprogram * getSubprogram() const
Get the attached subprogram.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const Instruction & back() const
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
unsigned getStructNumElements() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static bool isThunkProfitable(Function *F)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
void setTailCall(bool isTC=true)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
void setCallingConv(CallingConv::ID CC)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
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."))
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
GlobalNumberState assigns an integer to each global value in the program, which is used by the compar...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
bool hasGlobalUnnamedAddr() const
Value handle that asserts if the Value is deleted.
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
int compare()
Test whether the two functions have equivalent behaviour.
iterator_range< user_iterator > users()
amdgpu Simplify well known AMD library false Value Value * Arg
StringRef getName() const
Return a constant reference to the value's name.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PointerType * getType() const
Global values are always pointers.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
iterator_range< arg_iterator > args()
bool isStructTy() const
True if this is an instance of StructType.
an instruction to allocate memory on the stack