116 using namespace llvm;
118 #define DEBUG_TYPE "mergefunc"
120 STATISTIC(NumFunctionsMerged,
"Number of functions merged");
121 STATISTIC(NumThunksWritten,
"Number of thunks generated");
122 STATISTIC(NumAliasesWritten,
"Number of aliases generated");
123 STATISTIC(NumDoubleWeak,
"Number of new functions created");
127 cl::desc(
"How many functions in module could be used for "
128 "MergeFunctions pass sanity check. "
129 "'0' disables this check. Works only with '-debug' key."),
149 cl::desc(
"Preserve debug info in thunk when mergefunc "
150 "transformations are made."));
182 :
ModulePass(
ID), FnTree(FunctionNodeCmp(&GlobalNumbers)), FNodesInTree(),
183 HasGlobalAliases(
false) {
187 bool runOnModule(
Module &M)
override;
192 class FunctionNodeCmp {
196 bool operator()(
const FunctionNode &LHS,
const FunctionNode &RHS)
const {
198 if (LHS.getHash() != RHS.getHash())
199 return LHS.getHash() < RHS.getHash();
204 typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType;
210 std::vector<WeakTrackingVH> Deferred;
215 bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
228 void removeUsers(
Value *V);
244 void filterInstsUnrelatedToPDI(
BasicBlock *GEntryBlock,
245 std::vector<Instruction *> &PDIUnrelatedWL);
252 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
263 void replaceFunctionInTree(
const FunctionNode &FN,
Function *
G);
276 bool HasGlobalAliases;
282 INITIALIZE_PASS(MergeFunctions,
"mergefunc",
"Merge Functions",
false,
false)
285 return new MergeFunctions();
289 bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
291 unsigned TripleNumber = 0;
294 dbgs() <<
"MERGEFUNC-SANITY: Started for first " << Max <<
" functions.\n";
297 for (std::vector<WeakTrackingVH>::iterator
I = Worklist.begin(),
299 I !=
E && i < Max; ++
I, ++i) {
301 for (std::vector<WeakTrackingVH>::iterator J =
I; J !=
E && j < Max;
310 dbgs() <<
"MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
312 dbgs() << *F1 <<
'\n' << *F2 <<
'\n';
320 for (std::vector<WeakTrackingVH>::iterator K = J; K !=
E && k < Max;
321 ++k, ++K, ++TripleNumber) {
329 bool Transitive =
true;
331 if (Res1 != 0 && Res1 == Res4) {
333 Transitive = Res3 == Res1;
334 }
else if (Res3 != 0 && Res3 == -Res4) {
336 Transitive = Res3 == Res1;
337 }
else if (Res4 != 0 && -Res3 == Res4) {
339 Transitive = Res4 == -Res1;
343 dbgs() <<
"MERGEFUNC-SANITY: Non-transitive; triple: "
344 << TripleNumber <<
"\n";
345 dbgs() <<
"Res1, Res3, Res4: " << Res1 <<
", " << Res3 <<
", "
347 dbgs() << *F1 <<
'\n' << *F2 <<
'\n' << *F3 <<
'\n';
354 dbgs() <<
"MERGEFUNC-SANITY: " << (Valid ?
"Passed." :
"Failed.") <<
"\n";
361 bool MergeFunctions::runOnModule(
Module &M) {
365 bool Changed =
false;
369 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
372 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
378 HashedFuncs.begin(), HashedFuncs.end(),
379 [](
const std::pair<FunctionComparator::FunctionHash, Function *> &a,
380 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
381 return a.first < b.first;
384 auto S = HashedFuncs.begin();
385 for (
auto I = HashedFuncs.begin(),
IE = HashedFuncs.end(); I !=
IE; ++
I) {
388 if ((I != S && std::prev(I)->
first == I->first) ||
389 (std::next(I) !=
IE && std::next(I)->first == I->first) ) {
395 std::vector<WeakTrackingVH> Worklist;
396 Deferred.swap(Worklist);
398 DEBUG(doSanityCheck(Worklist));
400 DEBUG(
dbgs() <<
"size of module: " << M.size() <<
'\n');
401 DEBUG(
dbgs() <<
"size of worklist: " << Worklist.size() <<
'\n');
409 Changed |= insert(F);
412 DEBUG(
dbgs() <<
"size of FnTree: " << FnTree.size() <<
'\n');
413 }
while (!Deferred.empty());
416 GlobalNumbers.clear();
428 if (CS &&
CS.isCallee(U)) {
443 for (
unsigned argIdx = 0; argIdx <
CS.arg_size(); argIdx++)
444 NewArgAttrs.
push_back(NewPAL.getParamAttributes(argIdx));
448 NewPAL.getRetAttributes(),
451 remove(
CS.getInstruction()->getParent()->getParent());
500 void MergeFunctions::eraseInstsUnrelatedToPDI(
501 std::vector<Instruction *> &PDIUnrelatedWL) {
503 DEBUG(
dbgs() <<
" Erasing instructions (in reverse order of appearance in "
504 "entry block) unrelated to parameter debug info from entry "
506 while (!PDIUnrelatedWL.empty()) {
508 DEBUG(
dbgs() <<
" Deleting Instruction: ");
514 DEBUG(
dbgs() <<
" } // Done erasing instructions unrelated to parameter "
515 "debug info from entry block. \n");
519 void MergeFunctions::eraseTail(
Function *G) {
521 std::vector<BasicBlock *> WorklistBB;
524 BBI->dropAllReferences();
525 WorklistBB.push_back(&*BBI);
527 while (!WorklistBB.empty()) {
543 void MergeFunctions::filterInstsUnrelatedToPDI(
544 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
546 std::set<Instruction *> PDIRelated;
549 if (
auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
555 DEBUG(
dbgs() <<
" Include (parameter): ");
558 PDIRelated.insert(&*BI);
560 DEBUG(
dbgs() <<
" Delete (!parameter): ");
564 }
else if (
auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
572 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
574 DEBUG(
dbgs() <<
" Processing alloca users: ");
577 if (
StoreInst *SI = dyn_cast<StoreInst>(U)) {
578 if (
Value *Arg =
SI->getValueOperand()) {
579 if (dyn_cast<Argument>(Arg)) {
583 PDIRelated.insert(AI);
584 DEBUG(
dbgs() <<
" Include (parameter): ");
587 PDIRelated.insert(SI);
591 PDIRelated.insert(&*BI);
593 DEBUG(
dbgs() <<
" Delete (!parameter): ");
605 DEBUG(
dbgs() <<
" Delete (alloca NULL): ");
610 DEBUG(
dbgs() <<
" Delete (!parameter): ");
614 }
else if (dyn_cast<TerminatorInst>(BI) == GEntryBlock->
getTerminator()) {
615 DEBUG(
dbgs() <<
" Will Include Terminator: ");
618 PDIRelated.insert(&*BI);
626 <<
" Report parameter debug info related/related instructions: {\n");
631 if (PDIRelated.find(I) == PDIRelated.end()) {
635 PDIUnrelatedWL.push_back(I);
657 replaceDirectCallers(G, F);
669 std::vector<Instruction *> PDIUnrelatedWL;
673 DEBUG(
dbgs() <<
"writeThunk: (MergeFunctionsPDI) Do not create a new "
674 "function as thunk; retain original: "
677 DEBUG(
dbgs() <<
"writeThunk: (MergeFunctionsPDI) filter parameter related "
680 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
681 GEntryBlock->getTerminator()->eraseFromParent();
699 CallInst *CI = Builder.CreateCall(F, Args);
705 RI = Builder.CreateRetVoid();
718 DEBUG(
dbgs() <<
"writeThunk: (MergeFunctionsPDI) No DISubprogram for "
722 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
723 DEBUG(
dbgs() <<
"} // End of parameter related debug info filtering for: "
747 DEBUG(
dbgs() <<
"writeAlias: " << GA->getName() <<
'\n');
766 if (HasGlobalAliases) {
778 writeThunkOrAlias(F, G);
781 ++NumFunctionsMerged;
785 void MergeFunctions::replaceFunctionInTree(
const FunctionNode &FN,
789 "The two functions must be equal");
791 auto I = FNodesInTree.find(F);
792 assert(I != FNodesInTree.end() &&
"F should be in FNodesInTree");
793 assert(FNodesInTree.count(G) == 0 &&
"FNodesInTree should not contain G");
795 FnTreeType::iterator IterToFNInFnTree = I->second;
796 assert(&(*IterToFNInFnTree) == &FN &&
"F should map to FN in FNodesInTree.");
798 FNodesInTree.erase(I);
799 FNodesInTree.insert({
G, IterToFNInFnTree});
806 bool MergeFunctions::insert(
Function *NewFunction) {
807 std::pair<FnTreeType::iterator, bool> Result =
808 FnTree.insert(FunctionNode(NewFunction));
811 assert(FNodesInTree.count(NewFunction) == 0);
812 FNodesInTree.insert({NewFunction, Result.first});
817 const FunctionNode &OldF = *Result.first;
823 if (NewFunction->
size() == 1) {
826 <<
" is to small to bother merging\n");
836 if ((OldF.getFunc()->isInterposable() && !NewFunction->
isInterposable()) ||
837 (OldF.getFunc()->isInterposable() == NewFunction->
isInterposable() &&
838 OldF.getFunc()->getName() > NewFunction->
getName())) {
841 replaceFunctionInTree(*Result.first, NewFunction);
843 assert(OldF.getFunc() != F &&
"Must have swapped the functions.");
846 DEBUG(
dbgs() <<
" " << OldF.getFunc()->getName()
847 <<
" == " << NewFunction->
getName() <<
'\n');
850 mergeTwoFunctions(OldF.getFunc(), DeleteF);
857 auto I = FNodesInTree.find(F);
858 if (I != FNodesInTree.end()) {
860 FnTree.erase(I->second);
863 FNodesInTree.erase(I);
864 Deferred.emplace_back(F);
870 void MergeFunctions::removeUsers(
Value *V) {
871 std::vector<Value *> Worklist;
872 Worklist.push_back(V);
875 while (!Worklist.empty()) {
876 Value *V = Worklist.back();
882 }
else if (isa<GlobalValue>(U)) {
884 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
885 for (
User *UU :
C->users()) {
886 if (!Visited.
insert(UU).second)
887 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.
void push_back(const T &Elt)
LinkageTypes getLinkage() const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
VisibilityTypes getVisibility() const
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
const Instruction & back() const
static Value * createCast(IRBuilder<> &Builder, Value *V, Type *DestTy)
STATISTIC(NumFunctions,"Total number of functions")
unsigned getStructNumElements() const
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.
Like Internal, but omit from symbol table.
bool hasAvailableExternallyLinkage() const
const Function * getParent() const
Return the enclosing method, or null if none.
void setAlignment(unsigned Align)
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
void setCallingConv(CallingConv::ID CC)
AttributeList getAttributes() const
Return the attribute list for this Function.
DILocation * get() const
Get the underlying DILocation.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
A Use represents the edge between a Value definition and its users.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Value handle that is nullable, but tries to track the Value.
Type * getStructElementType(unsigned N) const
unsigned getAlignment() const
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."))
An instruction for storing to memory.
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 &)
static FunctionHash functionHash(Function &)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Function Alias Analysis false
Type * getReturnType() const
Returns the type of the ret val.
Type * getParamType(unsigned i) const
Parameter type accessors.
initializer< Ty > init(const Ty &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...
FunctionType * getFunctionType() const
Returns the FunctionType for me.
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 ...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void setTailCall(bool isTC=true)
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool hasWeakLinkage() const
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
uint64_t FunctionHash
Hash a function.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
bool hasExternalLinkage() const
Iterator for intrusive lists based on ilist_node.
bool hasGlobalUnnamedAddr() const
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.
Type * getType() const
All values are typed, get the type of this value.
const BasicBlock & getEntryBlock() 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.
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool isIntegerTy() const
True if this is an instance of IntegerType.
int compare()
Test whether the two functions have equivalent behaviour.
iterator_range< user_iterator > users()
bool isStructTy() const
True if this is an instance of StructType.
PointerType * getType() const
Global values are always pointers.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
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)
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...
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
bool hasLocalLinkage() const
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.
std::string Hash(const Unit &U)
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="")
const BasicBlock * getParent() const
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...
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 isVoidTy() const
Return true if this is 'void'.
an instruction to allocate memory on the stack