1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass looks for equivalent functions that are mergable and folds them.
12 // Order relation is defined on set of functions. It was made through
13 // special function comparison procedure that returns
14 // 0 when functions are equal,
15 // -1 when Left function is less than right function, and
16 // 1 for opposite case. We need total-ordering, so we need to maintain
17 // four properties on the functions set:
18 // a <= a (reflexivity)
19 // if a <= b and b <= a then a = b (antisymmetry)
20 // if a <= b and b <= c then a <= c (transitivity).
21 // for all a and b: a <= b or b <= a (totality).
23 // Comparison iterates through each instruction in each basic block.
24 // Functions are kept on binary tree. For each new function F we perform
25 // lookup in binary tree.
26 // In practice it works the following way:
27 // -- We define Function* container class with custom "operator<" (FunctionPtr).
28 // -- "FunctionPtr" instances are stored in std::set collection, so every
29 // std::set::insert operation will give you result in log(N) time.
31 // As an optimization, a hash of the function structure is calculated first, and
32 // two functions are only compared if they have the same hash. This hash is
33 // cheap to compute, and has the property that if function F == G according to
34 // the comparison function, then hash(F) == hash(G). This consistency property
35 // is critical to ensuring all possible merging opportunities are exploited.
36 // Collisions in the hash affect the speed of the pass but not the correctness
37 // or determinism of the resulting transformation.
39 // When a match is found the functions are folded. If both functions are
40 // overridable, we move the functionality into a new internal function and
41 // leave two overridable thunks to it.
43 //===----------------------------------------------------------------------===//
47 // * virtual functions.
49 // Many functions have their address taken by the virtual function table for
50 // the object they belong to. However, as long as it's only used for a lookup
51 // and call, this is irrelevant, and we'd like to fold such functions.
53 // * be smarter about bitcasts.
55 // In order to fold functions, we will sometimes add either bitcast instructions
56 // or bitcast constant expressions. Unfortunately, this can confound further
57 // analysis since the two functions differ where one has a bitcast and the
58 // other doesn't. We should learn to look through bitcasts.
60 // * Compare complex types with pointer types inside.
61 // * Compare cross-reference cases.
62 // * Compare complex expressions.
64 // All the three issues above could be described as ability to prove that
65 // fA == fB == fC == fE == fF == fG in example below:
84 // Simplest cross-reference case (fA <--> fB) was implemented in previous
85 // versions of MergeFunctions, though it presented only in two function pairs
86 // in test-suite (that counts >50k functions)
87 // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
88 // could cover much more cases.
90 //===----------------------------------------------------------------------===//
92 #include "llvm/ADT/ArrayRef.h"
93 #include "llvm/ADT/SmallPtrSet.h"
94 #include "llvm/ADT/SmallVector.h"
95 #include "llvm/ADT/Statistic.h"
96 #include "llvm/IR/Argument.h"
97 #include "llvm/IR/Attributes.h"
98 #include "llvm/IR/BasicBlock.h"
99 #include "llvm/IR/CallSite.h"
100 #include "llvm/IR/Constant.h"
101 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/DebugInfoMetadata.h"
103 #include "llvm/IR/DebugLoc.h"
104 #include "llvm/IR/DerivedTypes.h"
105 #include "llvm/IR/Function.h"
106 #include "llvm/IR/GlobalValue.h"
107 #include "llvm/IR/IRBuilder.h"
108 #include "llvm/IR/InstrTypes.h"
109 #include "llvm/IR/Instruction.h"
110 #include "llvm/IR/Instructions.h"
111 #include "llvm/IR/IntrinsicInst.h"
112 #include "llvm/IR/Module.h"
113 #include "llvm/IR/Type.h"
114 #include "llvm/IR/Use.h"
115 #include "llvm/IR/User.h"
116 #include "llvm/IR/Value.h"
117 #include "llvm/IR/ValueHandle.h"
118 #include "llvm/IR/ValueMap.h"
119 #include "llvm/Pass.h"
120 #include "llvm/Support/Casting.h"
121 #include "llvm/Support/CommandLine.h"
122 #include "llvm/Support/Debug.h"
123 #include "llvm/Support/raw_ostream.h"
124 #include "llvm/Transforms/IPO.h"
125 #include "llvm/Transforms/Utils/FunctionComparator.h"
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(NumAliasesWritten, "Number of aliases generated");
140 STATISTIC(NumDoubleWeak, "Number of new functions created");
142 static cl::opt<unsigned> NumFunctionsForSanityCheck(
144 cl::desc("How many functions in module could be used for "
145 "MergeFunctions pass sanity check. "
146 "'0' disables this check. Works only with '-debug' key."),
147 cl::init(0), cl::Hidden);
149 // Under option -mergefunc-preserve-debug-info we:
150 // - Do not create a new function for a thunk.
151 // - Retain the debug info for a thunk's parameters (and associated
152 // instructions for the debug info) from the entry block.
153 // Note: -debug will display the algorithm at work.
154 // - Create debug-info for the call (to the shared implementation) made by
155 // a thunk and its return value.
156 // - Erase the rest of the function, retaining the (minimally sized) entry
157 // block to create a thunk.
158 // - Preserve a thunk's call site to point to the thunk even when both occur
159 // within the same translation unit, to aid debugability. Note that this
160 // behaviour differs from the underlying -mergefunc implementation which
161 // modifies the thunk's call site to point to the shared implementation
162 // when both occur within the same translation unit.
164 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
166 cl::desc("Preserve debug info in thunk when mergefunc "
167 "transformations are made."));
170 MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
172 cl::desc("Allow mergefunc to create aliases"));
177 mutable AssertingVH<Function> F;
178 FunctionComparator::FunctionHash Hash;
181 // Note the hash is recalculated potentially multiple times, but it is cheap.
182 FunctionNode(Function *F)
183 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
185 Function *getFunc() const { return F; }
186 FunctionComparator::FunctionHash getHash() const { return Hash; }
188 /// Replace the reference to the function F by the function G, assuming their
189 /// implementations are equal.
190 void replaceBy(Function *G) const {
194 void release() { F = nullptr; }
197 /// MergeFunctions finds functions which will generate identical machine code,
198 /// by considering all pointer types to be equivalent. Once identified,
199 /// MergeFunctions will fold them by replacing a call to one to a call to a
200 /// bitcast of the other.
201 class MergeFunctions : public ModulePass {
206 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)) {
207 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
210 bool runOnModule(Module &M) override;
213 // The function comparison operator is provided here so that FunctionNodes do
214 // not need to become larger with another pointer.
215 class FunctionNodeCmp {
216 GlobalNumberState* GlobalNumbers;
219 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
221 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
222 // Order first by hashes, then full function comparison.
223 if (LHS.getHash() != RHS.getHash())
224 return LHS.getHash() < RHS.getHash();
225 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
226 return FCmp.compare() == -1;
229 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
231 GlobalNumberState GlobalNumbers;
233 /// A work queue of functions that may have been modified and should be
235 std::vector<WeakTrackingVH> Deferred;
238 /// Checks the rules of order relation introduced among functions set.
239 /// Returns true, if sanity check has been passed, and false if failed.
240 bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
243 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
244 /// equal to one that's already present.
245 bool insert(Function *NewFunction);
247 /// Remove a Function from the FnTree and queue it up for a second sweep of
249 void remove(Function *F);
251 /// Find the functions that use this Value and remove them from FnTree and
252 /// queue the functions.
253 void removeUsers(Value *V);
255 /// Replace all direct calls of Old with calls of New. Will bitcast New if
256 /// necessary to make types match.
257 void replaceDirectCallers(Function *Old, Function *New);
259 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
260 /// be converted into a thunk. In either case, it should never be visited
262 void mergeTwoFunctions(Function *F, Function *G);
264 /// Fill PDIUnrelatedWL with instructions from the entry block that are
265 /// unrelated to parameter related debug info.
266 void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
267 std::vector<Instruction *> &PDIUnrelatedWL);
269 /// Erase the rest of the CFG (i.e. barring the entry block).
270 void eraseTail(Function *G);
272 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
273 /// parameter debug info, from the entry block.
274 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
276 /// Replace G with a simple tail call to bitcast(F). Also (unless
277 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
279 void writeThunk(Function *F, Function *G);
281 // Replace G with an alias to F (deleting function G)
282 void writeAlias(Function *F, Function *G);
284 // Replace G with an alias to F if possible, or a thunk to F if
285 // profitable. Returns false if neither is the case.
286 bool writeThunkOrAlias(Function *F, Function *G);
288 /// Replace function F with function G in the function tree.
289 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
291 /// The set of all distinct functions. Use the insert() and remove() methods
292 /// to modify it. The map allows efficient lookup and deferring of Functions.
295 // Map functions to the iterators of the FunctionNode which contains them
296 // in the FnTree. This must be updated carefully whenever the FnTree is
297 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
298 // dangling iterators into FnTree. The invariant that preserves this is that
299 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
300 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
303 } // end anonymous namespace
305 char MergeFunctions::ID = 0;
307 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
309 ModulePass *llvm::createMergeFunctionsPass() {
310 return new MergeFunctions();
314 bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
315 if (const unsigned Max = NumFunctionsForSanityCheck) {
316 unsigned TripleNumber = 0;
319 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
322 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
324 I != E && i < Max; ++I, ++i) {
326 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
328 Function *F1 = cast<Function>(*I);
329 Function *F2 = cast<Function>(*J);
330 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
331 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
333 // If F1 <= F2, then F2 >= F1, otherwise report failure.
335 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
337 dbgs() << *F1 << '\n' << *F2 << '\n';
345 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
346 ++k, ++K, ++TripleNumber) {
350 Function *F3 = cast<Function>(*K);
351 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
352 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
354 bool Transitive = true;
356 if (Res1 != 0 && Res1 == Res4) {
357 // F1 > F2, F2 > F3 => F1 > F3
358 Transitive = Res3 == Res1;
359 } else if (Res3 != 0 && Res3 == -Res4) {
360 // F1 > F3, F3 > F2 => F1 > F2
361 Transitive = Res3 == Res1;
362 } else if (Res4 != 0 && -Res3 == Res4) {
363 // F2 > F3, F3 > F1 => F2 > F1
364 Transitive = Res4 == -Res1;
368 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
369 << TripleNumber << "\n";
370 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
372 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
379 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
386 bool MergeFunctions::runOnModule(Module &M) {
390 bool Changed = false;
392 // All functions in the module, ordered by hash. Functions with a unique
393 // hash value are easily eliminated.
394 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
396 for (Function &Func : M) {
397 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
398 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
403 HashedFuncs.begin(), HashedFuncs.end(),
404 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
405 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
406 return a.first < b.first;
409 auto S = HashedFuncs.begin();
410 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
411 // If the hash value matches the previous value or the next one, we must
412 // consider merging it. Otherwise it is dropped and never considered again.
413 if ((I != S && std::prev(I)->first == I->first) ||
414 (std::next(I) != IE && std::next(I)->first == I->first) ) {
415 Deferred.push_back(WeakTrackingVH(I->second));
420 std::vector<WeakTrackingVH> Worklist;
421 Deferred.swap(Worklist);
423 LLVM_DEBUG(doSanityCheck(Worklist));
425 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
426 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
428 // Insert functions and merge them.
429 for (WeakTrackingVH &I : Worklist) {
432 Function *F = cast<Function>(I);
433 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
434 Changed |= insert(F);
437 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
438 } while (!Deferred.empty());
441 FNodesInTree.clear();
442 GlobalNumbers.clear();
447 // Replace direct callers of Old with New.
448 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
449 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
450 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
453 CallSite CS(U->getUser());
454 if (CS && CS.isCallee(U)) {
455 // Transfer the called function's attributes to the call site. Due to the
456 // bitcast we will 'lose' ABI changing attributes because the 'called
457 // function' is no longer a Function* but the bitcast. Code that looks up
458 // the attributes from the called function will fail.
460 // FIXME: This is not actually true, at least not anymore. The callsite
461 // will always have the same ABI affecting attributes as the callee,
462 // because otherwise the original input has UB. Note that Old and New
463 // always have matching ABI, so no attributes need to be changed.
464 // Transferring other attributes may help other optimizations, but that
465 // should be done uniformly and not in this ad-hoc way.
466 auto &Context = New->getContext();
467 auto NewPAL = New->getAttributes();
468 SmallVector<AttributeSet, 4> NewArgAttrs;
469 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++)
470 NewArgAttrs.push_back(NewPAL.getParamAttributes(argIdx));
471 // Don't transfer attributes from the function to the callee. Function
472 // attributes typically aren't relevant to the calling convention or ABI.
473 CS.setAttributes(AttributeList::get(Context, /*FnAttrs=*/AttributeSet(),
474 NewPAL.getRetAttributes(),
477 remove(CS.getInstruction()->getFunction());
483 // Helper for writeThunk,
484 // Selects proper bitcast operation,
485 // but a bit simpler then CastInst::getCastOpcode.
486 static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
487 Type *SrcTy = V->getType();
488 if (SrcTy->isStructTy()) {
489 assert(DestTy->isStructTy());
490 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
491 Value *Result = UndefValue::get(DestTy);
492 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
493 Value *Element = createCast(
494 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
495 DestTy->getStructElementType(I));
498 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
502 assert(!DestTy->isStructTy());
503 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
504 return Builder.CreateIntToPtr(V, DestTy);
505 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
506 return Builder.CreatePtrToInt(V, DestTy);
508 return Builder.CreateBitCast(V, DestTy);
511 // Erase the instructions in PDIUnrelatedWL as they are unrelated to the
512 // parameter debug info, from the entry block.
513 void MergeFunctions::eraseInstsUnrelatedToPDI(
514 std::vector<Instruction *> &PDIUnrelatedWL) {
516 dbgs() << " Erasing instructions (in reverse order of appearance in "
517 "entry block) unrelated to parameter debug info from entry "
519 while (!PDIUnrelatedWL.empty()) {
520 Instruction *I = PDIUnrelatedWL.back();
521 LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
522 LLVM_DEBUG(I->print(dbgs()));
523 LLVM_DEBUG(dbgs() << "\n");
524 I->eraseFromParent();
525 PDIUnrelatedWL.pop_back();
527 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
528 "debug info from entry block. \n");
531 // Reduce G to its entry block.
532 void MergeFunctions::eraseTail(Function *G) {
533 std::vector<BasicBlock *> WorklistBB;
534 for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
536 BBI->dropAllReferences();
537 WorklistBB.push_back(&*BBI);
539 while (!WorklistBB.empty()) {
540 BasicBlock *BB = WorklistBB.back();
541 BB->eraseFromParent();
542 WorklistBB.pop_back();
546 // We are interested in the following instructions from the entry block as being
547 // related to parameter debug info:
548 // - @llvm.dbg.declare
549 // - stores from the incoming parameters to locations on the stack-frame
550 // - allocas that create these locations on the stack-frame
552 // - the entry block's terminator
553 // The rest are unrelated to debug info for the parameters; fill up
554 // PDIUnrelatedWL with such instructions.
555 void MergeFunctions::filterInstsUnrelatedToPDI(
556 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
557 std::set<Instruction *> PDIRelated;
558 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
560 if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
561 LLVM_DEBUG(dbgs() << " Deciding: ");
562 LLVM_DEBUG(BI->print(dbgs()));
563 LLVM_DEBUG(dbgs() << "\n");
564 DILocalVariable *DILocVar = DVI->getVariable();
565 if (DILocVar->isParameter()) {
566 LLVM_DEBUG(dbgs() << " Include (parameter): ");
567 LLVM_DEBUG(BI->print(dbgs()));
568 LLVM_DEBUG(dbgs() << "\n");
569 PDIRelated.insert(&*BI);
571 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
572 LLVM_DEBUG(BI->print(dbgs()));
573 LLVM_DEBUG(dbgs() << "\n");
575 } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
576 LLVM_DEBUG(dbgs() << " Deciding: ");
577 LLVM_DEBUG(BI->print(dbgs()));
578 LLVM_DEBUG(dbgs() << "\n");
579 DILocalVariable *DILocVar = DDI->getVariable();
580 if (DILocVar->isParameter()) {
581 LLVM_DEBUG(dbgs() << " Parameter: ");
582 LLVM_DEBUG(DILocVar->print(dbgs()));
583 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
585 LLVM_DEBUG(dbgs() << " Processing alloca users: ");
586 LLVM_DEBUG(dbgs() << "\n");
587 for (User *U : AI->users()) {
588 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
589 if (Value *Arg = SI->getValueOperand()) {
590 if (dyn_cast<Argument>(Arg)) {
591 LLVM_DEBUG(dbgs() << " Include: ");
592 LLVM_DEBUG(AI->print(dbgs()));
593 LLVM_DEBUG(dbgs() << "\n");
594 PDIRelated.insert(AI);
595 LLVM_DEBUG(dbgs() << " Include (parameter): ");
596 LLVM_DEBUG(SI->print(dbgs()));
597 LLVM_DEBUG(dbgs() << "\n");
598 PDIRelated.insert(SI);
599 LLVM_DEBUG(dbgs() << " Include: ");
600 LLVM_DEBUG(BI->print(dbgs()));
601 LLVM_DEBUG(dbgs() << "\n");
602 PDIRelated.insert(&*BI);
604 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
605 LLVM_DEBUG(SI->print(dbgs()));
606 LLVM_DEBUG(dbgs() << "\n");
610 LLVM_DEBUG(dbgs() << " Defer: ");
611 LLVM_DEBUG(U->print(dbgs()));
612 LLVM_DEBUG(dbgs() << "\n");
616 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
617 LLVM_DEBUG(BI->print(dbgs()));
618 LLVM_DEBUG(dbgs() << "\n");
621 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
622 LLVM_DEBUG(BI->print(dbgs()));
623 LLVM_DEBUG(dbgs() << "\n");
625 } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
626 LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
627 LLVM_DEBUG(BI->print(dbgs()));
628 LLVM_DEBUG(dbgs() << "\n");
629 PDIRelated.insert(&*BI);
631 LLVM_DEBUG(dbgs() << " Defer: ");
632 LLVM_DEBUG(BI->print(dbgs()));
633 LLVM_DEBUG(dbgs() << "\n");
638 << " Report parameter debug info related/related instructions: {\n");
639 for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
642 Instruction *I = &*BI;
643 if (PDIRelated.find(I) == PDIRelated.end()) {
644 LLVM_DEBUG(dbgs() << " !PDIRelated: ");
645 LLVM_DEBUG(I->print(dbgs()));
646 LLVM_DEBUG(dbgs() << "\n");
647 PDIUnrelatedWL.push_back(I);
649 LLVM_DEBUG(dbgs() << " PDIRelated: ");
650 LLVM_DEBUG(I->print(dbgs()));
651 LLVM_DEBUG(dbgs() << "\n");
654 LLVM_DEBUG(dbgs() << " }\n");
657 // Don't merge tiny functions using a thunk, since it can just end up
658 // making the function larger.
659 static bool isThunkProfitable(Function * F) {
660 if (F->size() == 1) {
661 if (F->front().size() <= 2) {
662 LLVM_DEBUG(dbgs() << "isThunkProfitable: " << F->getName()
663 << " is too small to bother creating a thunk for\n");
670 // Replace G with a simple tail call to bitcast(F). Also (unless
671 // MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
672 // delete G. Under MergeFunctionsPDI, we use G itself for creating
673 // the thunk as we preserve the debug info (and associated instructions)
674 // from G's entry block pertaining to G's incoming arguments which are
675 // passed on as corresponding arguments in the call that G makes to F.
676 // For better debugability, under MergeFunctionsPDI, we do not modify G's
677 // call sites to point to F even when within the same translation unit.
678 void MergeFunctions::writeThunk(Function *F, Function *G) {
679 BasicBlock *GEntryBlock = nullptr;
680 std::vector<Instruction *> PDIUnrelatedWL;
681 BasicBlock *BB = nullptr;
682 Function *NewG = nullptr;
683 if (MergeFunctionsPDI) {
684 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
685 "function as thunk; retain original: "
686 << G->getName() << "()\n");
687 GEntryBlock = &G->getEntryBlock();
689 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
691 << G->getName() << "() {\n");
692 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
693 GEntryBlock->getTerminator()->eraseFromParent();
696 NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
697 G->getAddressSpace(), "", G->getParent());
698 BB = BasicBlock::Create(F->getContext(), "", NewG);
701 IRBuilder<> Builder(BB);
702 Function *H = MergeFunctionsPDI ? G : NewG;
703 SmallVector<Value *, 16> Args;
705 FunctionType *FFTy = F->getFunctionType();
706 for (Argument &AI : H->args()) {
707 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
711 CallInst *CI = Builder.CreateCall(F, Args);
712 ReturnInst *RI = nullptr;
714 CI->setCallingConv(F->getCallingConv());
715 CI->setAttributes(F->getAttributes());
716 if (H->getReturnType()->isVoidTy()) {
717 RI = Builder.CreateRetVoid();
719 RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
722 if (MergeFunctionsPDI) {
723 DISubprogram *DIS = G->getSubprogram();
725 DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
726 DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
727 CI->setDebugLoc(CIDbgLoc);
728 RI->setDebugLoc(RIDbgLoc);
731 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
732 << G->getName() << "()\n");
735 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
737 dbgs() << "} // End of parameter related debug info filtering for: "
738 << G->getName() << "()\n");
740 NewG->copyAttributesFrom(G);
743 G->replaceAllUsesWith(NewG);
744 G->eraseFromParent();
747 LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
751 // Whether this function may be replaced by an alias
752 static bool canCreateAliasFor(Function *F) {
753 if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
756 // We should only see linkages supported by aliases here
757 assert(F->hasLocalLinkage() || F->hasExternalLinkage()
758 || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
762 // Replace G with an alias to F (deleting function G)
763 void MergeFunctions::writeAlias(Function *F, Function *G) {
764 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
765 PointerType *PtrType = G->getType();
766 auto *GA = GlobalAlias::create(
767 PtrType->getElementType(), PtrType->getAddressSpace(),
768 G->getLinkage(), "", BitcastF, G->getParent());
770 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
772 GA->setVisibility(G->getVisibility());
773 GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
776 G->replaceAllUsesWith(GA);
777 G->eraseFromParent();
779 LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
783 // Replace G with an alias to F if possible, or a thunk to F if
784 // profitable. Returns false if neither is the case.
785 bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
786 if (canCreateAliasFor(G)) {
790 if (isThunkProfitable(F)) {
797 // Merge two equivalent functions. Upon completion, Function G is deleted.
798 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
799 if (F->isInterposable()) {
800 assert(G->isInterposable());
802 // Both writeThunkOrAlias() calls below must succeed, either because we can
803 // create aliases for G and NewF, or because a thunk for F is profitable.
804 // F here has the same signature as NewF below, so that's what we check.
805 if (!isThunkProfitable(F) && (!canCreateAliasFor(F) || !canCreateAliasFor(G))) {
809 // Make them both thunks to the same internal function.
810 Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
811 F->getAddressSpace(), "", F->getParent());
812 NewF->copyAttributesFrom(F);
815 F->replaceAllUsesWith(NewF);
817 unsigned MaxAlignment = std::max(G->getAlignment(), NewF->getAlignment());
819 writeThunkOrAlias(F, G);
820 writeThunkOrAlias(F, NewF);
822 F->setAlignment(MaxAlignment);
823 F->setLinkage(GlobalValue::PrivateLinkage);
825 ++NumFunctionsMerged;
827 // For better debugability, under MergeFunctionsPDI, we do not modify G's
828 // call sites to point to F even when within the same translation unit.
829 if (!G->isInterposable() && !MergeFunctionsPDI) {
830 if (G->hasGlobalUnnamedAddr()) {
831 // G might have been a key in our GlobalNumberState, and it's illegal
832 // to replace a key in ValueMap<GlobalValue *> with a non-global.
833 GlobalNumbers.erase(G);
834 // If G's address is not significant, replace it entirely.
835 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
837 G->replaceAllUsesWith(BitcastF);
839 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
841 replaceDirectCallers(G, F);
845 // If G was internal then we may have replaced all uses of G with F. If so,
846 // stop here and delete G. There's no need for a thunk. (See note on
847 // MergeFunctionsPDI above).
848 if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
849 G->eraseFromParent();
850 ++NumFunctionsMerged;
854 if (writeThunkOrAlias(F, G)) {
855 ++NumFunctionsMerged;
860 /// Replace function F by function G.
861 void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
863 Function *F = FN.getFunc();
864 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
865 "The two functions must be equal");
867 auto I = FNodesInTree.find(F);
868 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
869 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
871 FnTreeType::iterator IterToFNInFnTree = I->second;
872 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
873 // Remove F -> FN and insert G -> FN
874 FNodesInTree.erase(I);
875 FNodesInTree.insert({G, IterToFNInFnTree});
876 // Replace F with G in FN, which is stored inside the FnTree.
880 // Ordering for functions that are equal under FunctionComparator
881 static bool isFuncOrderCorrect(const Function *F, const Function *G) {
882 if (F->isInterposable() != G->isInterposable()) {
883 // Strong before weak, because the weak function may call the strong
884 // one, but not the other way around.
885 return !F->isInterposable();
887 if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
888 // External before local, because we definitely have to keep the external
889 // function, but may be able to drop the local one.
890 return !F->hasLocalLinkage();
892 // Impose a total order (by name) on the replacement of functions. This is
893 // important when operating on more than one module independently to prevent
894 // cycles of thunks calling each other when the modules are linked together.
895 return F->getName() <= G->getName();
898 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
899 // that was already inserted.
900 bool MergeFunctions::insert(Function *NewFunction) {
901 std::pair<FnTreeType::iterator, bool> Result =
902 FnTree.insert(FunctionNode(NewFunction));
905 assert(FNodesInTree.count(NewFunction) == 0);
906 FNodesInTree.insert({NewFunction, Result.first});
907 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
912 const FunctionNode &OldF = *Result.first;
914 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
915 // Swap the two functions.
916 Function *F = OldF.getFunc();
917 replaceFunctionInTree(*Result.first, NewFunction);
919 assert(OldF.getFunc() != F && "Must have swapped the functions.");
922 LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName()
923 << " == " << NewFunction->getName() << '\n');
925 Function *DeleteF = NewFunction;
926 mergeTwoFunctions(OldF.getFunc(), DeleteF);
930 // Remove a function from FnTree. If it was already in FnTree, add
931 // it to Deferred so that we'll look at it in the next round.
932 void MergeFunctions::remove(Function *F) {
933 auto I = FNodesInTree.find(F);
934 if (I != FNodesInTree.end()) {
935 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
936 FnTree.erase(I->second);
937 // I->second has been invalidated, remove it from the FNodesInTree map to
938 // preserve the invariant.
939 FNodesInTree.erase(I);
940 Deferred.emplace_back(F);
944 // For each instruction used by the value, remove() the function that contains
945 // the instruction. This should happen right before a call to RAUW.
946 void MergeFunctions::removeUsers(Value *V) {
947 std::vector<Value *> Worklist;
948 Worklist.push_back(V);
949 SmallPtrSet<Value*, 8> Visited;
951 while (!Worklist.empty()) {
952 Value *V = Worklist.back();
955 for (User *U : V->users()) {
956 if (Instruction *I = dyn_cast<Instruction>(U)) {
957 remove(I->getFunction());
958 } else if (isa<GlobalValue>(U)) {
960 } else if (Constant *C = dyn_cast<Constant>(U)) {
961 for (User *UU : C->users()) {
962 if (!Visited.insert(UU).second)
963 Worklist.push_back(UU);