134 using namespace llvm;
136 #define DEBUG_TYPE "mergefunc" 138 STATISTIC(NumFunctionsMerged,
"Number of functions merged");
139 STATISTIC(NumThunksWritten,
"Number of thunks generated");
140 STATISTIC(NumAliasesWritten,
"Number of aliases generated");
141 STATISTIC(NumDoubleWeak,
"Number of new functions created");
145 cl::desc(
"How many functions in module could be used for " 146 "MergeFunctions pass sanity check. " 147 "'0' disables this check. Works only with '-debug' key."),
167 cl::desc(
"Preserve debug info in thunk when mergefunc " 168 "transformations are made."));
173 cl::desc(
"Allow mergefunc to create aliases"));
200 class MergeFunctions {
202 MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) {
205 bool runOnModule(
Module &M);
210 class FunctionNodeCmp {
216 bool operator()(
const FunctionNode &LHS,
const FunctionNode &RHS)
const {
218 if (LHS.getHash() != RHS.getHash())
219 return LHS.getHash() < RHS.getHash();
224 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
230 std::vector<WeakTrackingVH> Deferred;
235 bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
248 void removeUsers(
Value *V);
261 void filterInstsUnrelatedToPDI(
BasicBlock *GEntryBlock,
262 std::vector<Instruction *> &PDIUnrelatedWL);
269 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
284 void replaceFunctionInTree(
const FunctionNode &FN,
Function *
G);
298 class MergeFunctionsLegacyPass :
public ModulePass {
306 bool runOnModule(
Module &M)
override {
311 return MF.runOnModule(M);
319 "Merge Functions",
false,
false)
322 return new MergeFunctionsLegacyPass();
328 if (!MF.runOnModule(M))
334 bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
336 unsigned TripleNumber = 0;
339 dbgs() <<
"MERGEFUNC-SANITY: Started for first " << Max <<
" functions.\n";
342 for (std::vector<WeakTrackingVH>::iterator
I = Worklist.begin(),
344 I !=
E && i < Max; ++
I, ++i) {
346 for (std::vector<WeakTrackingVH>::iterator J =
I; J !=
E && j < Max;
355 dbgs() <<
"MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
357 dbgs() << *F1 <<
'\n' << *F2 <<
'\n';
365 for (std::vector<WeakTrackingVH>::iterator K = J; K !=
E && k < Max;
366 ++k, ++K, ++TripleNumber) {
374 bool Transitive =
true;
376 if (Res1 != 0 && Res1 == Res4) {
378 Transitive = Res3 == Res1;
379 }
else if (Res3 != 0 && Res3 == -Res4) {
381 Transitive = Res3 == Res1;
382 }
else if (Res4 != 0 && -Res3 == Res4) {
384 Transitive = Res4 == -Res1;
388 dbgs() <<
"MERGEFUNC-SANITY: Non-transitive; triple: " 389 << TripleNumber <<
"\n";
390 dbgs() <<
"Res1, Res3, Res4: " << Res1 <<
", " << Res3 <<
", " 392 dbgs() << *F1 <<
'\n' << *F2 <<
'\n' << *F3 <<
'\n';
399 dbgs() <<
"MERGEFUNC-SANITY: " << (Valid ?
"Passed." :
"Failed.") <<
"\n";
411 bool MergeFunctions::runOnModule(
Module &M) {
412 bool Changed =
false;
416 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
426 auto S = HashedFuncs.begin();
427 for (
auto I = HashedFuncs.begin(),
IE = HashedFuncs.end();
I !=
IE; ++
I) {
430 if ((
I != S && std::prev(
I)->
first ==
I->first) ||
431 (std::next(
I) !=
IE && std::next(
I)->first ==
I->first) ) {
437 std::vector<WeakTrackingVH> Worklist;
438 Deferred.swap(Worklist);
443 LLVM_DEBUG(
dbgs() <<
"size of worklist: " << Worklist.size() <<
'\n');
451 Changed |= insert(F);
454 LLVM_DEBUG(
dbgs() <<
"size of FnTree: " << FnTree.size() <<
'\n');
455 }
while (!Deferred.empty());
458 FNodesInTree.clear();
459 GlobalNumbers.
clear();
471 if (CS && CS.isCallee(U)) {
476 remove(CS.getInstruction()->getFunction());
512 void MergeFunctions::eraseInstsUnrelatedToPDI(
513 std::vector<Instruction *> &PDIUnrelatedWL) {
515 dbgs() <<
" Erasing instructions (in reverse order of appearance in " 516 "entry block) unrelated to parameter debug info from entry " 518 while (!PDIUnrelatedWL.empty()) {
526 LLVM_DEBUG(
dbgs() <<
" } // Done erasing instructions unrelated to parameter " 527 "debug info from entry block. \n");
531 void MergeFunctions::eraseTail(
Function *
G) {
532 std::vector<BasicBlock *> WorklistBB;
535 BBI->dropAllReferences();
536 WorklistBB.push_back(&*BBI);
538 while (!WorklistBB.empty()) {
554 void MergeFunctions::filterInstsUnrelatedToPDI(
555 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
556 std::set<Instruction *> PDIRelated;
559 if (
auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
568 PDIRelated.insert(&*BI);
574 }
else if (
auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
582 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
589 if (dyn_cast<Argument>(
Arg)) {
593 PDIRelated.insert(AI);
597 PDIRelated.insert(
SI);
601 PDIRelated.insert(&*BI);
624 }
else if (BI->isTerminator() && &*BI == GEntryBlock->
getTerminator()) {
628 PDIRelated.insert(&*BI);
637 <<
" Report parameter debug info related/related instructions: {\n");
642 if (PDIRelated.find(I) == PDIRelated.end()) {
646 PDIUnrelatedWL.push_back(I);
663 if (F->
size() == 1) {
666 <<
" is too small to bother creating a thunk for\n");
683 std::vector<Instruction *> PDIUnrelatedWL;
687 LLVM_DEBUG(
dbgs() <<
"writeThunk: (MergeFunctionsPDI) Do not create a new " 688 "function as thunk; retain original: " 692 dbgs() <<
"writeThunk: (MergeFunctionsPDI) filter parameter related " 695 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
696 GEntryBlock->getTerminator()->eraseFromParent();
715 CallInst *CI = Builder.CreateCall(F, Args);
721 RI = Builder.CreateRetVoid();
735 dbgs() <<
"writeThunk: (MergeFunctionsPDI) No DISubprogram for " 739 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
741 dbgs() <<
"} // End of parameter related debug info filtering for: " 771 PtrType->getElementType(), PtrType->getAddressSpace(),
823 writeThunkOrAlias(F, G);
824 writeThunkOrAlias(F, NewF);
829 ++NumFunctionsMerged;
837 GlobalNumbers.
erase(G);
845 replaceDirectCallers(G, F);
854 ++NumFunctionsMerged;
858 if (writeThunkOrAlias(F, G)) {
859 ++NumFunctionsMerged;
865 void MergeFunctions::replaceFunctionInTree(
const FunctionNode &FN,
869 "The two functions must be equal");
871 auto I = FNodesInTree.find(F);
872 assert(
I != FNodesInTree.end() &&
"F should be in FNodesInTree");
873 assert(FNodesInTree.count(G) == 0 &&
"FNodesInTree should not contain G");
875 FnTreeType::iterator IterToFNInFnTree =
I->second;
876 assert(&(*IterToFNInFnTree) == &FN &&
"F should map to FN in FNodesInTree.");
878 FNodesInTree.erase(
I);
879 FNodesInTree.insert({
G, IterToFNInFnTree});
904 bool MergeFunctions::insert(
Function *NewFunction) {
905 std::pair<FnTreeType::iterator, bool> Result =
906 FnTree.insert(FunctionNode(NewFunction));
909 assert(FNodesInTree.count(NewFunction) == 0);
910 FNodesInTree.insert({NewFunction, Result.first});
916 const FunctionNode &OldF = *Result.first;
921 replaceFunctionInTree(*Result.first, NewFunction);
923 assert(OldF.getFunc() != F &&
"Must have swapped the functions.");
927 <<
" == " << NewFunction->
getName() <<
'\n');
930 mergeTwoFunctions(OldF.getFunc(), DeleteF);
937 auto I = FNodesInTree.find(F);
938 if (
I != FNodesInTree.end()) {
940 FnTree.erase(
I->second);
943 FNodesInTree.erase(
I);
944 Deferred.emplace_back(F);
950 void MergeFunctions::removeUsers(
Value *V) {
952 if (
auto *
I = dyn_cast<Instruction>(U))
953 remove(
I->getFunction());
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
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
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...
This class represents an incoming formal argument to a Function.
static Value * createCast(IRBuilder<> &Builder, Value *V, Type *DestTy)
This class represents lattice values for constants.
ModulePass * createMergeFunctionsPass()
createMergeFunctionsPass - This pass discovers identical functions and collapses them.
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.
void push_back(const T &Elt)
static bool isFuncOrderCorrect(const Function *F, const Function *G)
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
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...
This defines the Use class.
iterator begin()
Instruction iterator methods.
uint64_t FunctionHash
Hash a function.
static bool isEligibleForMerging(Function &F)
Check whether F is eligible for function merging.
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 file contains the simple types necessary to represent the attributes associated with functions a...
void initializeMergeFunctionsLegacyPassPass(PassRegistry &)
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
bool hasExternalLinkage() const
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 setComdat(Comdat *C)
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.
bool hasLinkOnceLinkage() const
void takeName(Value *V)
Transfer the name from V to this value.
static bool canCreateAliasFor(Function *F)
void erase(GlobalValue *Global)
Class to represent pointers.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
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
INITIALIZE_PASS(MergeFunctionsLegacyPass, "mergefunc", "Merge Functions", false, false) ModulePass *llvm
initializer< Ty > init(const Ty &Val)
Type * getReturnType() const
Returns the type of the ret val.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
FunctionComparator - Compares two functions to determine whether or not they will generate machine co...
A set of analyses that are preserved following a run of a transformation pass.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
VisibilityTypes getVisibility() const
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.
const Instruction & back() const
unsigned getAddressSpace() const
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
void setCallingConv(CallingConv::ID CC)
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit...
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
unsigned getStructNumElements() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
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.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
bool hasWeakLinkage() 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."))
Iterator for intrusive lists based on ilist_node.
static bool canCreateThunkFor(Function *F)
Whether this function may be replaced by a forwarding thunk.
Align max(MaybeAlign Lhs, Align Rhs)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
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()
static cl::opt< bool > MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden, cl::init(false), cl::desc("Allow mergefunc to create aliases"))
const Comdat * getComdat() const
void setAlignment(MaybeAlign Align)
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 setAttributes(AttributeList A)
Set the parameter attributes for this call.
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
void stable_sort(R &&Range)
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
A container for analyses that lazily runs them and caches their results.
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Function object to check whether the first component of a std::pair compares less than the first comp...
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...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PointerType * getType() const
Global values are always pointers.
iterator_range< arg_iterator > args()
bool isStructTy() const
True if this is an instance of StructType.
an instruction to allocate memory on the stack