1*0b57cec5SDimitry Andric //===- MergeFunctions.cpp - Merge identical functions ---------------------===// 2*0b57cec5SDimitry Andric // 3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*0b57cec5SDimitry Andric // 7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 8*0b57cec5SDimitry Andric // 9*0b57cec5SDimitry Andric // This pass looks for equivalent functions that are mergable and folds them. 10*0b57cec5SDimitry Andric // 11*0b57cec5SDimitry Andric // Order relation is defined on set of functions. It was made through 12*0b57cec5SDimitry Andric // special function comparison procedure that returns 13*0b57cec5SDimitry Andric // 0 when functions are equal, 14*0b57cec5SDimitry Andric // -1 when Left function is less than right function, and 15*0b57cec5SDimitry Andric // 1 for opposite case. We need total-ordering, so we need to maintain 16*0b57cec5SDimitry Andric // four properties on the functions set: 17*0b57cec5SDimitry Andric // a <= a (reflexivity) 18*0b57cec5SDimitry Andric // if a <= b and b <= a then a = b (antisymmetry) 19*0b57cec5SDimitry Andric // if a <= b and b <= c then a <= c (transitivity). 20*0b57cec5SDimitry Andric // for all a and b: a <= b or b <= a (totality). 21*0b57cec5SDimitry Andric // 22*0b57cec5SDimitry Andric // Comparison iterates through each instruction in each basic block. 23*0b57cec5SDimitry Andric // Functions are kept on binary tree. For each new function F we perform 24*0b57cec5SDimitry Andric // lookup in binary tree. 25*0b57cec5SDimitry Andric // In practice it works the following way: 26*0b57cec5SDimitry Andric // -- We define Function* container class with custom "operator<" (FunctionPtr). 27*0b57cec5SDimitry Andric // -- "FunctionPtr" instances are stored in std::set collection, so every 28*0b57cec5SDimitry Andric // std::set::insert operation will give you result in log(N) time. 29*0b57cec5SDimitry Andric // 30*0b57cec5SDimitry Andric // As an optimization, a hash of the function structure is calculated first, and 31*0b57cec5SDimitry Andric // two functions are only compared if they have the same hash. This hash is 32*0b57cec5SDimitry Andric // cheap to compute, and has the property that if function F == G according to 33*0b57cec5SDimitry Andric // the comparison function, then hash(F) == hash(G). This consistency property 34*0b57cec5SDimitry Andric // is critical to ensuring all possible merging opportunities are exploited. 35*0b57cec5SDimitry Andric // Collisions in the hash affect the speed of the pass but not the correctness 36*0b57cec5SDimitry Andric // or determinism of the resulting transformation. 37*0b57cec5SDimitry Andric // 38*0b57cec5SDimitry Andric // When a match is found the functions are folded. If both functions are 39*0b57cec5SDimitry Andric // overridable, we move the functionality into a new internal function and 40*0b57cec5SDimitry Andric // leave two overridable thunks to it. 41*0b57cec5SDimitry Andric // 42*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 43*0b57cec5SDimitry Andric // 44*0b57cec5SDimitry Andric // Future work: 45*0b57cec5SDimitry Andric // 46*0b57cec5SDimitry Andric // * virtual functions. 47*0b57cec5SDimitry Andric // 48*0b57cec5SDimitry Andric // Many functions have their address taken by the virtual function table for 49*0b57cec5SDimitry Andric // the object they belong to. However, as long as it's only used for a lookup 50*0b57cec5SDimitry Andric // and call, this is irrelevant, and we'd like to fold such functions. 51*0b57cec5SDimitry Andric // 52*0b57cec5SDimitry Andric // * be smarter about bitcasts. 53*0b57cec5SDimitry Andric // 54*0b57cec5SDimitry Andric // In order to fold functions, we will sometimes add either bitcast instructions 55*0b57cec5SDimitry Andric // or bitcast constant expressions. Unfortunately, this can confound further 56*0b57cec5SDimitry Andric // analysis since the two functions differ where one has a bitcast and the 57*0b57cec5SDimitry Andric // other doesn't. We should learn to look through bitcasts. 58*0b57cec5SDimitry Andric // 59*0b57cec5SDimitry Andric // * Compare complex types with pointer types inside. 60*0b57cec5SDimitry Andric // * Compare cross-reference cases. 61*0b57cec5SDimitry Andric // * Compare complex expressions. 62*0b57cec5SDimitry Andric // 63*0b57cec5SDimitry Andric // All the three issues above could be described as ability to prove that 64*0b57cec5SDimitry Andric // fA == fB == fC == fE == fF == fG in example below: 65*0b57cec5SDimitry Andric // 66*0b57cec5SDimitry Andric // void fA() { 67*0b57cec5SDimitry Andric // fB(); 68*0b57cec5SDimitry Andric // } 69*0b57cec5SDimitry Andric // void fB() { 70*0b57cec5SDimitry Andric // fA(); 71*0b57cec5SDimitry Andric // } 72*0b57cec5SDimitry Andric // 73*0b57cec5SDimitry Andric // void fE() { 74*0b57cec5SDimitry Andric // fF(); 75*0b57cec5SDimitry Andric // } 76*0b57cec5SDimitry Andric // void fF() { 77*0b57cec5SDimitry Andric // fG(); 78*0b57cec5SDimitry Andric // } 79*0b57cec5SDimitry Andric // void fG() { 80*0b57cec5SDimitry Andric // fE(); 81*0b57cec5SDimitry Andric // } 82*0b57cec5SDimitry Andric // 83*0b57cec5SDimitry Andric // Simplest cross-reference case (fA <--> fB) was implemented in previous 84*0b57cec5SDimitry Andric // versions of MergeFunctions, though it presented only in two function pairs 85*0b57cec5SDimitry Andric // in test-suite (that counts >50k functions) 86*0b57cec5SDimitry Andric // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A) 87*0b57cec5SDimitry Andric // could cover much more cases. 88*0b57cec5SDimitry Andric // 89*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 90*0b57cec5SDimitry Andric 91*0b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h" 92*0b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 93*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 94*0b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 95*0b57cec5SDimitry Andric #include "llvm/IR/Argument.h" 96*0b57cec5SDimitry Andric #include "llvm/IR/Attributes.h" 97*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h" 98*0b57cec5SDimitry Andric #include "llvm/IR/CallSite.h" 99*0b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 100*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 101*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 102*0b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h" 103*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 104*0b57cec5SDimitry Andric #include "llvm/IR/Function.h" 105*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h" 106*0b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h" 107*0b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 108*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h" 109*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 110*0b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 111*0b57cec5SDimitry Andric #include "llvm/IR/Module.h" 112*0b57cec5SDimitry Andric #include "llvm/IR/Type.h" 113*0b57cec5SDimitry Andric #include "llvm/IR/Use.h" 114*0b57cec5SDimitry Andric #include "llvm/IR/User.h" 115*0b57cec5SDimitry Andric #include "llvm/IR/Value.h" 116*0b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h" 117*0b57cec5SDimitry Andric #include "llvm/IR/ValueMap.h" 118*0b57cec5SDimitry Andric #include "llvm/Pass.h" 119*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 120*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 121*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 122*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 123*0b57cec5SDimitry Andric #include "llvm/Transforms/IPO.h" 124*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/FunctionComparator.h" 125*0b57cec5SDimitry Andric #include <algorithm> 126*0b57cec5SDimitry Andric #include <cassert> 127*0b57cec5SDimitry Andric #include <iterator> 128*0b57cec5SDimitry Andric #include <set> 129*0b57cec5SDimitry Andric #include <utility> 130*0b57cec5SDimitry Andric #include <vector> 131*0b57cec5SDimitry Andric 132*0b57cec5SDimitry Andric using namespace llvm; 133*0b57cec5SDimitry Andric 134*0b57cec5SDimitry Andric #define DEBUG_TYPE "mergefunc" 135*0b57cec5SDimitry Andric 136*0b57cec5SDimitry Andric STATISTIC(NumFunctionsMerged, "Number of functions merged"); 137*0b57cec5SDimitry Andric STATISTIC(NumThunksWritten, "Number of thunks generated"); 138*0b57cec5SDimitry Andric STATISTIC(NumAliasesWritten, "Number of aliases generated"); 139*0b57cec5SDimitry Andric STATISTIC(NumDoubleWeak, "Number of new functions created"); 140*0b57cec5SDimitry Andric 141*0b57cec5SDimitry Andric static cl::opt<unsigned> NumFunctionsForSanityCheck( 142*0b57cec5SDimitry Andric "mergefunc-sanity", 143*0b57cec5SDimitry Andric cl::desc("How many functions in module could be used for " 144*0b57cec5SDimitry Andric "MergeFunctions pass sanity check. " 145*0b57cec5SDimitry Andric "'0' disables this check. Works only with '-debug' key."), 146*0b57cec5SDimitry Andric cl::init(0), cl::Hidden); 147*0b57cec5SDimitry Andric 148*0b57cec5SDimitry Andric // Under option -mergefunc-preserve-debug-info we: 149*0b57cec5SDimitry Andric // - Do not create a new function for a thunk. 150*0b57cec5SDimitry Andric // - Retain the debug info for a thunk's parameters (and associated 151*0b57cec5SDimitry Andric // instructions for the debug info) from the entry block. 152*0b57cec5SDimitry Andric // Note: -debug will display the algorithm at work. 153*0b57cec5SDimitry Andric // - Create debug-info for the call (to the shared implementation) made by 154*0b57cec5SDimitry Andric // a thunk and its return value. 155*0b57cec5SDimitry Andric // - Erase the rest of the function, retaining the (minimally sized) entry 156*0b57cec5SDimitry Andric // block to create a thunk. 157*0b57cec5SDimitry Andric // - Preserve a thunk's call site to point to the thunk even when both occur 158*0b57cec5SDimitry Andric // within the same translation unit, to aid debugability. Note that this 159*0b57cec5SDimitry Andric // behaviour differs from the underlying -mergefunc implementation which 160*0b57cec5SDimitry Andric // modifies the thunk's call site to point to the shared implementation 161*0b57cec5SDimitry Andric // when both occur within the same translation unit. 162*0b57cec5SDimitry Andric static cl::opt<bool> 163*0b57cec5SDimitry Andric MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden, 164*0b57cec5SDimitry Andric cl::init(false), 165*0b57cec5SDimitry Andric cl::desc("Preserve debug info in thunk when mergefunc " 166*0b57cec5SDimitry Andric "transformations are made.")); 167*0b57cec5SDimitry Andric 168*0b57cec5SDimitry Andric static cl::opt<bool> 169*0b57cec5SDimitry Andric MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden, 170*0b57cec5SDimitry Andric cl::init(false), 171*0b57cec5SDimitry Andric cl::desc("Allow mergefunc to create aliases")); 172*0b57cec5SDimitry Andric 173*0b57cec5SDimitry Andric namespace { 174*0b57cec5SDimitry Andric 175*0b57cec5SDimitry Andric class FunctionNode { 176*0b57cec5SDimitry Andric mutable AssertingVH<Function> F; 177*0b57cec5SDimitry Andric FunctionComparator::FunctionHash Hash; 178*0b57cec5SDimitry Andric 179*0b57cec5SDimitry Andric public: 180*0b57cec5SDimitry Andric // Note the hash is recalculated potentially multiple times, but it is cheap. 181*0b57cec5SDimitry Andric FunctionNode(Function *F) 182*0b57cec5SDimitry Andric : F(F), Hash(FunctionComparator::functionHash(*F)) {} 183*0b57cec5SDimitry Andric 184*0b57cec5SDimitry Andric Function *getFunc() const { return F; } 185*0b57cec5SDimitry Andric FunctionComparator::FunctionHash getHash() const { return Hash; } 186*0b57cec5SDimitry Andric 187*0b57cec5SDimitry Andric /// Replace the reference to the function F by the function G, assuming their 188*0b57cec5SDimitry Andric /// implementations are equal. 189*0b57cec5SDimitry Andric void replaceBy(Function *G) const { 190*0b57cec5SDimitry Andric F = G; 191*0b57cec5SDimitry Andric } 192*0b57cec5SDimitry Andric }; 193*0b57cec5SDimitry Andric 194*0b57cec5SDimitry Andric /// MergeFunctions finds functions which will generate identical machine code, 195*0b57cec5SDimitry Andric /// by considering all pointer types to be equivalent. Once identified, 196*0b57cec5SDimitry Andric /// MergeFunctions will fold them by replacing a call to one to a call to a 197*0b57cec5SDimitry Andric /// bitcast of the other. 198*0b57cec5SDimitry Andric class MergeFunctions : public ModulePass { 199*0b57cec5SDimitry Andric public: 200*0b57cec5SDimitry Andric static char ID; 201*0b57cec5SDimitry Andric 202*0b57cec5SDimitry Andric MergeFunctions() 203*0b57cec5SDimitry Andric : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)) { 204*0b57cec5SDimitry Andric initializeMergeFunctionsPass(*PassRegistry::getPassRegistry()); 205*0b57cec5SDimitry Andric } 206*0b57cec5SDimitry Andric 207*0b57cec5SDimitry Andric bool runOnModule(Module &M) override; 208*0b57cec5SDimitry Andric 209*0b57cec5SDimitry Andric private: 210*0b57cec5SDimitry Andric // The function comparison operator is provided here so that FunctionNodes do 211*0b57cec5SDimitry Andric // not need to become larger with another pointer. 212*0b57cec5SDimitry Andric class FunctionNodeCmp { 213*0b57cec5SDimitry Andric GlobalNumberState* GlobalNumbers; 214*0b57cec5SDimitry Andric 215*0b57cec5SDimitry Andric public: 216*0b57cec5SDimitry Andric FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {} 217*0b57cec5SDimitry Andric 218*0b57cec5SDimitry Andric bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const { 219*0b57cec5SDimitry Andric // Order first by hashes, then full function comparison. 220*0b57cec5SDimitry Andric if (LHS.getHash() != RHS.getHash()) 221*0b57cec5SDimitry Andric return LHS.getHash() < RHS.getHash(); 222*0b57cec5SDimitry Andric FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers); 223*0b57cec5SDimitry Andric return FCmp.compare() == -1; 224*0b57cec5SDimitry Andric } 225*0b57cec5SDimitry Andric }; 226*0b57cec5SDimitry Andric using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>; 227*0b57cec5SDimitry Andric 228*0b57cec5SDimitry Andric GlobalNumberState GlobalNumbers; 229*0b57cec5SDimitry Andric 230*0b57cec5SDimitry Andric /// A work queue of functions that may have been modified and should be 231*0b57cec5SDimitry Andric /// analyzed again. 232*0b57cec5SDimitry Andric std::vector<WeakTrackingVH> Deferred; 233*0b57cec5SDimitry Andric 234*0b57cec5SDimitry Andric #ifndef NDEBUG 235*0b57cec5SDimitry Andric /// Checks the rules of order relation introduced among functions set. 236*0b57cec5SDimitry Andric /// Returns true, if sanity check has been passed, and false if failed. 237*0b57cec5SDimitry Andric bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist); 238*0b57cec5SDimitry Andric #endif 239*0b57cec5SDimitry Andric 240*0b57cec5SDimitry Andric /// Insert a ComparableFunction into the FnTree, or merge it away if it's 241*0b57cec5SDimitry Andric /// equal to one that's already present. 242*0b57cec5SDimitry Andric bool insert(Function *NewFunction); 243*0b57cec5SDimitry Andric 244*0b57cec5SDimitry Andric /// Remove a Function from the FnTree and queue it up for a second sweep of 245*0b57cec5SDimitry Andric /// analysis. 246*0b57cec5SDimitry Andric void remove(Function *F); 247*0b57cec5SDimitry Andric 248*0b57cec5SDimitry Andric /// Find the functions that use this Value and remove them from FnTree and 249*0b57cec5SDimitry Andric /// queue the functions. 250*0b57cec5SDimitry Andric void removeUsers(Value *V); 251*0b57cec5SDimitry Andric 252*0b57cec5SDimitry Andric /// Replace all direct calls of Old with calls of New. Will bitcast New if 253*0b57cec5SDimitry Andric /// necessary to make types match. 254*0b57cec5SDimitry Andric void replaceDirectCallers(Function *Old, Function *New); 255*0b57cec5SDimitry Andric 256*0b57cec5SDimitry Andric /// Merge two equivalent functions. Upon completion, G may be deleted, or may 257*0b57cec5SDimitry Andric /// be converted into a thunk. In either case, it should never be visited 258*0b57cec5SDimitry Andric /// again. 259*0b57cec5SDimitry Andric void mergeTwoFunctions(Function *F, Function *G); 260*0b57cec5SDimitry Andric 261*0b57cec5SDimitry Andric /// Fill PDIUnrelatedWL with instructions from the entry block that are 262*0b57cec5SDimitry Andric /// unrelated to parameter related debug info. 263*0b57cec5SDimitry Andric void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock, 264*0b57cec5SDimitry Andric std::vector<Instruction *> &PDIUnrelatedWL); 265*0b57cec5SDimitry Andric 266*0b57cec5SDimitry Andric /// Erase the rest of the CFG (i.e. barring the entry block). 267*0b57cec5SDimitry Andric void eraseTail(Function *G); 268*0b57cec5SDimitry Andric 269*0b57cec5SDimitry Andric /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the 270*0b57cec5SDimitry Andric /// parameter debug info, from the entry block. 271*0b57cec5SDimitry Andric void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL); 272*0b57cec5SDimitry Andric 273*0b57cec5SDimitry Andric /// Replace G with a simple tail call to bitcast(F). Also (unless 274*0b57cec5SDimitry Andric /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F), 275*0b57cec5SDimitry Andric /// delete G. 276*0b57cec5SDimitry Andric void writeThunk(Function *F, Function *G); 277*0b57cec5SDimitry Andric 278*0b57cec5SDimitry Andric // Replace G with an alias to F (deleting function G) 279*0b57cec5SDimitry Andric void writeAlias(Function *F, Function *G); 280*0b57cec5SDimitry Andric 281*0b57cec5SDimitry Andric // Replace G with an alias to F if possible, or a thunk to F if possible. 282*0b57cec5SDimitry Andric // Returns false if neither is the case. 283*0b57cec5SDimitry Andric bool writeThunkOrAlias(Function *F, Function *G); 284*0b57cec5SDimitry Andric 285*0b57cec5SDimitry Andric /// Replace function F with function G in the function tree. 286*0b57cec5SDimitry Andric void replaceFunctionInTree(const FunctionNode &FN, Function *G); 287*0b57cec5SDimitry Andric 288*0b57cec5SDimitry Andric /// The set of all distinct functions. Use the insert() and remove() methods 289*0b57cec5SDimitry Andric /// to modify it. The map allows efficient lookup and deferring of Functions. 290*0b57cec5SDimitry Andric FnTreeType FnTree; 291*0b57cec5SDimitry Andric 292*0b57cec5SDimitry Andric // Map functions to the iterators of the FunctionNode which contains them 293*0b57cec5SDimitry Andric // in the FnTree. This must be updated carefully whenever the FnTree is 294*0b57cec5SDimitry Andric // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid 295*0b57cec5SDimitry Andric // dangling iterators into FnTree. The invariant that preserves this is that 296*0b57cec5SDimitry Andric // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree. 297*0b57cec5SDimitry Andric DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree; 298*0b57cec5SDimitry Andric }; 299*0b57cec5SDimitry Andric 300*0b57cec5SDimitry Andric } // end anonymous namespace 301*0b57cec5SDimitry Andric 302*0b57cec5SDimitry Andric char MergeFunctions::ID = 0; 303*0b57cec5SDimitry Andric 304*0b57cec5SDimitry Andric INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false) 305*0b57cec5SDimitry Andric 306*0b57cec5SDimitry Andric ModulePass *llvm::createMergeFunctionsPass() { 307*0b57cec5SDimitry Andric return new MergeFunctions(); 308*0b57cec5SDimitry Andric } 309*0b57cec5SDimitry Andric 310*0b57cec5SDimitry Andric #ifndef NDEBUG 311*0b57cec5SDimitry Andric bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) { 312*0b57cec5SDimitry Andric if (const unsigned Max = NumFunctionsForSanityCheck) { 313*0b57cec5SDimitry Andric unsigned TripleNumber = 0; 314*0b57cec5SDimitry Andric bool Valid = true; 315*0b57cec5SDimitry Andric 316*0b57cec5SDimitry Andric dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n"; 317*0b57cec5SDimitry Andric 318*0b57cec5SDimitry Andric unsigned i = 0; 319*0b57cec5SDimitry Andric for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(), 320*0b57cec5SDimitry Andric E = Worklist.end(); 321*0b57cec5SDimitry Andric I != E && i < Max; ++I, ++i) { 322*0b57cec5SDimitry Andric unsigned j = i; 323*0b57cec5SDimitry Andric for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max; 324*0b57cec5SDimitry Andric ++J, ++j) { 325*0b57cec5SDimitry Andric Function *F1 = cast<Function>(*I); 326*0b57cec5SDimitry Andric Function *F2 = cast<Function>(*J); 327*0b57cec5SDimitry Andric int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare(); 328*0b57cec5SDimitry Andric int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare(); 329*0b57cec5SDimitry Andric 330*0b57cec5SDimitry Andric // If F1 <= F2, then F2 >= F1, otherwise report failure. 331*0b57cec5SDimitry Andric if (Res1 != -Res2) { 332*0b57cec5SDimitry Andric dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber 333*0b57cec5SDimitry Andric << "\n"; 334*0b57cec5SDimitry Andric dbgs() << *F1 << '\n' << *F2 << '\n'; 335*0b57cec5SDimitry Andric Valid = false; 336*0b57cec5SDimitry Andric } 337*0b57cec5SDimitry Andric 338*0b57cec5SDimitry Andric if (Res1 == 0) 339*0b57cec5SDimitry Andric continue; 340*0b57cec5SDimitry Andric 341*0b57cec5SDimitry Andric unsigned k = j; 342*0b57cec5SDimitry Andric for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max; 343*0b57cec5SDimitry Andric ++k, ++K, ++TripleNumber) { 344*0b57cec5SDimitry Andric if (K == J) 345*0b57cec5SDimitry Andric continue; 346*0b57cec5SDimitry Andric 347*0b57cec5SDimitry Andric Function *F3 = cast<Function>(*K); 348*0b57cec5SDimitry Andric int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare(); 349*0b57cec5SDimitry Andric int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare(); 350*0b57cec5SDimitry Andric 351*0b57cec5SDimitry Andric bool Transitive = true; 352*0b57cec5SDimitry Andric 353*0b57cec5SDimitry Andric if (Res1 != 0 && Res1 == Res4) { 354*0b57cec5SDimitry Andric // F1 > F2, F2 > F3 => F1 > F3 355*0b57cec5SDimitry Andric Transitive = Res3 == Res1; 356*0b57cec5SDimitry Andric } else if (Res3 != 0 && Res3 == -Res4) { 357*0b57cec5SDimitry Andric // F1 > F3, F3 > F2 => F1 > F2 358*0b57cec5SDimitry Andric Transitive = Res3 == Res1; 359*0b57cec5SDimitry Andric } else if (Res4 != 0 && -Res3 == Res4) { 360*0b57cec5SDimitry Andric // F2 > F3, F3 > F1 => F2 > F1 361*0b57cec5SDimitry Andric Transitive = Res4 == -Res1; 362*0b57cec5SDimitry Andric } 363*0b57cec5SDimitry Andric 364*0b57cec5SDimitry Andric if (!Transitive) { 365*0b57cec5SDimitry Andric dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: " 366*0b57cec5SDimitry Andric << TripleNumber << "\n"; 367*0b57cec5SDimitry Andric dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", " 368*0b57cec5SDimitry Andric << Res4 << "\n"; 369*0b57cec5SDimitry Andric dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n'; 370*0b57cec5SDimitry Andric Valid = false; 371*0b57cec5SDimitry Andric } 372*0b57cec5SDimitry Andric } 373*0b57cec5SDimitry Andric } 374*0b57cec5SDimitry Andric } 375*0b57cec5SDimitry Andric 376*0b57cec5SDimitry Andric dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n"; 377*0b57cec5SDimitry Andric return Valid; 378*0b57cec5SDimitry Andric } 379*0b57cec5SDimitry Andric return true; 380*0b57cec5SDimitry Andric } 381*0b57cec5SDimitry Andric #endif 382*0b57cec5SDimitry Andric 383*0b57cec5SDimitry Andric /// Check whether \p F is eligible for function merging. 384*0b57cec5SDimitry Andric static bool isEligibleForMerging(Function &F) { 385*0b57cec5SDimitry Andric return !F.isDeclaration() && !F.hasAvailableExternallyLinkage(); 386*0b57cec5SDimitry Andric } 387*0b57cec5SDimitry Andric 388*0b57cec5SDimitry Andric bool MergeFunctions::runOnModule(Module &M) { 389*0b57cec5SDimitry Andric if (skipModule(M)) 390*0b57cec5SDimitry Andric return false; 391*0b57cec5SDimitry Andric 392*0b57cec5SDimitry Andric bool Changed = false; 393*0b57cec5SDimitry Andric 394*0b57cec5SDimitry Andric // All functions in the module, ordered by hash. Functions with a unique 395*0b57cec5SDimitry Andric // hash value are easily eliminated. 396*0b57cec5SDimitry Andric std::vector<std::pair<FunctionComparator::FunctionHash, Function *>> 397*0b57cec5SDimitry Andric HashedFuncs; 398*0b57cec5SDimitry Andric for (Function &Func : M) { 399*0b57cec5SDimitry Andric if (isEligibleForMerging(Func)) { 400*0b57cec5SDimitry Andric HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func}); 401*0b57cec5SDimitry Andric } 402*0b57cec5SDimitry Andric } 403*0b57cec5SDimitry Andric 404*0b57cec5SDimitry Andric llvm::stable_sort(HashedFuncs, less_first()); 405*0b57cec5SDimitry Andric 406*0b57cec5SDimitry Andric auto S = HashedFuncs.begin(); 407*0b57cec5SDimitry Andric for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) { 408*0b57cec5SDimitry Andric // If the hash value matches the previous value or the next one, we must 409*0b57cec5SDimitry Andric // consider merging it. Otherwise it is dropped and never considered again. 410*0b57cec5SDimitry Andric if ((I != S && std::prev(I)->first == I->first) || 411*0b57cec5SDimitry Andric (std::next(I) != IE && std::next(I)->first == I->first) ) { 412*0b57cec5SDimitry Andric Deferred.push_back(WeakTrackingVH(I->second)); 413*0b57cec5SDimitry Andric } 414*0b57cec5SDimitry Andric } 415*0b57cec5SDimitry Andric 416*0b57cec5SDimitry Andric do { 417*0b57cec5SDimitry Andric std::vector<WeakTrackingVH> Worklist; 418*0b57cec5SDimitry Andric Deferred.swap(Worklist); 419*0b57cec5SDimitry Andric 420*0b57cec5SDimitry Andric LLVM_DEBUG(doSanityCheck(Worklist)); 421*0b57cec5SDimitry Andric 422*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n'); 423*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n'); 424*0b57cec5SDimitry Andric 425*0b57cec5SDimitry Andric // Insert functions and merge them. 426*0b57cec5SDimitry Andric for (WeakTrackingVH &I : Worklist) { 427*0b57cec5SDimitry Andric if (!I) 428*0b57cec5SDimitry Andric continue; 429*0b57cec5SDimitry Andric Function *F = cast<Function>(I); 430*0b57cec5SDimitry Andric if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) { 431*0b57cec5SDimitry Andric Changed |= insert(F); 432*0b57cec5SDimitry Andric } 433*0b57cec5SDimitry Andric } 434*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n'); 435*0b57cec5SDimitry Andric } while (!Deferred.empty()); 436*0b57cec5SDimitry Andric 437*0b57cec5SDimitry Andric FnTree.clear(); 438*0b57cec5SDimitry Andric FNodesInTree.clear(); 439*0b57cec5SDimitry Andric GlobalNumbers.clear(); 440*0b57cec5SDimitry Andric 441*0b57cec5SDimitry Andric return Changed; 442*0b57cec5SDimitry Andric } 443*0b57cec5SDimitry Andric 444*0b57cec5SDimitry Andric // Replace direct callers of Old with New. 445*0b57cec5SDimitry Andric void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) { 446*0b57cec5SDimitry Andric Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType()); 447*0b57cec5SDimitry Andric for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) { 448*0b57cec5SDimitry Andric Use *U = &*UI; 449*0b57cec5SDimitry Andric ++UI; 450*0b57cec5SDimitry Andric CallSite CS(U->getUser()); 451*0b57cec5SDimitry Andric if (CS && CS.isCallee(U)) { 452*0b57cec5SDimitry Andric // Transfer the called function's attributes to the call site. Due to the 453*0b57cec5SDimitry Andric // bitcast we will 'lose' ABI changing attributes because the 'called 454*0b57cec5SDimitry Andric // function' is no longer a Function* but the bitcast. Code that looks up 455*0b57cec5SDimitry Andric // the attributes from the called function will fail. 456*0b57cec5SDimitry Andric 457*0b57cec5SDimitry Andric // FIXME: This is not actually true, at least not anymore. The callsite 458*0b57cec5SDimitry Andric // will always have the same ABI affecting attributes as the callee, 459*0b57cec5SDimitry Andric // because otherwise the original input has UB. Note that Old and New 460*0b57cec5SDimitry Andric // always have matching ABI, so no attributes need to be changed. 461*0b57cec5SDimitry Andric // Transferring other attributes may help other optimizations, but that 462*0b57cec5SDimitry Andric // should be done uniformly and not in this ad-hoc way. 463*0b57cec5SDimitry Andric auto &Context = New->getContext(); 464*0b57cec5SDimitry Andric auto NewPAL = New->getAttributes(); 465*0b57cec5SDimitry Andric SmallVector<AttributeSet, 4> NewArgAttrs; 466*0b57cec5SDimitry Andric for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) 467*0b57cec5SDimitry Andric NewArgAttrs.push_back(NewPAL.getParamAttributes(argIdx)); 468*0b57cec5SDimitry Andric // Don't transfer attributes from the function to the callee. Function 469*0b57cec5SDimitry Andric // attributes typically aren't relevant to the calling convention or ABI. 470*0b57cec5SDimitry Andric CS.setAttributes(AttributeList::get(Context, /*FnAttrs=*/AttributeSet(), 471*0b57cec5SDimitry Andric NewPAL.getRetAttributes(), 472*0b57cec5SDimitry Andric NewArgAttrs)); 473*0b57cec5SDimitry Andric 474*0b57cec5SDimitry Andric remove(CS.getInstruction()->getFunction()); 475*0b57cec5SDimitry Andric U->set(BitcastNew); 476*0b57cec5SDimitry Andric } 477*0b57cec5SDimitry Andric } 478*0b57cec5SDimitry Andric } 479*0b57cec5SDimitry Andric 480*0b57cec5SDimitry Andric // Helper for writeThunk, 481*0b57cec5SDimitry Andric // Selects proper bitcast operation, 482*0b57cec5SDimitry Andric // but a bit simpler then CastInst::getCastOpcode. 483*0b57cec5SDimitry Andric static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) { 484*0b57cec5SDimitry Andric Type *SrcTy = V->getType(); 485*0b57cec5SDimitry Andric if (SrcTy->isStructTy()) { 486*0b57cec5SDimitry Andric assert(DestTy->isStructTy()); 487*0b57cec5SDimitry Andric assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements()); 488*0b57cec5SDimitry Andric Value *Result = UndefValue::get(DestTy); 489*0b57cec5SDimitry Andric for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) { 490*0b57cec5SDimitry Andric Value *Element = createCast( 491*0b57cec5SDimitry Andric Builder, Builder.CreateExtractValue(V, makeArrayRef(I)), 492*0b57cec5SDimitry Andric DestTy->getStructElementType(I)); 493*0b57cec5SDimitry Andric 494*0b57cec5SDimitry Andric Result = 495*0b57cec5SDimitry Andric Builder.CreateInsertValue(Result, Element, makeArrayRef(I)); 496*0b57cec5SDimitry Andric } 497*0b57cec5SDimitry Andric return Result; 498*0b57cec5SDimitry Andric } 499*0b57cec5SDimitry Andric assert(!DestTy->isStructTy()); 500*0b57cec5SDimitry Andric if (SrcTy->isIntegerTy() && DestTy->isPointerTy()) 501*0b57cec5SDimitry Andric return Builder.CreateIntToPtr(V, DestTy); 502*0b57cec5SDimitry Andric else if (SrcTy->isPointerTy() && DestTy->isIntegerTy()) 503*0b57cec5SDimitry Andric return Builder.CreatePtrToInt(V, DestTy); 504*0b57cec5SDimitry Andric else 505*0b57cec5SDimitry Andric return Builder.CreateBitCast(V, DestTy); 506*0b57cec5SDimitry Andric } 507*0b57cec5SDimitry Andric 508*0b57cec5SDimitry Andric // Erase the instructions in PDIUnrelatedWL as they are unrelated to the 509*0b57cec5SDimitry Andric // parameter debug info, from the entry block. 510*0b57cec5SDimitry Andric void MergeFunctions::eraseInstsUnrelatedToPDI( 511*0b57cec5SDimitry Andric std::vector<Instruction *> &PDIUnrelatedWL) { 512*0b57cec5SDimitry Andric LLVM_DEBUG( 513*0b57cec5SDimitry Andric dbgs() << " Erasing instructions (in reverse order of appearance in " 514*0b57cec5SDimitry Andric "entry block) unrelated to parameter debug info from entry " 515*0b57cec5SDimitry Andric "block: {\n"); 516*0b57cec5SDimitry Andric while (!PDIUnrelatedWL.empty()) { 517*0b57cec5SDimitry Andric Instruction *I = PDIUnrelatedWL.back(); 518*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Deleting Instruction: "); 519*0b57cec5SDimitry Andric LLVM_DEBUG(I->print(dbgs())); 520*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 521*0b57cec5SDimitry Andric I->eraseFromParent(); 522*0b57cec5SDimitry Andric PDIUnrelatedWL.pop_back(); 523*0b57cec5SDimitry Andric } 524*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter " 525*0b57cec5SDimitry Andric "debug info from entry block. \n"); 526*0b57cec5SDimitry Andric } 527*0b57cec5SDimitry Andric 528*0b57cec5SDimitry Andric // Reduce G to its entry block. 529*0b57cec5SDimitry Andric void MergeFunctions::eraseTail(Function *G) { 530*0b57cec5SDimitry Andric std::vector<BasicBlock *> WorklistBB; 531*0b57cec5SDimitry Andric for (Function::iterator BBI = std::next(G->begin()), BBE = G->end(); 532*0b57cec5SDimitry Andric BBI != BBE; ++BBI) { 533*0b57cec5SDimitry Andric BBI->dropAllReferences(); 534*0b57cec5SDimitry Andric WorklistBB.push_back(&*BBI); 535*0b57cec5SDimitry Andric } 536*0b57cec5SDimitry Andric while (!WorklistBB.empty()) { 537*0b57cec5SDimitry Andric BasicBlock *BB = WorklistBB.back(); 538*0b57cec5SDimitry Andric BB->eraseFromParent(); 539*0b57cec5SDimitry Andric WorklistBB.pop_back(); 540*0b57cec5SDimitry Andric } 541*0b57cec5SDimitry Andric } 542*0b57cec5SDimitry Andric 543*0b57cec5SDimitry Andric // We are interested in the following instructions from the entry block as being 544*0b57cec5SDimitry Andric // related to parameter debug info: 545*0b57cec5SDimitry Andric // - @llvm.dbg.declare 546*0b57cec5SDimitry Andric // - stores from the incoming parameters to locations on the stack-frame 547*0b57cec5SDimitry Andric // - allocas that create these locations on the stack-frame 548*0b57cec5SDimitry Andric // - @llvm.dbg.value 549*0b57cec5SDimitry Andric // - the entry block's terminator 550*0b57cec5SDimitry Andric // The rest are unrelated to debug info for the parameters; fill up 551*0b57cec5SDimitry Andric // PDIUnrelatedWL with such instructions. 552*0b57cec5SDimitry Andric void MergeFunctions::filterInstsUnrelatedToPDI( 553*0b57cec5SDimitry Andric BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) { 554*0b57cec5SDimitry Andric std::set<Instruction *> PDIRelated; 555*0b57cec5SDimitry Andric for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end(); 556*0b57cec5SDimitry Andric BI != BIE; ++BI) { 557*0b57cec5SDimitry Andric if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) { 558*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Deciding: "); 559*0b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs())); 560*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 561*0b57cec5SDimitry Andric DILocalVariable *DILocVar = DVI->getVariable(); 562*0b57cec5SDimitry Andric if (DILocVar->isParameter()) { 563*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Include (parameter): "); 564*0b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs())); 565*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 566*0b57cec5SDimitry Andric PDIRelated.insert(&*BI); 567*0b57cec5SDimitry Andric } else { 568*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Delete (!parameter): "); 569*0b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs())); 570*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 571*0b57cec5SDimitry Andric } 572*0b57cec5SDimitry Andric } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) { 573*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Deciding: "); 574*0b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs())); 575*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 576*0b57cec5SDimitry Andric DILocalVariable *DILocVar = DDI->getVariable(); 577*0b57cec5SDimitry Andric if (DILocVar->isParameter()) { 578*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Parameter: "); 579*0b57cec5SDimitry Andric LLVM_DEBUG(DILocVar->print(dbgs())); 580*0b57cec5SDimitry Andric AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress()); 581*0b57cec5SDimitry Andric if (AI) { 582*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Processing alloca users: "); 583*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 584*0b57cec5SDimitry Andric for (User *U : AI->users()) { 585*0b57cec5SDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 586*0b57cec5SDimitry Andric if (Value *Arg = SI->getValueOperand()) { 587*0b57cec5SDimitry Andric if (dyn_cast<Argument>(Arg)) { 588*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Include: "); 589*0b57cec5SDimitry Andric LLVM_DEBUG(AI->print(dbgs())); 590*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 591*0b57cec5SDimitry Andric PDIRelated.insert(AI); 592*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Include (parameter): "); 593*0b57cec5SDimitry Andric LLVM_DEBUG(SI->print(dbgs())); 594*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 595*0b57cec5SDimitry Andric PDIRelated.insert(SI); 596*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Include: "); 597*0b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs())); 598*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 599*0b57cec5SDimitry Andric PDIRelated.insert(&*BI); 600*0b57cec5SDimitry Andric } else { 601*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Delete (!parameter): "); 602*0b57cec5SDimitry Andric LLVM_DEBUG(SI->print(dbgs())); 603*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 604*0b57cec5SDimitry Andric } 605*0b57cec5SDimitry Andric } 606*0b57cec5SDimitry Andric } else { 607*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Defer: "); 608*0b57cec5SDimitry Andric LLVM_DEBUG(U->print(dbgs())); 609*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 610*0b57cec5SDimitry Andric } 611*0b57cec5SDimitry Andric } 612*0b57cec5SDimitry Andric } else { 613*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Delete (alloca NULL): "); 614*0b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs())); 615*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 616*0b57cec5SDimitry Andric } 617*0b57cec5SDimitry Andric } else { 618*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Delete (!parameter): "); 619*0b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs())); 620*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 621*0b57cec5SDimitry Andric } 622*0b57cec5SDimitry Andric } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) { 623*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Will Include Terminator: "); 624*0b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs())); 625*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 626*0b57cec5SDimitry Andric PDIRelated.insert(&*BI); 627*0b57cec5SDimitry Andric } else { 628*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Defer: "); 629*0b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs())); 630*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 631*0b57cec5SDimitry Andric } 632*0b57cec5SDimitry Andric } 633*0b57cec5SDimitry Andric LLVM_DEBUG( 634*0b57cec5SDimitry Andric dbgs() 635*0b57cec5SDimitry Andric << " Report parameter debug info related/related instructions: {\n"); 636*0b57cec5SDimitry Andric for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end(); 637*0b57cec5SDimitry Andric BI != BE; ++BI) { 638*0b57cec5SDimitry Andric 639*0b57cec5SDimitry Andric Instruction *I = &*BI; 640*0b57cec5SDimitry Andric if (PDIRelated.find(I) == PDIRelated.end()) { 641*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " !PDIRelated: "); 642*0b57cec5SDimitry Andric LLVM_DEBUG(I->print(dbgs())); 643*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 644*0b57cec5SDimitry Andric PDIUnrelatedWL.push_back(I); 645*0b57cec5SDimitry Andric } else { 646*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " PDIRelated: "); 647*0b57cec5SDimitry Andric LLVM_DEBUG(I->print(dbgs())); 648*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 649*0b57cec5SDimitry Andric } 650*0b57cec5SDimitry Andric } 651*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " }\n"); 652*0b57cec5SDimitry Andric } 653*0b57cec5SDimitry Andric 654*0b57cec5SDimitry Andric /// Whether this function may be replaced by a forwarding thunk. 655*0b57cec5SDimitry Andric static bool canCreateThunkFor(Function *F) { 656*0b57cec5SDimitry Andric if (F->isVarArg()) 657*0b57cec5SDimitry Andric return false; 658*0b57cec5SDimitry Andric 659*0b57cec5SDimitry Andric // Don't merge tiny functions using a thunk, since it can just end up 660*0b57cec5SDimitry Andric // making the function larger. 661*0b57cec5SDimitry Andric if (F->size() == 1) { 662*0b57cec5SDimitry Andric if (F->front().size() <= 2) { 663*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName() 664*0b57cec5SDimitry Andric << " is too small to bother creating a thunk for\n"); 665*0b57cec5SDimitry Andric return false; 666*0b57cec5SDimitry Andric } 667*0b57cec5SDimitry Andric } 668*0b57cec5SDimitry Andric return true; 669*0b57cec5SDimitry Andric } 670*0b57cec5SDimitry Andric 671*0b57cec5SDimitry Andric // Replace G with a simple tail call to bitcast(F). Also (unless 672*0b57cec5SDimitry Andric // MergeFunctionsPDI holds) replace direct uses of G with bitcast(F), 673*0b57cec5SDimitry Andric // delete G. Under MergeFunctionsPDI, we use G itself for creating 674*0b57cec5SDimitry Andric // the thunk as we preserve the debug info (and associated instructions) 675*0b57cec5SDimitry Andric // from G's entry block pertaining to G's incoming arguments which are 676*0b57cec5SDimitry Andric // passed on as corresponding arguments in the call that G makes to F. 677*0b57cec5SDimitry Andric // For better debugability, under MergeFunctionsPDI, we do not modify G's 678*0b57cec5SDimitry Andric // call sites to point to F even when within the same translation unit. 679*0b57cec5SDimitry Andric void MergeFunctions::writeThunk(Function *F, Function *G) { 680*0b57cec5SDimitry Andric BasicBlock *GEntryBlock = nullptr; 681*0b57cec5SDimitry Andric std::vector<Instruction *> PDIUnrelatedWL; 682*0b57cec5SDimitry Andric BasicBlock *BB = nullptr; 683*0b57cec5SDimitry Andric Function *NewG = nullptr; 684*0b57cec5SDimitry Andric if (MergeFunctionsPDI) { 685*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new " 686*0b57cec5SDimitry Andric "function as thunk; retain original: " 687*0b57cec5SDimitry Andric << G->getName() << "()\n"); 688*0b57cec5SDimitry Andric GEntryBlock = &G->getEntryBlock(); 689*0b57cec5SDimitry Andric LLVM_DEBUG( 690*0b57cec5SDimitry Andric dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related " 691*0b57cec5SDimitry Andric "debug info for " 692*0b57cec5SDimitry Andric << G->getName() << "() {\n"); 693*0b57cec5SDimitry Andric filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL); 694*0b57cec5SDimitry Andric GEntryBlock->getTerminator()->eraseFromParent(); 695*0b57cec5SDimitry Andric BB = GEntryBlock; 696*0b57cec5SDimitry Andric } else { 697*0b57cec5SDimitry Andric NewG = Function::Create(G->getFunctionType(), G->getLinkage(), 698*0b57cec5SDimitry Andric G->getAddressSpace(), "", G->getParent()); 699*0b57cec5SDimitry Andric NewG->setComdat(G->getComdat()); 700*0b57cec5SDimitry Andric BB = BasicBlock::Create(F->getContext(), "", NewG); 701*0b57cec5SDimitry Andric } 702*0b57cec5SDimitry Andric 703*0b57cec5SDimitry Andric IRBuilder<> Builder(BB); 704*0b57cec5SDimitry Andric Function *H = MergeFunctionsPDI ? G : NewG; 705*0b57cec5SDimitry Andric SmallVector<Value *, 16> Args; 706*0b57cec5SDimitry Andric unsigned i = 0; 707*0b57cec5SDimitry Andric FunctionType *FFTy = F->getFunctionType(); 708*0b57cec5SDimitry Andric for (Argument &AI : H->args()) { 709*0b57cec5SDimitry Andric Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i))); 710*0b57cec5SDimitry Andric ++i; 711*0b57cec5SDimitry Andric } 712*0b57cec5SDimitry Andric 713*0b57cec5SDimitry Andric CallInst *CI = Builder.CreateCall(F, Args); 714*0b57cec5SDimitry Andric ReturnInst *RI = nullptr; 715*0b57cec5SDimitry Andric CI->setTailCall(); 716*0b57cec5SDimitry Andric CI->setCallingConv(F->getCallingConv()); 717*0b57cec5SDimitry Andric CI->setAttributes(F->getAttributes()); 718*0b57cec5SDimitry Andric if (H->getReturnType()->isVoidTy()) { 719*0b57cec5SDimitry Andric RI = Builder.CreateRetVoid(); 720*0b57cec5SDimitry Andric } else { 721*0b57cec5SDimitry Andric RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType())); 722*0b57cec5SDimitry Andric } 723*0b57cec5SDimitry Andric 724*0b57cec5SDimitry Andric if (MergeFunctionsPDI) { 725*0b57cec5SDimitry Andric DISubprogram *DIS = G->getSubprogram(); 726*0b57cec5SDimitry Andric if (DIS) { 727*0b57cec5SDimitry Andric DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS); 728*0b57cec5SDimitry Andric DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS); 729*0b57cec5SDimitry Andric CI->setDebugLoc(CIDbgLoc); 730*0b57cec5SDimitry Andric RI->setDebugLoc(RIDbgLoc); 731*0b57cec5SDimitry Andric } else { 732*0b57cec5SDimitry Andric LLVM_DEBUG( 733*0b57cec5SDimitry Andric dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for " 734*0b57cec5SDimitry Andric << G->getName() << "()\n"); 735*0b57cec5SDimitry Andric } 736*0b57cec5SDimitry Andric eraseTail(G); 737*0b57cec5SDimitry Andric eraseInstsUnrelatedToPDI(PDIUnrelatedWL); 738*0b57cec5SDimitry Andric LLVM_DEBUG( 739*0b57cec5SDimitry Andric dbgs() << "} // End of parameter related debug info filtering for: " 740*0b57cec5SDimitry Andric << G->getName() << "()\n"); 741*0b57cec5SDimitry Andric } else { 742*0b57cec5SDimitry Andric NewG->copyAttributesFrom(G); 743*0b57cec5SDimitry Andric NewG->takeName(G); 744*0b57cec5SDimitry Andric removeUsers(G); 745*0b57cec5SDimitry Andric G->replaceAllUsesWith(NewG); 746*0b57cec5SDimitry Andric G->eraseFromParent(); 747*0b57cec5SDimitry Andric } 748*0b57cec5SDimitry Andric 749*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n'); 750*0b57cec5SDimitry Andric ++NumThunksWritten; 751*0b57cec5SDimitry Andric } 752*0b57cec5SDimitry Andric 753*0b57cec5SDimitry Andric // Whether this function may be replaced by an alias 754*0b57cec5SDimitry Andric static bool canCreateAliasFor(Function *F) { 755*0b57cec5SDimitry Andric if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr()) 756*0b57cec5SDimitry Andric return false; 757*0b57cec5SDimitry Andric 758*0b57cec5SDimitry Andric // We should only see linkages supported by aliases here 759*0b57cec5SDimitry Andric assert(F->hasLocalLinkage() || F->hasExternalLinkage() 760*0b57cec5SDimitry Andric || F->hasWeakLinkage() || F->hasLinkOnceLinkage()); 761*0b57cec5SDimitry Andric return true; 762*0b57cec5SDimitry Andric } 763*0b57cec5SDimitry Andric 764*0b57cec5SDimitry Andric // Replace G with an alias to F (deleting function G) 765*0b57cec5SDimitry Andric void MergeFunctions::writeAlias(Function *F, Function *G) { 766*0b57cec5SDimitry Andric Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType()); 767*0b57cec5SDimitry Andric PointerType *PtrType = G->getType(); 768*0b57cec5SDimitry Andric auto *GA = GlobalAlias::create( 769*0b57cec5SDimitry Andric PtrType->getElementType(), PtrType->getAddressSpace(), 770*0b57cec5SDimitry Andric G->getLinkage(), "", BitcastF, G->getParent()); 771*0b57cec5SDimitry Andric 772*0b57cec5SDimitry Andric F->setAlignment(std::max(F->getAlignment(), G->getAlignment())); 773*0b57cec5SDimitry Andric GA->takeName(G); 774*0b57cec5SDimitry Andric GA->setVisibility(G->getVisibility()); 775*0b57cec5SDimitry Andric GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 776*0b57cec5SDimitry Andric 777*0b57cec5SDimitry Andric removeUsers(G); 778*0b57cec5SDimitry Andric G->replaceAllUsesWith(GA); 779*0b57cec5SDimitry Andric G->eraseFromParent(); 780*0b57cec5SDimitry Andric 781*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n'); 782*0b57cec5SDimitry Andric ++NumAliasesWritten; 783*0b57cec5SDimitry Andric } 784*0b57cec5SDimitry Andric 785*0b57cec5SDimitry Andric // Replace G with an alias to F if possible, or a thunk to F if 786*0b57cec5SDimitry Andric // profitable. Returns false if neither is the case. 787*0b57cec5SDimitry Andric bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) { 788*0b57cec5SDimitry Andric if (canCreateAliasFor(G)) { 789*0b57cec5SDimitry Andric writeAlias(F, G); 790*0b57cec5SDimitry Andric return true; 791*0b57cec5SDimitry Andric } 792*0b57cec5SDimitry Andric if (canCreateThunkFor(F)) { 793*0b57cec5SDimitry Andric writeThunk(F, G); 794*0b57cec5SDimitry Andric return true; 795*0b57cec5SDimitry Andric } 796*0b57cec5SDimitry Andric return false; 797*0b57cec5SDimitry Andric } 798*0b57cec5SDimitry Andric 799*0b57cec5SDimitry Andric // Merge two equivalent functions. Upon completion, Function G is deleted. 800*0b57cec5SDimitry Andric void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) { 801*0b57cec5SDimitry Andric if (F->isInterposable()) { 802*0b57cec5SDimitry Andric assert(G->isInterposable()); 803*0b57cec5SDimitry Andric 804*0b57cec5SDimitry Andric // Both writeThunkOrAlias() calls below must succeed, either because we can 805*0b57cec5SDimitry Andric // create aliases for G and NewF, or because a thunk for F is profitable. 806*0b57cec5SDimitry Andric // F here has the same signature as NewF below, so that's what we check. 807*0b57cec5SDimitry Andric if (!canCreateThunkFor(F) && 808*0b57cec5SDimitry Andric (!canCreateAliasFor(F) || !canCreateAliasFor(G))) 809*0b57cec5SDimitry Andric return; 810*0b57cec5SDimitry Andric 811*0b57cec5SDimitry Andric // Make them both thunks to the same internal function. 812*0b57cec5SDimitry Andric Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(), 813*0b57cec5SDimitry Andric F->getAddressSpace(), "", F->getParent()); 814*0b57cec5SDimitry Andric NewF->copyAttributesFrom(F); 815*0b57cec5SDimitry Andric NewF->takeName(F); 816*0b57cec5SDimitry Andric removeUsers(F); 817*0b57cec5SDimitry Andric F->replaceAllUsesWith(NewF); 818*0b57cec5SDimitry Andric 819*0b57cec5SDimitry Andric unsigned MaxAlignment = std::max(G->getAlignment(), NewF->getAlignment()); 820*0b57cec5SDimitry Andric 821*0b57cec5SDimitry Andric writeThunkOrAlias(F, G); 822*0b57cec5SDimitry Andric writeThunkOrAlias(F, NewF); 823*0b57cec5SDimitry Andric 824*0b57cec5SDimitry Andric F->setAlignment(MaxAlignment); 825*0b57cec5SDimitry Andric F->setLinkage(GlobalValue::PrivateLinkage); 826*0b57cec5SDimitry Andric ++NumDoubleWeak; 827*0b57cec5SDimitry Andric ++NumFunctionsMerged; 828*0b57cec5SDimitry Andric } else { 829*0b57cec5SDimitry Andric // For better debugability, under MergeFunctionsPDI, we do not modify G's 830*0b57cec5SDimitry Andric // call sites to point to F even when within the same translation unit. 831*0b57cec5SDimitry Andric if (!G->isInterposable() && !MergeFunctionsPDI) { 832*0b57cec5SDimitry Andric if (G->hasGlobalUnnamedAddr()) { 833*0b57cec5SDimitry Andric // G might have been a key in our GlobalNumberState, and it's illegal 834*0b57cec5SDimitry Andric // to replace a key in ValueMap<GlobalValue *> with a non-global. 835*0b57cec5SDimitry Andric GlobalNumbers.erase(G); 836*0b57cec5SDimitry Andric // If G's address is not significant, replace it entirely. 837*0b57cec5SDimitry Andric Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType()); 838*0b57cec5SDimitry Andric removeUsers(G); 839*0b57cec5SDimitry Andric G->replaceAllUsesWith(BitcastF); 840*0b57cec5SDimitry Andric } else { 841*0b57cec5SDimitry Andric // Redirect direct callers of G to F. (See note on MergeFunctionsPDI 842*0b57cec5SDimitry Andric // above). 843*0b57cec5SDimitry Andric replaceDirectCallers(G, F); 844*0b57cec5SDimitry Andric } 845*0b57cec5SDimitry Andric } 846*0b57cec5SDimitry Andric 847*0b57cec5SDimitry Andric // If G was internal then we may have replaced all uses of G with F. If so, 848*0b57cec5SDimitry Andric // stop here and delete G. There's no need for a thunk. (See note on 849*0b57cec5SDimitry Andric // MergeFunctionsPDI above). 850*0b57cec5SDimitry Andric if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) { 851*0b57cec5SDimitry Andric G->eraseFromParent(); 852*0b57cec5SDimitry Andric ++NumFunctionsMerged; 853*0b57cec5SDimitry Andric return; 854*0b57cec5SDimitry Andric } 855*0b57cec5SDimitry Andric 856*0b57cec5SDimitry Andric if (writeThunkOrAlias(F, G)) { 857*0b57cec5SDimitry Andric ++NumFunctionsMerged; 858*0b57cec5SDimitry Andric } 859*0b57cec5SDimitry Andric } 860*0b57cec5SDimitry Andric } 861*0b57cec5SDimitry Andric 862*0b57cec5SDimitry Andric /// Replace function F by function G. 863*0b57cec5SDimitry Andric void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN, 864*0b57cec5SDimitry Andric Function *G) { 865*0b57cec5SDimitry Andric Function *F = FN.getFunc(); 866*0b57cec5SDimitry Andric assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 && 867*0b57cec5SDimitry Andric "The two functions must be equal"); 868*0b57cec5SDimitry Andric 869*0b57cec5SDimitry Andric auto I = FNodesInTree.find(F); 870*0b57cec5SDimitry Andric assert(I != FNodesInTree.end() && "F should be in FNodesInTree"); 871*0b57cec5SDimitry Andric assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G"); 872*0b57cec5SDimitry Andric 873*0b57cec5SDimitry Andric FnTreeType::iterator IterToFNInFnTree = I->second; 874*0b57cec5SDimitry Andric assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree."); 875*0b57cec5SDimitry Andric // Remove F -> FN and insert G -> FN 876*0b57cec5SDimitry Andric FNodesInTree.erase(I); 877*0b57cec5SDimitry Andric FNodesInTree.insert({G, IterToFNInFnTree}); 878*0b57cec5SDimitry Andric // Replace F with G in FN, which is stored inside the FnTree. 879*0b57cec5SDimitry Andric FN.replaceBy(G); 880*0b57cec5SDimitry Andric } 881*0b57cec5SDimitry Andric 882*0b57cec5SDimitry Andric // Ordering for functions that are equal under FunctionComparator 883*0b57cec5SDimitry Andric static bool isFuncOrderCorrect(const Function *F, const Function *G) { 884*0b57cec5SDimitry Andric if (F->isInterposable() != G->isInterposable()) { 885*0b57cec5SDimitry Andric // Strong before weak, because the weak function may call the strong 886*0b57cec5SDimitry Andric // one, but not the other way around. 887*0b57cec5SDimitry Andric return !F->isInterposable(); 888*0b57cec5SDimitry Andric } 889*0b57cec5SDimitry Andric if (F->hasLocalLinkage() != G->hasLocalLinkage()) { 890*0b57cec5SDimitry Andric // External before local, because we definitely have to keep the external 891*0b57cec5SDimitry Andric // function, but may be able to drop the local one. 892*0b57cec5SDimitry Andric return !F->hasLocalLinkage(); 893*0b57cec5SDimitry Andric } 894*0b57cec5SDimitry Andric // Impose a total order (by name) on the replacement of functions. This is 895*0b57cec5SDimitry Andric // important when operating on more than one module independently to prevent 896*0b57cec5SDimitry Andric // cycles of thunks calling each other when the modules are linked together. 897*0b57cec5SDimitry Andric return F->getName() <= G->getName(); 898*0b57cec5SDimitry Andric } 899*0b57cec5SDimitry Andric 900*0b57cec5SDimitry Andric // Insert a ComparableFunction into the FnTree, or merge it away if equal to one 901*0b57cec5SDimitry Andric // that was already inserted. 902*0b57cec5SDimitry Andric bool MergeFunctions::insert(Function *NewFunction) { 903*0b57cec5SDimitry Andric std::pair<FnTreeType::iterator, bool> Result = 904*0b57cec5SDimitry Andric FnTree.insert(FunctionNode(NewFunction)); 905*0b57cec5SDimitry Andric 906*0b57cec5SDimitry Andric if (Result.second) { 907*0b57cec5SDimitry Andric assert(FNodesInTree.count(NewFunction) == 0); 908*0b57cec5SDimitry Andric FNodesInTree.insert({NewFunction, Result.first}); 909*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() 910*0b57cec5SDimitry Andric << '\n'); 911*0b57cec5SDimitry Andric return false; 912*0b57cec5SDimitry Andric } 913*0b57cec5SDimitry Andric 914*0b57cec5SDimitry Andric const FunctionNode &OldF = *Result.first; 915*0b57cec5SDimitry Andric 916*0b57cec5SDimitry Andric if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) { 917*0b57cec5SDimitry Andric // Swap the two functions. 918*0b57cec5SDimitry Andric Function *F = OldF.getFunc(); 919*0b57cec5SDimitry Andric replaceFunctionInTree(*Result.first, NewFunction); 920*0b57cec5SDimitry Andric NewFunction = F; 921*0b57cec5SDimitry Andric assert(OldF.getFunc() != F && "Must have swapped the functions."); 922*0b57cec5SDimitry Andric } 923*0b57cec5SDimitry Andric 924*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName() 925*0b57cec5SDimitry Andric << " == " << NewFunction->getName() << '\n'); 926*0b57cec5SDimitry Andric 927*0b57cec5SDimitry Andric Function *DeleteF = NewFunction; 928*0b57cec5SDimitry Andric mergeTwoFunctions(OldF.getFunc(), DeleteF); 929*0b57cec5SDimitry Andric return true; 930*0b57cec5SDimitry Andric } 931*0b57cec5SDimitry Andric 932*0b57cec5SDimitry Andric // Remove a function from FnTree. If it was already in FnTree, add 933*0b57cec5SDimitry Andric // it to Deferred so that we'll look at it in the next round. 934*0b57cec5SDimitry Andric void MergeFunctions::remove(Function *F) { 935*0b57cec5SDimitry Andric auto I = FNodesInTree.find(F); 936*0b57cec5SDimitry Andric if (I != FNodesInTree.end()) { 937*0b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n"); 938*0b57cec5SDimitry Andric FnTree.erase(I->second); 939*0b57cec5SDimitry Andric // I->second has been invalidated, remove it from the FNodesInTree map to 940*0b57cec5SDimitry Andric // preserve the invariant. 941*0b57cec5SDimitry Andric FNodesInTree.erase(I); 942*0b57cec5SDimitry Andric Deferred.emplace_back(F); 943*0b57cec5SDimitry Andric } 944*0b57cec5SDimitry Andric } 945*0b57cec5SDimitry Andric 946*0b57cec5SDimitry Andric // For each instruction used by the value, remove() the function that contains 947*0b57cec5SDimitry Andric // the instruction. This should happen right before a call to RAUW. 948*0b57cec5SDimitry Andric void MergeFunctions::removeUsers(Value *V) { 949*0b57cec5SDimitry Andric for (User *U : V->users()) 950*0b57cec5SDimitry Andric if (auto *I = dyn_cast<Instruction>(U)) 951*0b57cec5SDimitry Andric remove(I->getFunction()); 952*0b57cec5SDimitry Andric } 953