1f22ef01cSRoman Divacky //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This pass looks for equivalent functions that are mergable and folds them.
11f22ef01cSRoman Divacky //
1291bc56edSDimitry Andric // Order relation is defined on set of functions. It was made through
1391bc56edSDimitry Andric // special function comparison procedure that returns
1491bc56edSDimitry Andric // 0 when functions are equal,
1591bc56edSDimitry Andric // -1 when Left function is less than right function, and
1691bc56edSDimitry Andric // 1 for opposite case. We need total-ordering, so we need to maintain
1791bc56edSDimitry Andric // four properties on the functions set:
1891bc56edSDimitry Andric // a <= a (reflexivity)
1991bc56edSDimitry Andric // if a <= b and b <= a then a = b (antisymmetry)
2091bc56edSDimitry Andric // if a <= b and b <= c then a <= c (transitivity).
2191bc56edSDimitry Andric // for all a and b: a <= b or b <= a (totality).
22f22ef01cSRoman Divacky //
2391bc56edSDimitry Andric // Comparison iterates through each instruction in each basic block.
2491bc56edSDimitry Andric // Functions are kept on binary tree. For each new function F we perform
2591bc56edSDimitry Andric // lookup in binary tree.
2691bc56edSDimitry Andric // In practice it works the following way:
2791bc56edSDimitry Andric // -- We define Function* container class with custom "operator<" (FunctionPtr).
2891bc56edSDimitry Andric // -- "FunctionPtr" instances are stored in std::set collection, so every
2991bc56edSDimitry Andric //    std::set::insert operation will give you result in log(N) time.
30f22ef01cSRoman Divacky //
317d523365SDimitry Andric // As an optimization, a hash of the function structure is calculated first, and
327d523365SDimitry Andric // two functions are only compared if they have the same hash. This hash is
337d523365SDimitry Andric // cheap to compute, and has the property that if function F == G according to
347d523365SDimitry Andric // the comparison function, then hash(F) == hash(G). This consistency property
357d523365SDimitry Andric // is critical to ensuring all possible merging opportunities are exploited.
367d523365SDimitry Andric // Collisions in the hash affect the speed of the pass but not the correctness
377d523365SDimitry Andric // or determinism of the resulting transformation.
387d523365SDimitry Andric //
39f22ef01cSRoman Divacky // When a match is found the functions are folded. If both functions are
40f22ef01cSRoman Divacky // overridable, we move the functionality into a new internal function and
41f22ef01cSRoman Divacky // leave two overridable thunks to it.
42f22ef01cSRoman Divacky //
43f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
44f22ef01cSRoman Divacky //
45f22ef01cSRoman Divacky // Future work:
46f22ef01cSRoman Divacky //
47f22ef01cSRoman Divacky // * virtual functions.
48f22ef01cSRoman Divacky //
49f22ef01cSRoman Divacky // Many functions have their address taken by the virtual function table for
50f22ef01cSRoman Divacky // the object they belong to. However, as long as it's only used for a lookup
51e580952dSDimitry Andric // and call, this is irrelevant, and we'd like to fold such functions.
52f22ef01cSRoman Divacky //
53e580952dSDimitry Andric // * be smarter about bitcasts.
54f22ef01cSRoman Divacky //
55f22ef01cSRoman Divacky // In order to fold functions, we will sometimes add either bitcast instructions
56f22ef01cSRoman Divacky // or bitcast constant expressions. Unfortunately, this can confound further
57f22ef01cSRoman Divacky // analysis since the two functions differ where one has a bitcast and the
58e580952dSDimitry Andric // other doesn't. We should learn to look through bitcasts.
59f22ef01cSRoman Divacky //
6091bc56edSDimitry Andric // * Compare complex types with pointer types inside.
6191bc56edSDimitry Andric // * Compare cross-reference cases.
6291bc56edSDimitry Andric // * Compare complex expressions.
6391bc56edSDimitry Andric //
6491bc56edSDimitry Andric // All the three issues above could be described as ability to prove that
6591bc56edSDimitry Andric // fA == fB == fC == fE == fF == fG in example below:
6691bc56edSDimitry Andric //
6791bc56edSDimitry Andric //  void fA() {
6891bc56edSDimitry Andric //    fB();
6991bc56edSDimitry Andric //  }
7091bc56edSDimitry Andric //  void fB() {
7191bc56edSDimitry Andric //    fA();
7291bc56edSDimitry Andric //  }
7391bc56edSDimitry Andric //
7491bc56edSDimitry Andric //  void fE() {
7591bc56edSDimitry Andric //    fF();
7691bc56edSDimitry Andric //  }
7791bc56edSDimitry Andric //  void fF() {
7891bc56edSDimitry Andric //    fG();
7991bc56edSDimitry Andric //  }
8091bc56edSDimitry Andric //  void fG() {
8191bc56edSDimitry Andric //    fE();
8291bc56edSDimitry Andric //  }
8391bc56edSDimitry Andric //
8491bc56edSDimitry Andric // Simplest cross-reference case (fA <--> fB) was implemented in previous
8591bc56edSDimitry Andric // versions of MergeFunctions, though it presented only in two function pairs
8691bc56edSDimitry Andric // in test-suite (that counts >50k functions)
8791bc56edSDimitry Andric // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
8891bc56edSDimitry Andric // could cover much more cases.
8991bc56edSDimitry Andric //
90f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
91f22ef01cSRoman Divacky 
922cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
934ba319b5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
942cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
957ae0e2c9SDimitry Andric #include "llvm/ADT/Statistic.h"
962cab237bSDimitry Andric #include "llvm/IR/Argument.h"
972cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
982cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
9991bc56edSDimitry Andric #include "llvm/IR/CallSite.h"
1002cab237bSDimitry Andric #include "llvm/IR/Constant.h"
101139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
1022cab237bSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
1032cab237bSDimitry Andric #include "llvm/IR/DebugLoc.h"
1042cab237bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
1052cab237bSDimitry Andric #include "llvm/IR/Function.h"
1062cab237bSDimitry Andric #include "llvm/IR/GlobalValue.h"
107139f7f9bSDimitry Andric #include "llvm/IR/IRBuilder.h"
1082cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
1092cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
110139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
1117a7e6055SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
112139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
1132cab237bSDimitry Andric #include "llvm/IR/Type.h"
1142cab237bSDimitry Andric #include "llvm/IR/Use.h"
1152cab237bSDimitry Andric #include "llvm/IR/User.h"
1162cab237bSDimitry Andric #include "llvm/IR/Value.h"
11791bc56edSDimitry Andric #include "llvm/IR/ValueHandle.h"
1187d523365SDimitry Andric #include "llvm/IR/ValueMap.h"
119139f7f9bSDimitry Andric #include "llvm/Pass.h"
1202cab237bSDimitry Andric #include "llvm/Support/Casting.h"
12191bc56edSDimitry Andric #include "llvm/Support/CommandLine.h"
122f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
123f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
1243ca95b02SDimitry Andric #include "llvm/Transforms/IPO.h"
125d88c1a5aSDimitry Andric #include "llvm/Transforms/Utils/FunctionComparator.h"
1262cab237bSDimitry Andric #include <algorithm>
1272cab237bSDimitry Andric #include <cassert>
1282cab237bSDimitry Andric #include <iterator>
1292cab237bSDimitry Andric #include <set>
1302cab237bSDimitry Andric #include <utility>
131f22ef01cSRoman Divacky #include <vector>
1327d523365SDimitry Andric 
133f22ef01cSRoman Divacky using namespace llvm;
134f22ef01cSRoman Divacky 
13591bc56edSDimitry Andric #define DEBUG_TYPE "mergefunc"
13691bc56edSDimitry Andric 
137f22ef01cSRoman Divacky STATISTIC(NumFunctionsMerged, "Number of functions merged");
1382754fe60SDimitry Andric STATISTIC(NumThunksWritten, "Number of thunks generated");
139*b5893f02SDimitry Andric STATISTIC(NumAliasesWritten, "Number of aliases generated");
1402754fe60SDimitry Andric STATISTIC(NumDoubleWeak, "Number of new functions created");
1412754fe60SDimitry Andric 
14291bc56edSDimitry Andric static cl::opt<unsigned> NumFunctionsForSanityCheck(
14391bc56edSDimitry Andric     "mergefunc-sanity",
14491bc56edSDimitry Andric     cl::desc("How many functions in module could be used for "
14591bc56edSDimitry Andric              "MergeFunctions pass sanity check. "
14691bc56edSDimitry Andric              "'0' disables this check. Works only with '-debug' key."),
14791bc56edSDimitry Andric     cl::init(0), cl::Hidden);
148f22ef01cSRoman Divacky 
1497a7e6055SDimitry Andric // Under option -mergefunc-preserve-debug-info we:
1507a7e6055SDimitry Andric // - Do not create a new function for a thunk.
1517a7e6055SDimitry Andric // - Retain the debug info for a thunk's parameters (and associated
1527a7e6055SDimitry Andric //   instructions for the debug info) from the entry block.
1537a7e6055SDimitry Andric //   Note: -debug will display the algorithm at work.
1547a7e6055SDimitry Andric // - Create debug-info for the call (to the shared implementation) made by
1557a7e6055SDimitry Andric //   a thunk and its return value.
1567a7e6055SDimitry Andric // - Erase the rest of the function, retaining the (minimally sized) entry
1577a7e6055SDimitry Andric //   block to create a thunk.
1587a7e6055SDimitry Andric // - Preserve a thunk's call site to point to the thunk even when both occur
1597a7e6055SDimitry Andric //   within the same translation unit, to aid debugability. Note that this
1607a7e6055SDimitry Andric //   behaviour differs from the underlying -mergefunc implementation which
1617a7e6055SDimitry Andric //   modifies the thunk's call site to point to the shared implementation
1627a7e6055SDimitry Andric //   when both occur within the same translation unit.
1637a7e6055SDimitry Andric static cl::opt<bool>
1647a7e6055SDimitry Andric     MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
1657a7e6055SDimitry Andric                       cl::init(false),
1667a7e6055SDimitry Andric                       cl::desc("Preserve debug info in thunk when mergefunc "
1677a7e6055SDimitry Andric                                "transformations are made."));
1687a7e6055SDimitry Andric 
169*b5893f02SDimitry Andric static cl::opt<bool>
170*b5893f02SDimitry Andric     MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
171*b5893f02SDimitry Andric                           cl::init(false),
172*b5893f02SDimitry Andric                           cl::desc("Allow mergefunc to create aliases"));
173*b5893f02SDimitry Andric 
174e580952dSDimitry Andric namespace {
1752754fe60SDimitry Andric 
17639d628a0SDimitry Andric class FunctionNode {
17797bc6c73SDimitry Andric   mutable AssertingVH<Function> F;
1787d523365SDimitry Andric   FunctionComparator::FunctionHash Hash;
1792cab237bSDimitry Andric 
18091bc56edSDimitry Andric public:
1817d523365SDimitry Andric   // Note the hash is recalculated potentially multiple times, but it is cheap.
FunctionNode(Function * F)1827d523365SDimitry Andric   FunctionNode(Function *F)
1837d523365SDimitry Andric     : F(F), Hash(FunctionComparator::functionHash(*F))  {}
1842cab237bSDimitry Andric 
getFunc() const18591bc56edSDimitry Andric   Function *getFunc() const { return F; }
getHash() const1867d523365SDimitry Andric   FunctionComparator::FunctionHash getHash() const { return Hash; }
18797bc6c73SDimitry Andric 
18897bc6c73SDimitry Andric   /// Replace the reference to the function F by the function G, assuming their
18997bc6c73SDimitry Andric   /// implementations are equal.
replaceBy(Function * G) const19097bc6c73SDimitry Andric   void replaceBy(Function *G) const {
19197bc6c73SDimitry Andric     F = G;
19297bc6c73SDimitry Andric   }
19397bc6c73SDimitry Andric 
release()1947d523365SDimitry Andric   void release() { F = nullptr; }
19591bc56edSDimitry Andric };
1962754fe60SDimitry Andric 
1972754fe60SDimitry Andric /// MergeFunctions finds functions which will generate identical machine code,
1982754fe60SDimitry Andric /// by considering all pointer types to be equivalent. Once identified,
1992754fe60SDimitry Andric /// MergeFunctions will fold them by replacing a call to one to a call to a
2002754fe60SDimitry Andric /// bitcast of the other.
2012754fe60SDimitry Andric class MergeFunctions : public ModulePass {
2022754fe60SDimitry Andric public:
2032754fe60SDimitry Andric   static char ID;
2042cab237bSDimitry Andric 
MergeFunctions()2052754fe60SDimitry Andric   MergeFunctions()
2062cab237bSDimitry Andric     : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)) {
2072754fe60SDimitry Andric     initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
2082754fe60SDimitry Andric   }
2092754fe60SDimitry Andric 
21091bc56edSDimitry Andric   bool runOnModule(Module &M) override;
2112754fe60SDimitry Andric 
2122754fe60SDimitry Andric private:
2137d523365SDimitry Andric   // The function comparison operator is provided here so that FunctionNodes do
2147d523365SDimitry Andric   // not need to become larger with another pointer.
2157d523365SDimitry Andric   class FunctionNodeCmp {
2167d523365SDimitry Andric     GlobalNumberState* GlobalNumbers;
2172cab237bSDimitry Andric 
2187d523365SDimitry Andric   public:
FunctionNodeCmp(GlobalNumberState * GN)2197d523365SDimitry Andric     FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
2202cab237bSDimitry Andric 
operator ()(const FunctionNode & LHS,const FunctionNode & RHS) const2217d523365SDimitry Andric     bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
2227d523365SDimitry Andric       // Order first by hashes, then full function comparison.
2237d523365SDimitry Andric       if (LHS.getHash() != RHS.getHash())
2247d523365SDimitry Andric         return LHS.getHash() < RHS.getHash();
2257d523365SDimitry Andric       FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
2267d523365SDimitry Andric       return FCmp.compare() == -1;
2277d523365SDimitry Andric     }
2287d523365SDimitry Andric   };
2292cab237bSDimitry Andric   using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
2307d523365SDimitry Andric 
2317d523365SDimitry Andric   GlobalNumberState GlobalNumbers;
2322754fe60SDimitry Andric 
2332754fe60SDimitry Andric   /// A work queue of functions that may have been modified and should be
2342754fe60SDimitry Andric   /// analyzed again.
235f37b6182SDimitry Andric   std::vector<WeakTrackingVH> Deferred;
2362754fe60SDimitry Andric 
2372cab237bSDimitry Andric #ifndef NDEBUG
23891bc56edSDimitry Andric   /// Checks the rules of order relation introduced among functions set.
23991bc56edSDimitry Andric   /// Returns true, if sanity check has been passed, and false if failed.
240f37b6182SDimitry Andric   bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
241f37b6182SDimitry Andric #endif
2422754fe60SDimitry Andric 
24391bc56edSDimitry Andric   /// Insert a ComparableFunction into the FnTree, or merge it away if it's
24491bc56edSDimitry Andric   /// equal to one that's already present.
24591bc56edSDimitry Andric   bool insert(Function *NewFunction);
24691bc56edSDimitry Andric 
24791bc56edSDimitry Andric   /// Remove a Function from the FnTree and queue it up for a second sweep of
2482754fe60SDimitry Andric   /// analysis.
2492754fe60SDimitry Andric   void remove(Function *F);
2502754fe60SDimitry Andric 
25191bc56edSDimitry Andric   /// Find the functions that use this Value and remove them from FnTree and
2522754fe60SDimitry Andric   /// queue the functions.
2532754fe60SDimitry Andric   void removeUsers(Value *V);
2542754fe60SDimitry Andric 
2552754fe60SDimitry Andric   /// Replace all direct calls of Old with calls of New. Will bitcast New if
2562754fe60SDimitry Andric   /// necessary to make types match.
2572754fe60SDimitry Andric   void replaceDirectCallers(Function *Old, Function *New);
2582754fe60SDimitry Andric 
2592754fe60SDimitry Andric   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
2602754fe60SDimitry Andric   /// be converted into a thunk. In either case, it should never be visited
2612754fe60SDimitry Andric   /// again.
2622754fe60SDimitry Andric   void mergeTwoFunctions(Function *F, Function *G);
2632754fe60SDimitry Andric 
2647a7e6055SDimitry Andric   /// Fill PDIUnrelatedWL with instructions from the entry block that are
2657a7e6055SDimitry Andric   /// unrelated to parameter related debug info.
2667a7e6055SDimitry Andric   void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
2677a7e6055SDimitry Andric                                  std::vector<Instruction *> &PDIUnrelatedWL);
2687a7e6055SDimitry Andric 
2697a7e6055SDimitry Andric   /// Erase the rest of the CFG (i.e. barring the entry block).
2707a7e6055SDimitry Andric   void eraseTail(Function *G);
2717a7e6055SDimitry Andric 
2727a7e6055SDimitry Andric   /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
2737a7e6055SDimitry Andric   /// parameter debug info, from the entry block.
2747a7e6055SDimitry Andric   void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
2757a7e6055SDimitry Andric 
2767a7e6055SDimitry Andric   /// Replace G with a simple tail call to bitcast(F). Also (unless
2777a7e6055SDimitry Andric   /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
2787a7e6055SDimitry Andric   /// delete G.
2792754fe60SDimitry Andric   void writeThunk(Function *F, Function *G);
2802754fe60SDimitry Andric 
281*b5893f02SDimitry Andric   // Replace G with an alias to F (deleting function G)
282*b5893f02SDimitry Andric   void writeAlias(Function *F, Function *G);
283*b5893f02SDimitry Andric 
284*b5893f02SDimitry Andric   // Replace G with an alias to F if possible, or a thunk to F if
285*b5893f02SDimitry Andric   // profitable. Returns false if neither is the case.
286*b5893f02SDimitry Andric   bool writeThunkOrAlias(Function *F, Function *G);
287*b5893f02SDimitry Andric 
28897bc6c73SDimitry Andric   /// Replace function F with function G in the function tree.
2897d523365SDimitry Andric   void replaceFunctionInTree(const FunctionNode &FN, Function *G);
29097bc6c73SDimitry Andric 
2912754fe60SDimitry Andric   /// The set of all distinct functions. Use the insert() and remove() methods
2927d523365SDimitry Andric   /// to modify it. The map allows efficient lookup and deferring of Functions.
29391bc56edSDimitry Andric   FnTreeType FnTree;
2942cab237bSDimitry Andric 
2957d523365SDimitry Andric   // Map functions to the iterators of the FunctionNode which contains them
2967d523365SDimitry Andric   // in the FnTree. This must be updated carefully whenever the FnTree is
2977d523365SDimitry Andric   // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
2987d523365SDimitry Andric   // dangling iterators into FnTree. The invariant that preserves this is that
2997d523365SDimitry Andric   // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
300*b5893f02SDimitry Andric   DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
3012754fe60SDimitry Andric };
3022754fe60SDimitry Andric 
3032754fe60SDimitry Andric } // end anonymous namespace
3042754fe60SDimitry Andric 
3052754fe60SDimitry Andric char MergeFunctions::ID = 0;
3062cab237bSDimitry Andric 
3072754fe60SDimitry Andric INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
3082754fe60SDimitry Andric 
createMergeFunctionsPass()3092754fe60SDimitry Andric ModulePass *llvm::createMergeFunctionsPass() {
3102754fe60SDimitry Andric   return new MergeFunctions();
3112754fe60SDimitry Andric }
3122754fe60SDimitry Andric 
313f37b6182SDimitry Andric #ifndef NDEBUG
doSanityCheck(std::vector<WeakTrackingVH> & Worklist)314f37b6182SDimitry Andric bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
31591bc56edSDimitry Andric   if (const unsigned Max = NumFunctionsForSanityCheck) {
31691bc56edSDimitry Andric     unsigned TripleNumber = 0;
31791bc56edSDimitry Andric     bool Valid = true;
31891bc56edSDimitry Andric 
31991bc56edSDimitry Andric     dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
32091bc56edSDimitry Andric 
32191bc56edSDimitry Andric     unsigned i = 0;
322f37b6182SDimitry Andric     for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
323f37b6182SDimitry Andric                                                E = Worklist.end();
32491bc56edSDimitry Andric          I != E && i < Max; ++I, ++i) {
32591bc56edSDimitry Andric       unsigned j = i;
326f37b6182SDimitry Andric       for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
327f37b6182SDimitry Andric            ++J, ++j) {
32891bc56edSDimitry Andric         Function *F1 = cast<Function>(*I);
32991bc56edSDimitry Andric         Function *F2 = cast<Function>(*J);
3307d523365SDimitry Andric         int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
3317d523365SDimitry Andric         int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
33291bc56edSDimitry Andric 
33391bc56edSDimitry Andric         // If F1 <= F2, then F2 >= F1, otherwise report failure.
33491bc56edSDimitry Andric         if (Res1 != -Res2) {
33591bc56edSDimitry Andric           dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
33691bc56edSDimitry Andric                  << "\n";
3377a7e6055SDimitry Andric           dbgs() << *F1 << '\n' << *F2 << '\n';
33891bc56edSDimitry Andric           Valid = false;
33991bc56edSDimitry Andric         }
34091bc56edSDimitry Andric 
34191bc56edSDimitry Andric         if (Res1 == 0)
34291bc56edSDimitry Andric           continue;
34391bc56edSDimitry Andric 
34491bc56edSDimitry Andric         unsigned k = j;
345f37b6182SDimitry Andric         for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
34691bc56edSDimitry Andric              ++k, ++K, ++TripleNumber) {
34791bc56edSDimitry Andric           if (K == J)
34891bc56edSDimitry Andric             continue;
34991bc56edSDimitry Andric 
35091bc56edSDimitry Andric           Function *F3 = cast<Function>(*K);
3517d523365SDimitry Andric           int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
3527d523365SDimitry Andric           int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
35391bc56edSDimitry Andric 
35491bc56edSDimitry Andric           bool Transitive = true;
35591bc56edSDimitry Andric 
35691bc56edSDimitry Andric           if (Res1 != 0 && Res1 == Res4) {
35791bc56edSDimitry Andric             // F1 > F2, F2 > F3 => F1 > F3
35891bc56edSDimitry Andric             Transitive = Res3 == Res1;
35991bc56edSDimitry Andric           } else if (Res3 != 0 && Res3 == -Res4) {
36091bc56edSDimitry Andric             // F1 > F3, F3 > F2 => F1 > F2
36191bc56edSDimitry Andric             Transitive = Res3 == Res1;
36291bc56edSDimitry Andric           } else if (Res4 != 0 && -Res3 == Res4) {
36391bc56edSDimitry Andric             // F2 > F3, F3 > F1 => F2 > F1
36491bc56edSDimitry Andric             Transitive = Res4 == -Res1;
36591bc56edSDimitry Andric           }
36691bc56edSDimitry Andric 
36791bc56edSDimitry Andric           if (!Transitive) {
36891bc56edSDimitry Andric             dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
36991bc56edSDimitry Andric                    << TripleNumber << "\n";
37091bc56edSDimitry Andric             dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
37191bc56edSDimitry Andric                    << Res4 << "\n";
3727a7e6055SDimitry Andric             dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
37391bc56edSDimitry Andric             Valid = false;
37491bc56edSDimitry Andric           }
37591bc56edSDimitry Andric         }
37691bc56edSDimitry Andric       }
37791bc56edSDimitry Andric     }
37891bc56edSDimitry Andric 
37991bc56edSDimitry Andric     dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
38091bc56edSDimitry Andric     return Valid;
38191bc56edSDimitry Andric   }
38291bc56edSDimitry Andric   return true;
38391bc56edSDimitry Andric }
384f37b6182SDimitry Andric #endif
38591bc56edSDimitry Andric 
runOnModule(Module & M)3862754fe60SDimitry Andric bool MergeFunctions::runOnModule(Module &M) {
3873ca95b02SDimitry Andric   if (skipModule(M))
3883ca95b02SDimitry Andric     return false;
3893ca95b02SDimitry Andric 
3902754fe60SDimitry Andric   bool Changed = false;
3912754fe60SDimitry Andric 
3927d523365SDimitry Andric   // All functions in the module, ordered by hash. Functions with a unique
3937d523365SDimitry Andric   // hash value are easily eliminated.
3947d523365SDimitry Andric   std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
3957d523365SDimitry Andric     HashedFuncs;
3967d523365SDimitry Andric   for (Function &Func : M) {
3977d523365SDimitry Andric     if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
3987d523365SDimitry Andric       HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
3997d523365SDimitry Andric     }
4007d523365SDimitry Andric   }
4017d523365SDimitry Andric 
4027d523365SDimitry Andric   std::stable_sort(
4037d523365SDimitry Andric       HashedFuncs.begin(), HashedFuncs.end(),
4047d523365SDimitry Andric       [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
4057d523365SDimitry Andric          const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
4067d523365SDimitry Andric         return a.first < b.first;
4077d523365SDimitry Andric       });
4087d523365SDimitry Andric 
4097d523365SDimitry Andric   auto S = HashedFuncs.begin();
4107d523365SDimitry Andric   for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
4117d523365SDimitry Andric     // If the hash value matches the previous value or the next one, we must
4127d523365SDimitry Andric     // consider merging it. Otherwise it is dropped and never considered again.
4137d523365SDimitry Andric     if ((I != S && std::prev(I)->first == I->first) ||
4147d523365SDimitry Andric         (std::next(I) != IE && std::next(I)->first == I->first) ) {
415f37b6182SDimitry Andric       Deferred.push_back(WeakTrackingVH(I->second));
4167d523365SDimitry Andric     }
4172754fe60SDimitry Andric   }
4182754fe60SDimitry Andric 
4192754fe60SDimitry Andric   do {
420f37b6182SDimitry Andric     std::vector<WeakTrackingVH> Worklist;
4212754fe60SDimitry Andric     Deferred.swap(Worklist);
4222754fe60SDimitry Andric 
4234ba319b5SDimitry Andric     LLVM_DEBUG(doSanityCheck(Worklist));
42491bc56edSDimitry Andric 
4254ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
4264ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
4272754fe60SDimitry Andric 
4283ca95b02SDimitry Andric     // Insert functions and merge them.
429f37b6182SDimitry Andric     for (WeakTrackingVH &I : Worklist) {
4303ca95b02SDimitry Andric       if (!I)
4313ca95b02SDimitry Andric         continue;
4323ca95b02SDimitry Andric       Function *F = cast<Function>(I);
4333ca95b02SDimitry Andric       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
43491bc56edSDimitry Andric         Changed |= insert(F);
4352754fe60SDimitry Andric       }
4362754fe60SDimitry Andric     }
4374ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
4382754fe60SDimitry Andric   } while (!Deferred.empty());
4392754fe60SDimitry Andric 
44091bc56edSDimitry Andric   FnTree.clear();
441*b5893f02SDimitry Andric   FNodesInTree.clear();
4427d523365SDimitry Andric   GlobalNumbers.clear();
4432754fe60SDimitry Andric 
4442754fe60SDimitry Andric   return Changed;
4452754fe60SDimitry Andric }
4462754fe60SDimitry Andric 
4472754fe60SDimitry Andric // Replace direct callers of Old with New.
replaceDirectCallers(Function * Old,Function * New)4482754fe60SDimitry Andric void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
4492754fe60SDimitry Andric   Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
45091bc56edSDimitry Andric   for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
45191bc56edSDimitry Andric     Use *U = &*UI;
452f22ef01cSRoman Divacky     ++UI;
45391bc56edSDimitry Andric     CallSite CS(U->getUser());
45491bc56edSDimitry Andric     if (CS && CS.isCallee(U)) {
4557d523365SDimitry Andric       // Transfer the called function's attributes to the call site. Due to the
4567d523365SDimitry Andric       // bitcast we will 'lose' ABI changing attributes because the 'called
4577d523365SDimitry Andric       // function' is no longer a Function* but the bitcast. Code that looks up
4587d523365SDimitry Andric       // the attributes from the called function will fail.
4597d523365SDimitry Andric 
4607d523365SDimitry Andric       // FIXME: This is not actually true, at least not anymore. The callsite
4617d523365SDimitry Andric       // will always have the same ABI affecting attributes as the callee,
4627d523365SDimitry Andric       // because otherwise the original input has UB. Note that Old and New
4637d523365SDimitry Andric       // always have matching ABI, so no attributes need to be changed.
4647d523365SDimitry Andric       // Transferring other attributes may help other optimizations, but that
4657d523365SDimitry Andric       // should be done uniformly and not in this ad-hoc way.
4667d523365SDimitry Andric       auto &Context = New->getContext();
4677a7e6055SDimitry Andric       auto NewPAL = New->getAttributes();
4687a7e6055SDimitry Andric       SmallVector<AttributeSet, 4> NewArgAttrs;
4697a7e6055SDimitry Andric       for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++)
4707a7e6055SDimitry Andric         NewArgAttrs.push_back(NewPAL.getParamAttributes(argIdx));
4717a7e6055SDimitry Andric       // Don't transfer attributes from the function to the callee. Function
4727a7e6055SDimitry Andric       // attributes typically aren't relevant to the calling convention or ABI.
4737a7e6055SDimitry Andric       CS.setAttributes(AttributeList::get(Context, /*FnAttrs=*/AttributeSet(),
4747a7e6055SDimitry Andric                                           NewPAL.getRetAttributes(),
4757a7e6055SDimitry Andric                                           NewArgAttrs));
4767d523365SDimitry Andric 
477*b5893f02SDimitry Andric       remove(CS.getInstruction()->getFunction());
47891bc56edSDimitry Andric       U->set(BitcastNew);
4792754fe60SDimitry Andric     }
480f22ef01cSRoman Divacky   }
481f22ef01cSRoman Divacky }
482f22ef01cSRoman Divacky 
483f785676fSDimitry Andric // Helper for writeThunk,
484f785676fSDimitry Andric // Selects proper bitcast operation,
48591bc56edSDimitry Andric // but a bit simpler then CastInst::getCastOpcode.
createCast(IRBuilder<> & Builder,Value * V,Type * DestTy)4863ca95b02SDimitry Andric static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
487f785676fSDimitry Andric   Type *SrcTy = V->getType();
48891bc56edSDimitry Andric   if (SrcTy->isStructTy()) {
48991bc56edSDimitry Andric     assert(DestTy->isStructTy());
49091bc56edSDimitry Andric     assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
49191bc56edSDimitry Andric     Value *Result = UndefValue::get(DestTy);
49291bc56edSDimitry Andric     for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
49391bc56edSDimitry Andric       Value *Element = createCast(
49439d628a0SDimitry Andric           Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
49591bc56edSDimitry Andric           DestTy->getStructElementType(I));
49691bc56edSDimitry Andric 
49791bc56edSDimitry Andric       Result =
49839d628a0SDimitry Andric           Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
49991bc56edSDimitry Andric     }
50091bc56edSDimitry Andric     return Result;
50191bc56edSDimitry Andric   }
50291bc56edSDimitry Andric   assert(!DestTy->isStructTy());
503f785676fSDimitry Andric   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
504f785676fSDimitry Andric     return Builder.CreateIntToPtr(V, DestTy);
505f785676fSDimitry Andric   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
506f785676fSDimitry Andric     return Builder.CreatePtrToInt(V, DestTy);
507f785676fSDimitry Andric   else
508f785676fSDimitry Andric     return Builder.CreateBitCast(V, DestTy);
509f785676fSDimitry Andric }
510f785676fSDimitry Andric 
5117a7e6055SDimitry Andric // Erase the instructions in PDIUnrelatedWL as they are unrelated to the
5127a7e6055SDimitry Andric // parameter debug info, from the entry block.
eraseInstsUnrelatedToPDI(std::vector<Instruction * > & PDIUnrelatedWL)5137a7e6055SDimitry Andric void MergeFunctions::eraseInstsUnrelatedToPDI(
5147a7e6055SDimitry Andric     std::vector<Instruction *> &PDIUnrelatedWL) {
5154ba319b5SDimitry Andric   LLVM_DEBUG(
5164ba319b5SDimitry Andric       dbgs() << " Erasing instructions (in reverse order of appearance in "
5177a7e6055SDimitry Andric                 "entry block) unrelated to parameter debug info from entry "
5187a7e6055SDimitry Andric                 "block: {\n");
5197a7e6055SDimitry Andric   while (!PDIUnrelatedWL.empty()) {
5207a7e6055SDimitry Andric     Instruction *I = PDIUnrelatedWL.back();
5214ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Deleting Instruction: ");
5224ba319b5SDimitry Andric     LLVM_DEBUG(I->print(dbgs()));
5234ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
5247a7e6055SDimitry Andric     I->eraseFromParent();
5257a7e6055SDimitry Andric     PDIUnrelatedWL.pop_back();
5267a7e6055SDimitry Andric   }
5274ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
5287a7e6055SDimitry Andric                        "debug info from entry block. \n");
5297a7e6055SDimitry Andric }
5307a7e6055SDimitry Andric 
5317a7e6055SDimitry Andric // Reduce G to its entry block.
eraseTail(Function * G)5327a7e6055SDimitry Andric void MergeFunctions::eraseTail(Function *G) {
5337a7e6055SDimitry Andric   std::vector<BasicBlock *> WorklistBB;
5347a7e6055SDimitry Andric   for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
5357a7e6055SDimitry Andric        BBI != BBE; ++BBI) {
5367a7e6055SDimitry Andric     BBI->dropAllReferences();
5377a7e6055SDimitry Andric     WorklistBB.push_back(&*BBI);
5387a7e6055SDimitry Andric   }
5397a7e6055SDimitry Andric   while (!WorklistBB.empty()) {
5407a7e6055SDimitry Andric     BasicBlock *BB = WorklistBB.back();
5417a7e6055SDimitry Andric     BB->eraseFromParent();
5427a7e6055SDimitry Andric     WorklistBB.pop_back();
5437a7e6055SDimitry Andric   }
5447a7e6055SDimitry Andric }
5457a7e6055SDimitry Andric 
5467a7e6055SDimitry Andric // We are interested in the following instructions from the entry block as being
5477a7e6055SDimitry Andric // related to parameter debug info:
5487a7e6055SDimitry Andric // - @llvm.dbg.declare
5497a7e6055SDimitry Andric // - stores from the incoming parameters to locations on the stack-frame
5507a7e6055SDimitry Andric // - allocas that create these locations on the stack-frame
5517a7e6055SDimitry Andric // - @llvm.dbg.value
5527a7e6055SDimitry Andric // - the entry block's terminator
5537a7e6055SDimitry Andric // The rest are unrelated to debug info for the parameters; fill up
5547a7e6055SDimitry Andric // PDIUnrelatedWL with such instructions.
filterInstsUnrelatedToPDI(BasicBlock * GEntryBlock,std::vector<Instruction * > & PDIUnrelatedWL)5557a7e6055SDimitry Andric void MergeFunctions::filterInstsUnrelatedToPDI(
5567a7e6055SDimitry Andric     BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
5577a7e6055SDimitry Andric   std::set<Instruction *> PDIRelated;
5587a7e6055SDimitry Andric   for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
5597a7e6055SDimitry Andric        BI != BIE; ++BI) {
5607a7e6055SDimitry Andric     if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
5614ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << " Deciding: ");
5624ba319b5SDimitry Andric       LLVM_DEBUG(BI->print(dbgs()));
5634ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
5647a7e6055SDimitry Andric       DILocalVariable *DILocVar = DVI->getVariable();
5657a7e6055SDimitry Andric       if (DILocVar->isParameter()) {
5664ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "  Include (parameter): ");
5674ba319b5SDimitry Andric         LLVM_DEBUG(BI->print(dbgs()));
5684ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "\n");
5697a7e6055SDimitry Andric         PDIRelated.insert(&*BI);
5707a7e6055SDimitry Andric       } else {
5714ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "  Delete (!parameter): ");
5724ba319b5SDimitry Andric         LLVM_DEBUG(BI->print(dbgs()));
5734ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "\n");
5747a7e6055SDimitry Andric       }
5757a7e6055SDimitry Andric     } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
5764ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << " Deciding: ");
5774ba319b5SDimitry Andric       LLVM_DEBUG(BI->print(dbgs()));
5784ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
5797a7e6055SDimitry Andric       DILocalVariable *DILocVar = DDI->getVariable();
5807a7e6055SDimitry Andric       if (DILocVar->isParameter()) {
5814ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "  Parameter: ");
5824ba319b5SDimitry Andric         LLVM_DEBUG(DILocVar->print(dbgs()));
5837a7e6055SDimitry Andric         AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
5847a7e6055SDimitry Andric         if (AI) {
5854ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "  Processing alloca users: ");
5864ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "\n");
5877a7e6055SDimitry Andric           for (User *U : AI->users()) {
5887a7e6055SDimitry Andric             if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
5897a7e6055SDimitry Andric               if (Value *Arg = SI->getValueOperand()) {
5907a7e6055SDimitry Andric                 if (dyn_cast<Argument>(Arg)) {
5914ba319b5SDimitry Andric                   LLVM_DEBUG(dbgs() << "  Include: ");
5924ba319b5SDimitry Andric                   LLVM_DEBUG(AI->print(dbgs()));
5934ba319b5SDimitry Andric                   LLVM_DEBUG(dbgs() << "\n");
5947a7e6055SDimitry Andric                   PDIRelated.insert(AI);
5954ba319b5SDimitry Andric                   LLVM_DEBUG(dbgs() << "   Include (parameter): ");
5964ba319b5SDimitry Andric                   LLVM_DEBUG(SI->print(dbgs()));
5974ba319b5SDimitry Andric                   LLVM_DEBUG(dbgs() << "\n");
5987a7e6055SDimitry Andric                   PDIRelated.insert(SI);
5994ba319b5SDimitry Andric                   LLVM_DEBUG(dbgs() << "  Include: ");
6004ba319b5SDimitry Andric                   LLVM_DEBUG(BI->print(dbgs()));
6014ba319b5SDimitry Andric                   LLVM_DEBUG(dbgs() << "\n");
6027a7e6055SDimitry Andric                   PDIRelated.insert(&*BI);
6037a7e6055SDimitry Andric                 } else {
6044ba319b5SDimitry Andric                   LLVM_DEBUG(dbgs() << "   Delete (!parameter): ");
6054ba319b5SDimitry Andric                   LLVM_DEBUG(SI->print(dbgs()));
6064ba319b5SDimitry Andric                   LLVM_DEBUG(dbgs() << "\n");
6077a7e6055SDimitry Andric                 }
6087a7e6055SDimitry Andric               }
6097a7e6055SDimitry Andric             } else {
6104ba319b5SDimitry Andric               LLVM_DEBUG(dbgs() << "   Defer: ");
6114ba319b5SDimitry Andric               LLVM_DEBUG(U->print(dbgs()));
6124ba319b5SDimitry Andric               LLVM_DEBUG(dbgs() << "\n");
6137a7e6055SDimitry Andric             }
6147a7e6055SDimitry Andric           }
6157a7e6055SDimitry Andric         } else {
6164ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "  Delete (alloca NULL): ");
6174ba319b5SDimitry Andric           LLVM_DEBUG(BI->print(dbgs()));
6184ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "\n");
6197a7e6055SDimitry Andric         }
6207a7e6055SDimitry Andric       } else {
6214ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "  Delete (!parameter): ");
6224ba319b5SDimitry Andric         LLVM_DEBUG(BI->print(dbgs()));
6234ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "\n");
6247a7e6055SDimitry Andric       }
625*b5893f02SDimitry Andric     } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
6264ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
6274ba319b5SDimitry Andric       LLVM_DEBUG(BI->print(dbgs()));
6284ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
6297a7e6055SDimitry Andric       PDIRelated.insert(&*BI);
6307a7e6055SDimitry Andric     } else {
6314ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << " Defer: ");
6324ba319b5SDimitry Andric       LLVM_DEBUG(BI->print(dbgs()));
6334ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
6347a7e6055SDimitry Andric     }
6357a7e6055SDimitry Andric   }
6364ba319b5SDimitry Andric   LLVM_DEBUG(
6374ba319b5SDimitry Andric       dbgs()
6387a7e6055SDimitry Andric       << " Report parameter debug info related/related instructions: {\n");
6397a7e6055SDimitry Andric   for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
6407a7e6055SDimitry Andric        BI != BE; ++BI) {
6417a7e6055SDimitry Andric 
6427a7e6055SDimitry Andric     Instruction *I = &*BI;
6437a7e6055SDimitry Andric     if (PDIRelated.find(I) == PDIRelated.end()) {
6444ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "  !PDIRelated: ");
6454ba319b5SDimitry Andric       LLVM_DEBUG(I->print(dbgs()));
6464ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
6477a7e6055SDimitry Andric       PDIUnrelatedWL.push_back(I);
6487a7e6055SDimitry Andric     } else {
6494ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "   PDIRelated: ");
6504ba319b5SDimitry Andric       LLVM_DEBUG(I->print(dbgs()));
6514ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
6527a7e6055SDimitry Andric     }
6537a7e6055SDimitry Andric   }
6544ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << " }\n");
6557a7e6055SDimitry Andric }
6567a7e6055SDimitry Andric 
6576ccc06f6SDimitry Andric // Don't merge tiny functions using a thunk, since it can just end up
6586ccc06f6SDimitry Andric // making the function larger.
isThunkProfitable(Function * F)6596ccc06f6SDimitry Andric static bool isThunkProfitable(Function * F) {
6606ccc06f6SDimitry Andric   if (F->size() == 1) {
6616ccc06f6SDimitry Andric     if (F->front().size() <= 2) {
6624ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "isThunkProfitable: " << F->getName()
6636ccc06f6SDimitry Andric                         << " is too small to bother creating a thunk for\n");
6646ccc06f6SDimitry Andric       return false;
6656ccc06f6SDimitry Andric     }
6666ccc06f6SDimitry Andric   }
6676ccc06f6SDimitry Andric   return true;
6686ccc06f6SDimitry Andric }
6696ccc06f6SDimitry Andric 
6707a7e6055SDimitry Andric // Replace G with a simple tail call to bitcast(F). Also (unless
6717a7e6055SDimitry Andric // MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
6727a7e6055SDimitry Andric // delete G. Under MergeFunctionsPDI, we use G itself for creating
6737a7e6055SDimitry Andric // the thunk as we preserve the debug info (and associated instructions)
6747a7e6055SDimitry Andric // from G's entry block pertaining to G's incoming arguments which are
6757a7e6055SDimitry Andric // passed on as corresponding arguments in the call that G makes to F.
6767a7e6055SDimitry Andric // For better debugability, under MergeFunctionsPDI, we do not modify G's
6777a7e6055SDimitry Andric // call sites to point to F even when within the same translation unit.
writeThunk(Function * F,Function * G)6782754fe60SDimitry Andric void MergeFunctions::writeThunk(Function *F, Function *G) {
6797a7e6055SDimitry Andric   BasicBlock *GEntryBlock = nullptr;
6807a7e6055SDimitry Andric   std::vector<Instruction *> PDIUnrelatedWL;
6817a7e6055SDimitry Andric   BasicBlock *BB = nullptr;
6827a7e6055SDimitry Andric   Function *NewG = nullptr;
6837a7e6055SDimitry Andric   if (MergeFunctionsPDI) {
6844ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
6857a7e6055SDimitry Andric                          "function as thunk; retain original: "
6867a7e6055SDimitry Andric                       << G->getName() << "()\n");
6877a7e6055SDimitry Andric     GEntryBlock = &G->getEntryBlock();
6884ba319b5SDimitry Andric     LLVM_DEBUG(
6894ba319b5SDimitry Andric         dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
6907a7e6055SDimitry Andric                   "debug info for "
6917a7e6055SDimitry Andric                << G->getName() << "() {\n");
6927a7e6055SDimitry Andric     filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
6937a7e6055SDimitry Andric     GEntryBlock->getTerminator()->eraseFromParent();
6947a7e6055SDimitry Andric     BB = GEntryBlock;
6957a7e6055SDimitry Andric   } else {
696*b5893f02SDimitry Andric     NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
697*b5893f02SDimitry Andric                             G->getAddressSpace(), "", G->getParent());
6987a7e6055SDimitry Andric     BB = BasicBlock::Create(F->getContext(), "", NewG);
6997a7e6055SDimitry Andric   }
700f22ef01cSRoman Divacky 
7017a7e6055SDimitry Andric   IRBuilder<> Builder(BB);
7027a7e6055SDimitry Andric   Function *H = MergeFunctionsPDI ? G : NewG;
703f22ef01cSRoman Divacky   SmallVector<Value *, 16> Args;
704f22ef01cSRoman Divacky   unsigned i = 0;
7056122f3e6SDimitry Andric   FunctionType *FFTy = F->getFunctionType();
7067a7e6055SDimitry Andric   for (Argument &AI : H->args()) {
7077d523365SDimitry Andric     Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
708f22ef01cSRoman Divacky     ++i;
709f22ef01cSRoman Divacky   }
710f22ef01cSRoman Divacky 
71117a519f9SDimitry Andric   CallInst *CI = Builder.CreateCall(F, Args);
7127a7e6055SDimitry Andric   ReturnInst *RI = nullptr;
713f22ef01cSRoman Divacky   CI->setTailCall();
714f22ef01cSRoman Divacky   CI->setCallingConv(F->getCallingConv());
7157d523365SDimitry Andric   CI->setAttributes(F->getAttributes());
7167a7e6055SDimitry Andric   if (H->getReturnType()->isVoidTy()) {
7177a7e6055SDimitry Andric     RI = Builder.CreateRetVoid();
718f22ef01cSRoman Divacky   } else {
7197a7e6055SDimitry Andric     RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
720f22ef01cSRoman Divacky   }
721f22ef01cSRoman Divacky 
7227a7e6055SDimitry Andric   if (MergeFunctionsPDI) {
7237a7e6055SDimitry Andric     DISubprogram *DIS = G->getSubprogram();
7247a7e6055SDimitry Andric     if (DIS) {
7257a7e6055SDimitry Andric       DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
7267a7e6055SDimitry Andric       DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
7277a7e6055SDimitry Andric       CI->setDebugLoc(CIDbgLoc);
7287a7e6055SDimitry Andric       RI->setDebugLoc(RIDbgLoc);
7297a7e6055SDimitry Andric     } else {
7304ba319b5SDimitry Andric       LLVM_DEBUG(
7314ba319b5SDimitry Andric           dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
7327a7e6055SDimitry Andric                  << G->getName() << "()\n");
7337a7e6055SDimitry Andric     }
7347a7e6055SDimitry Andric     eraseTail(G);
7357a7e6055SDimitry Andric     eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
7364ba319b5SDimitry Andric     LLVM_DEBUG(
7374ba319b5SDimitry Andric         dbgs() << "} // End of parameter related debug info filtering for: "
7387a7e6055SDimitry Andric                << G->getName() << "()\n");
7397a7e6055SDimitry Andric   } else {
740f22ef01cSRoman Divacky     NewG->copyAttributesFrom(G);
741f22ef01cSRoman Divacky     NewG->takeName(G);
7422754fe60SDimitry Andric     removeUsers(G);
743f22ef01cSRoman Divacky     G->replaceAllUsesWith(NewG);
744f22ef01cSRoman Divacky     G->eraseFromParent();
7457a7e6055SDimitry Andric   }
7462754fe60SDimitry Andric 
7474ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
7482754fe60SDimitry Andric   ++NumThunksWritten;
749f22ef01cSRoman Divacky }
750f22ef01cSRoman Divacky 
751*b5893f02SDimitry Andric // Whether this function may be replaced by an alias
canCreateAliasFor(Function * F)752*b5893f02SDimitry Andric static bool canCreateAliasFor(Function *F) {
753*b5893f02SDimitry Andric   if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
754*b5893f02SDimitry Andric     return false;
755*b5893f02SDimitry Andric 
756*b5893f02SDimitry Andric   // We should only see linkages supported by aliases here
757*b5893f02SDimitry Andric   assert(F->hasLocalLinkage() || F->hasExternalLinkage()
758*b5893f02SDimitry Andric       || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
759*b5893f02SDimitry Andric   return true;
760*b5893f02SDimitry Andric }
761*b5893f02SDimitry Andric 
762*b5893f02SDimitry Andric // Replace G with an alias to F (deleting function G)
writeAlias(Function * F,Function * G)763*b5893f02SDimitry Andric void MergeFunctions::writeAlias(Function *F, Function *G) {
764*b5893f02SDimitry Andric   Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
765*b5893f02SDimitry Andric   PointerType *PtrType = G->getType();
766*b5893f02SDimitry Andric   auto *GA = GlobalAlias::create(
767*b5893f02SDimitry Andric       PtrType->getElementType(), PtrType->getAddressSpace(),
768*b5893f02SDimitry Andric       G->getLinkage(), "", BitcastF, G->getParent());
769*b5893f02SDimitry Andric 
770*b5893f02SDimitry Andric   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
771*b5893f02SDimitry Andric   GA->takeName(G);
772*b5893f02SDimitry Andric   GA->setVisibility(G->getVisibility());
773*b5893f02SDimitry Andric   GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
774*b5893f02SDimitry Andric 
775*b5893f02SDimitry Andric   removeUsers(G);
776*b5893f02SDimitry Andric   G->replaceAllUsesWith(GA);
777*b5893f02SDimitry Andric   G->eraseFromParent();
778*b5893f02SDimitry Andric 
779*b5893f02SDimitry Andric   LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
780*b5893f02SDimitry Andric   ++NumAliasesWritten;
781*b5893f02SDimitry Andric }
782*b5893f02SDimitry Andric 
783*b5893f02SDimitry Andric // Replace G with an alias to F if possible, or a thunk to F if
784*b5893f02SDimitry Andric // profitable. Returns false if neither is the case.
writeThunkOrAlias(Function * F,Function * G)785*b5893f02SDimitry Andric bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
786*b5893f02SDimitry Andric   if (canCreateAliasFor(G)) {
787*b5893f02SDimitry Andric     writeAlias(F, G);
788*b5893f02SDimitry Andric     return true;
789*b5893f02SDimitry Andric   }
790*b5893f02SDimitry Andric   if (isThunkProfitable(F)) {
791*b5893f02SDimitry Andric     writeThunk(F, G);
792*b5893f02SDimitry Andric     return true;
793*b5893f02SDimitry Andric   }
794*b5893f02SDimitry Andric   return false;
795*b5893f02SDimitry Andric }
796*b5893f02SDimitry Andric 
7972754fe60SDimitry Andric // Merge two equivalent functions. Upon completion, Function G is deleted.
mergeTwoFunctions(Function * F,Function * G)7982754fe60SDimitry Andric void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
7993ca95b02SDimitry Andric   if (F->isInterposable()) {
8003ca95b02SDimitry Andric     assert(G->isInterposable());
8012754fe60SDimitry Andric 
802*b5893f02SDimitry Andric     // Both writeThunkOrAlias() calls below must succeed, either because we can
803*b5893f02SDimitry Andric     // create aliases for G and NewF, or because a thunk for F is profitable.
804*b5893f02SDimitry Andric     // F here has the same signature as NewF below, so that's what we check.
805*b5893f02SDimitry Andric     if (!isThunkProfitable(F) && (!canCreateAliasFor(F) || !canCreateAliasFor(G))) {
8066ccc06f6SDimitry Andric       return;
8076ccc06f6SDimitry Andric     }
8086ccc06f6SDimitry Andric 
809f22ef01cSRoman Divacky     // Make them both thunks to the same internal function.
810*b5893f02SDimitry Andric     Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
811*b5893f02SDimitry Andric                                       F->getAddressSpace(), "", F->getParent());
812*b5893f02SDimitry Andric     NewF->copyAttributesFrom(F);
813*b5893f02SDimitry Andric     NewF->takeName(F);
8142754fe60SDimitry Andric     removeUsers(F);
815*b5893f02SDimitry Andric     F->replaceAllUsesWith(NewF);
816f22ef01cSRoman Divacky 
817*b5893f02SDimitry Andric     unsigned MaxAlignment = std::max(G->getAlignment(), NewF->getAlignment());
818f22ef01cSRoman Divacky 
819*b5893f02SDimitry Andric     writeThunkOrAlias(F, G);
820*b5893f02SDimitry Andric     writeThunkOrAlias(F, NewF);
821e580952dSDimitry Andric 
822e580952dSDimitry Andric     F->setAlignment(MaxAlignment);
8232754fe60SDimitry Andric     F->setLinkage(GlobalValue::PrivateLinkage);
8242754fe60SDimitry Andric     ++NumDoubleWeak;
8256ccc06f6SDimitry Andric     ++NumFunctionsMerged;
8262754fe60SDimitry Andric   } else {
8276ccc06f6SDimitry Andric     // For better debugability, under MergeFunctionsPDI, we do not modify G's
8286ccc06f6SDimitry Andric     // call sites to point to F even when within the same translation unit.
8296ccc06f6SDimitry Andric     if (!G->isInterposable() && !MergeFunctionsPDI) {
8306ccc06f6SDimitry Andric       if (G->hasGlobalUnnamedAddr()) {
8316ccc06f6SDimitry Andric         // G might have been a key in our GlobalNumberState, and it's illegal
8326ccc06f6SDimitry Andric         // to replace a key in ValueMap<GlobalValue *> with a non-global.
8336ccc06f6SDimitry Andric         GlobalNumbers.erase(G);
8346ccc06f6SDimitry Andric         // If G's address is not significant, replace it entirely.
8356ccc06f6SDimitry Andric         Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
836*b5893f02SDimitry Andric         removeUsers(G);
8376ccc06f6SDimitry Andric         G->replaceAllUsesWith(BitcastF);
8386ccc06f6SDimitry Andric       } else {
8396ccc06f6SDimitry Andric         // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
8406ccc06f6SDimitry Andric         // above).
8416ccc06f6SDimitry Andric         replaceDirectCallers(G, F);
8426ccc06f6SDimitry Andric       }
843f22ef01cSRoman Divacky     }
844f22ef01cSRoman Divacky 
8456ccc06f6SDimitry Andric     // If G was internal then we may have replaced all uses of G with F. If so,
8466ccc06f6SDimitry Andric     // stop here and delete G. There's no need for a thunk. (See note on
8476ccc06f6SDimitry Andric     // MergeFunctionsPDI above).
848*b5893f02SDimitry Andric     if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
8496ccc06f6SDimitry Andric       G->eraseFromParent();
850f22ef01cSRoman Divacky       ++NumFunctionsMerged;
8516ccc06f6SDimitry Andric       return;
8526ccc06f6SDimitry Andric     }
8536ccc06f6SDimitry Andric 
854*b5893f02SDimitry Andric     if (writeThunkOrAlias(F, G)) {
8556ccc06f6SDimitry Andric       ++NumFunctionsMerged;
8566ccc06f6SDimitry Andric     }
857f22ef01cSRoman Divacky   }
858*b5893f02SDimitry Andric }
859f22ef01cSRoman Divacky 
8607d523365SDimitry Andric /// Replace function F by function G.
replaceFunctionInTree(const FunctionNode & FN,Function * G)8617d523365SDimitry Andric void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
86297bc6c73SDimitry Andric                                            Function *G) {
8637d523365SDimitry Andric   Function *F = FN.getFunc();
8647d523365SDimitry Andric   assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
8657d523365SDimitry Andric          "The two functions must be equal");
86697bc6c73SDimitry Andric 
8677d523365SDimitry Andric   auto I = FNodesInTree.find(F);
8687d523365SDimitry Andric   assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
8697d523365SDimitry Andric   assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
87097bc6c73SDimitry Andric 
8717d523365SDimitry Andric   FnTreeType::iterator IterToFNInFnTree = I->second;
8727d523365SDimitry Andric   assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
8737d523365SDimitry Andric   // Remove F -> FN and insert G -> FN
8747d523365SDimitry Andric   FNodesInTree.erase(I);
8757d523365SDimitry Andric   FNodesInTree.insert({G, IterToFNInFnTree});
8767d523365SDimitry Andric   // Replace F with G in FN, which is stored inside the FnTree.
8777d523365SDimitry Andric   FN.replaceBy(G);
87897bc6c73SDimitry Andric }
87997bc6c73SDimitry Andric 
880*b5893f02SDimitry Andric // Ordering for functions that are equal under FunctionComparator
isFuncOrderCorrect(const Function * F,const Function * G)881*b5893f02SDimitry Andric static bool isFuncOrderCorrect(const Function *F, const Function *G) {
882*b5893f02SDimitry Andric   if (F->isInterposable() != G->isInterposable()) {
883*b5893f02SDimitry Andric     // Strong before weak, because the weak function may call the strong
884*b5893f02SDimitry Andric     // one, but not the other way around.
885*b5893f02SDimitry Andric     return !F->isInterposable();
886*b5893f02SDimitry Andric   }
887*b5893f02SDimitry Andric   if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
888*b5893f02SDimitry Andric     // External before local, because we definitely have to keep the external
889*b5893f02SDimitry Andric     // function, but may be able to drop the local one.
890*b5893f02SDimitry Andric     return !F->hasLocalLinkage();
891*b5893f02SDimitry Andric   }
892*b5893f02SDimitry Andric   // Impose a total order (by name) on the replacement of functions. This is
893*b5893f02SDimitry Andric   // important when operating on more than one module independently to prevent
894*b5893f02SDimitry Andric   // cycles of thunks calling each other when the modules are linked together.
895*b5893f02SDimitry Andric   return F->getName() <= G->getName();
896*b5893f02SDimitry Andric }
897*b5893f02SDimitry Andric 
89891bc56edSDimitry Andric // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
8992754fe60SDimitry Andric // that was already inserted.
insert(Function * NewFunction)90091bc56edSDimitry Andric bool MergeFunctions::insert(Function *NewFunction) {
90191bc56edSDimitry Andric   std::pair<FnTreeType::iterator, bool> Result =
902ff0cc061SDimitry Andric       FnTree.insert(FunctionNode(NewFunction));
90391bc56edSDimitry Andric 
9042754fe60SDimitry Andric   if (Result.second) {
9057d523365SDimitry Andric     assert(FNodesInTree.count(NewFunction) == 0);
9067d523365SDimitry Andric     FNodesInTree.insert({NewFunction, Result.first});
9074ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
9084ba319b5SDimitry Andric                       << '\n');
9092754fe60SDimitry Andric     return false;
9102754fe60SDimitry Andric   }
911f22ef01cSRoman Divacky 
91239d628a0SDimitry Andric   const FunctionNode &OldF = *Result.first;
913f22ef01cSRoman Divacky 
914*b5893f02SDimitry Andric   if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
91597bc6c73SDimitry Andric     // Swap the two functions.
91697bc6c73SDimitry Andric     Function *F = OldF.getFunc();
9177d523365SDimitry Andric     replaceFunctionInTree(*Result.first, NewFunction);
91897bc6c73SDimitry Andric     NewFunction = F;
91997bc6c73SDimitry Andric     assert(OldF.getFunc() != F && "Must have swapped the functions.");
92097bc6c73SDimitry Andric   }
92197bc6c73SDimitry Andric 
9224ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "  " << OldF.getFunc()->getName()
92391bc56edSDimitry Andric                     << " == " << NewFunction->getName() << '\n');
924e580952dSDimitry Andric 
92591bc56edSDimitry Andric   Function *DeleteF = NewFunction;
9262754fe60SDimitry Andric   mergeTwoFunctions(OldF.getFunc(), DeleteF);
9272754fe60SDimitry Andric   return true;
9282754fe60SDimitry Andric }
929e580952dSDimitry Andric 
93091bc56edSDimitry Andric // Remove a function from FnTree. If it was already in FnTree, add
93191bc56edSDimitry Andric // it to Deferred so that we'll look at it in the next round.
remove(Function * F)9322754fe60SDimitry Andric void MergeFunctions::remove(Function *F) {
9337d523365SDimitry Andric   auto I = FNodesInTree.find(F);
9347d523365SDimitry Andric   if (I != FNodesInTree.end()) {
9354ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
9367d523365SDimitry Andric     FnTree.erase(I->second);
9377d523365SDimitry Andric     // I->second has been invalidated, remove it from the FNodesInTree map to
9387d523365SDimitry Andric     // preserve the invariant.
9397d523365SDimitry Andric     FNodesInTree.erase(I);
94097bc6c73SDimitry Andric     Deferred.emplace_back(F);
941f22ef01cSRoman Divacky   }
942f22ef01cSRoman Divacky }
943f22ef01cSRoman Divacky 
9442754fe60SDimitry Andric // For each instruction used by the value, remove() the function that contains
9452754fe60SDimitry Andric // the instruction. This should happen right before a call to RAUW.
removeUsers(Value * V)9462754fe60SDimitry Andric void MergeFunctions::removeUsers(Value *V) {
9472754fe60SDimitry Andric   std::vector<Value *> Worklist;
9482754fe60SDimitry Andric   Worklist.push_back(V);
9494ba319b5SDimitry Andric   SmallPtrSet<Value*, 8> Visited;
9507d523365SDimitry Andric   Visited.insert(V);
9512754fe60SDimitry Andric   while (!Worklist.empty()) {
9522754fe60SDimitry Andric     Value *V = Worklist.back();
9532754fe60SDimitry Andric     Worklist.pop_back();
9542754fe60SDimitry Andric 
95591bc56edSDimitry Andric     for (User *U : V->users()) {
95691bc56edSDimitry Andric       if (Instruction *I = dyn_cast<Instruction>(U)) {
957*b5893f02SDimitry Andric         remove(I->getFunction());
95891bc56edSDimitry Andric       } else if (isa<GlobalValue>(U)) {
9592754fe60SDimitry Andric         // do nothing
96091bc56edSDimitry Andric       } else if (Constant *C = dyn_cast<Constant>(U)) {
9617d523365SDimitry Andric         for (User *UU : C->users()) {
9627d523365SDimitry Andric           if (!Visited.insert(UU).second)
96391bc56edSDimitry Andric             Worklist.push_back(UU);
9642754fe60SDimitry Andric         }
9652754fe60SDimitry Andric       }
9662754fe60SDimitry Andric     }
967f22ef01cSRoman Divacky   }
9687d523365SDimitry Andric }
969