10b57cec5SDimitry Andric //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass looks for equivalent functions that are mergable and folds them.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric // Order relation is defined on set of functions. It was made through
120b57cec5SDimitry Andric // special function comparison procedure that returns
130b57cec5SDimitry Andric // 0 when functions are equal,
140b57cec5SDimitry Andric // -1 when Left function is less than right function, and
150b57cec5SDimitry Andric // 1 for opposite case. We need total-ordering, so we need to maintain
160b57cec5SDimitry Andric // four properties on the functions set:
170b57cec5SDimitry Andric // a <= a (reflexivity)
180b57cec5SDimitry Andric // if a <= b and b <= a then a = b (antisymmetry)
190b57cec5SDimitry Andric // if a <= b and b <= c then a <= c (transitivity).
200b57cec5SDimitry Andric // for all a and b: a <= b or b <= a (totality).
210b57cec5SDimitry Andric //
220b57cec5SDimitry Andric // Comparison iterates through each instruction in each basic block.
230b57cec5SDimitry Andric // Functions are kept on binary tree. For each new function F we perform
240b57cec5SDimitry Andric // lookup in binary tree.
250b57cec5SDimitry Andric // In practice it works the following way:
260b57cec5SDimitry Andric // -- We define Function* container class with custom "operator<" (FunctionPtr).
270b57cec5SDimitry Andric // -- "FunctionPtr" instances are stored in std::set collection, so every
280b57cec5SDimitry Andric // std::set::insert operation will give you result in log(N) time.
290b57cec5SDimitry Andric //
300b57cec5SDimitry Andric // As an optimization, a hash of the function structure is calculated first, and
310b57cec5SDimitry Andric // two functions are only compared if they have the same hash. This hash is
320b57cec5SDimitry Andric // cheap to compute, and has the property that if function F == G according to
330b57cec5SDimitry Andric // the comparison function, then hash(F) == hash(G). This consistency property
340b57cec5SDimitry Andric // is critical to ensuring all possible merging opportunities are exploited.
350b57cec5SDimitry Andric // Collisions in the hash affect the speed of the pass but not the correctness
360b57cec5SDimitry Andric // or determinism of the resulting transformation.
370b57cec5SDimitry Andric //
380b57cec5SDimitry Andric // When a match is found the functions are folded. If both functions are
390b57cec5SDimitry Andric // overridable, we move the functionality into a new internal function and
400b57cec5SDimitry Andric // leave two overridable thunks to it.
410b57cec5SDimitry Andric //
420b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
430b57cec5SDimitry Andric //
440b57cec5SDimitry Andric // Future work:
450b57cec5SDimitry Andric //
460b57cec5SDimitry Andric // * virtual functions.
470b57cec5SDimitry Andric //
480b57cec5SDimitry Andric // Many functions have their address taken by the virtual function table for
490b57cec5SDimitry Andric // the object they belong to. However, as long as it's only used for a lookup
500b57cec5SDimitry Andric // and call, this is irrelevant, and we'd like to fold such functions.
510b57cec5SDimitry Andric //
520b57cec5SDimitry Andric // * be smarter about bitcasts.
530b57cec5SDimitry Andric //
540b57cec5SDimitry Andric // In order to fold functions, we will sometimes add either bitcast instructions
550b57cec5SDimitry Andric // or bitcast constant expressions. Unfortunately, this can confound further
560b57cec5SDimitry Andric // analysis since the two functions differ where one has a bitcast and the
570b57cec5SDimitry Andric // other doesn't. We should learn to look through bitcasts.
580b57cec5SDimitry Andric //
590b57cec5SDimitry Andric // * Compare complex types with pointer types inside.
600b57cec5SDimitry Andric // * Compare cross-reference cases.
610b57cec5SDimitry Andric // * Compare complex expressions.
620b57cec5SDimitry Andric //
630b57cec5SDimitry Andric // All the three issues above could be described as ability to prove that
640b57cec5SDimitry Andric // fA == fB == fC == fE == fF == fG in example below:
650b57cec5SDimitry Andric //
660b57cec5SDimitry Andric // void fA() {
670b57cec5SDimitry Andric // fB();
680b57cec5SDimitry Andric // }
690b57cec5SDimitry Andric // void fB() {
700b57cec5SDimitry Andric // fA();
710b57cec5SDimitry Andric // }
720b57cec5SDimitry Andric //
730b57cec5SDimitry Andric // void fE() {
740b57cec5SDimitry Andric // fF();
750b57cec5SDimitry Andric // }
760b57cec5SDimitry Andric // void fF() {
770b57cec5SDimitry Andric // fG();
780b57cec5SDimitry Andric // }
790b57cec5SDimitry Andric // void fG() {
800b57cec5SDimitry Andric // fE();
810b57cec5SDimitry Andric // }
820b57cec5SDimitry Andric //
830b57cec5SDimitry Andric // Simplest cross-reference case (fA <--> fB) was implemented in previous
840b57cec5SDimitry Andric // versions of MergeFunctions, though it presented only in two function pairs
850b57cec5SDimitry Andric // in test-suite (that counts >50k functions)
860b57cec5SDimitry Andric // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
870b57cec5SDimitry Andric // could cover much more cases.
880b57cec5SDimitry Andric //
890b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
900b57cec5SDimitry Andric
9181ad6265SDimitry Andric #include "llvm/Transforms/IPO/MergeFunctions.h"
920b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
930b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
940b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
950b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
960b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
970b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
980b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
990b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
1000b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
1010b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
1020b57cec5SDimitry Andric #include "llvm/IR/Function.h"
1030b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
1040b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
1050b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
1060b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
1070b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
1080b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
1090b57cec5SDimitry Andric #include "llvm/IR/Module.h"
110*c9157d92SDimitry Andric #include "llvm/IR/StructuralHash.h"
1110b57cec5SDimitry Andric #include "llvm/IR/Type.h"
1120b57cec5SDimitry Andric #include "llvm/IR/Use.h"
1130b57cec5SDimitry Andric #include "llvm/IR/User.h"
1140b57cec5SDimitry Andric #include "llvm/IR/Value.h"
1150b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
1160b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1170b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
1180b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
1190b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1200b57cec5SDimitry Andric #include "llvm/Transforms/IPO.h"
1210b57cec5SDimitry Andric #include "llvm/Transforms/Utils/FunctionComparator.h"
12281ad6265SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
1230b57cec5SDimitry Andric #include <algorithm>
1240b57cec5SDimitry Andric #include <cassert>
1250b57cec5SDimitry Andric #include <iterator>
1260b57cec5SDimitry Andric #include <set>
1270b57cec5SDimitry Andric #include <utility>
1280b57cec5SDimitry Andric #include <vector>
1290b57cec5SDimitry Andric
1300b57cec5SDimitry Andric using namespace llvm;
1310b57cec5SDimitry Andric
1320b57cec5SDimitry Andric #define DEBUG_TYPE "mergefunc"
1330b57cec5SDimitry Andric
1340b57cec5SDimitry Andric STATISTIC(NumFunctionsMerged, "Number of functions merged");
1350b57cec5SDimitry Andric STATISTIC(NumThunksWritten, "Number of thunks generated");
1360b57cec5SDimitry Andric STATISTIC(NumAliasesWritten, "Number of aliases generated");
1370b57cec5SDimitry Andric STATISTIC(NumDoubleWeak, "Number of new functions created");
1380b57cec5SDimitry Andric
13981ad6265SDimitry Andric static cl::opt<unsigned> NumFunctionsForVerificationCheck(
14081ad6265SDimitry Andric "mergefunc-verify",
14181ad6265SDimitry Andric cl::desc("How many functions in a module could be used for "
14281ad6265SDimitry Andric "MergeFunctions to pass a basic correctness check. "
1430b57cec5SDimitry Andric "'0' disables this check. Works only with '-debug' key."),
1440b57cec5SDimitry Andric cl::init(0), cl::Hidden);
1450b57cec5SDimitry Andric
1460b57cec5SDimitry Andric // Under option -mergefunc-preserve-debug-info we:
1470b57cec5SDimitry Andric // - Do not create a new function for a thunk.
1480b57cec5SDimitry Andric // - Retain the debug info for a thunk's parameters (and associated
1490b57cec5SDimitry Andric // instructions for the debug info) from the entry block.
1500b57cec5SDimitry Andric // Note: -debug will display the algorithm at work.
1510b57cec5SDimitry Andric // - Create debug-info for the call (to the shared implementation) made by
1520b57cec5SDimitry Andric // a thunk and its return value.
1530b57cec5SDimitry Andric // - Erase the rest of the function, retaining the (minimally sized) entry
1540b57cec5SDimitry Andric // block to create a thunk.
1550b57cec5SDimitry Andric // - Preserve a thunk's call site to point to the thunk even when both occur
1560b57cec5SDimitry Andric // within the same translation unit, to aid debugability. Note that this
1570b57cec5SDimitry Andric // behaviour differs from the underlying -mergefunc implementation which
1580b57cec5SDimitry Andric // modifies the thunk's call site to point to the shared implementation
1590b57cec5SDimitry Andric // when both occur within the same translation unit.
1600b57cec5SDimitry Andric static cl::opt<bool>
1610b57cec5SDimitry Andric MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
1620b57cec5SDimitry Andric cl::init(false),
1630b57cec5SDimitry Andric cl::desc("Preserve debug info in thunk when mergefunc "
1640b57cec5SDimitry Andric "transformations are made."));
1650b57cec5SDimitry Andric
1660b57cec5SDimitry Andric static cl::opt<bool>
1670b57cec5SDimitry Andric MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
1680b57cec5SDimitry Andric cl::init(false),
1690b57cec5SDimitry Andric cl::desc("Allow mergefunc to create aliases"));
1700b57cec5SDimitry Andric
1710b57cec5SDimitry Andric namespace {
1720b57cec5SDimitry Andric
1730b57cec5SDimitry Andric class FunctionNode {
1740b57cec5SDimitry Andric mutable AssertingVH<Function> F;
175*c9157d92SDimitry Andric IRHash Hash;
1760b57cec5SDimitry Andric
1770b57cec5SDimitry Andric public:
1780b57cec5SDimitry Andric // Note the hash is recalculated potentially multiple times, but it is cheap.
FunctionNode(Function * F)179*c9157d92SDimitry Andric FunctionNode(Function *F) : F(F), Hash(StructuralHash(*F)) {}
1800b57cec5SDimitry Andric
getFunc() const1810b57cec5SDimitry Andric Function *getFunc() const { return F; }
getHash() const182*c9157d92SDimitry Andric IRHash getHash() const { return Hash; }
1830b57cec5SDimitry Andric
1840b57cec5SDimitry Andric /// Replace the reference to the function F by the function G, assuming their
1850b57cec5SDimitry Andric /// implementations are equal.
replaceBy(Function * G) const1860b57cec5SDimitry Andric void replaceBy(Function *G) const {
1870b57cec5SDimitry Andric F = G;
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric };
1900b57cec5SDimitry Andric
1910b57cec5SDimitry Andric /// MergeFunctions finds functions which will generate identical machine code,
1920b57cec5SDimitry Andric /// by considering all pointer types to be equivalent. Once identified,
1930b57cec5SDimitry Andric /// MergeFunctions will fold them by replacing a call to one to a call to a
1940b57cec5SDimitry Andric /// bitcast of the other.
195480093f4SDimitry Andric class MergeFunctions {
1960b57cec5SDimitry Andric public:
MergeFunctions()197480093f4SDimitry Andric MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) {
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric
200480093f4SDimitry Andric bool runOnModule(Module &M);
2010b57cec5SDimitry Andric
2020b57cec5SDimitry Andric private:
2030b57cec5SDimitry Andric // The function comparison operator is provided here so that FunctionNodes do
2040b57cec5SDimitry Andric // not need to become larger with another pointer.
2050b57cec5SDimitry Andric class FunctionNodeCmp {
2060b57cec5SDimitry Andric GlobalNumberState* GlobalNumbers;
2070b57cec5SDimitry Andric
2080b57cec5SDimitry Andric public:
FunctionNodeCmp(GlobalNumberState * GN)2090b57cec5SDimitry Andric FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
2100b57cec5SDimitry Andric
operator ()(const FunctionNode & LHS,const FunctionNode & RHS) const2110b57cec5SDimitry Andric bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
2120b57cec5SDimitry Andric // Order first by hashes, then full function comparison.
2130b57cec5SDimitry Andric if (LHS.getHash() != RHS.getHash())
2140b57cec5SDimitry Andric return LHS.getHash() < RHS.getHash();
2150b57cec5SDimitry Andric FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
216bdd1243dSDimitry Andric return FCmp.compare() < 0;
2170b57cec5SDimitry Andric }
2180b57cec5SDimitry Andric };
2190b57cec5SDimitry Andric using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
2200b57cec5SDimitry Andric
2210b57cec5SDimitry Andric GlobalNumberState GlobalNumbers;
2220b57cec5SDimitry Andric
2230b57cec5SDimitry Andric /// A work queue of functions that may have been modified and should be
2240b57cec5SDimitry Andric /// analyzed again.
2250b57cec5SDimitry Andric std::vector<WeakTrackingVH> Deferred;
2260b57cec5SDimitry Andric
22781ad6265SDimitry Andric /// Set of values marked as used in llvm.used and llvm.compiler.used.
22881ad6265SDimitry Andric SmallPtrSet<GlobalValue *, 4> Used;
22981ad6265SDimitry Andric
2300b57cec5SDimitry Andric #ifndef NDEBUG
2310b57cec5SDimitry Andric /// Checks the rules of order relation introduced among functions set.
23281ad6265SDimitry Andric /// Returns true, if check has been passed, and false if failed.
23381ad6265SDimitry Andric bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
2340b57cec5SDimitry Andric #endif
2350b57cec5SDimitry Andric
2360b57cec5SDimitry Andric /// Insert a ComparableFunction into the FnTree, or merge it away if it's
2370b57cec5SDimitry Andric /// equal to one that's already present.
2380b57cec5SDimitry Andric bool insert(Function *NewFunction);
2390b57cec5SDimitry Andric
2400b57cec5SDimitry Andric /// Remove a Function from the FnTree and queue it up for a second sweep of
2410b57cec5SDimitry Andric /// analysis.
2420b57cec5SDimitry Andric void remove(Function *F);
2430b57cec5SDimitry Andric
2440b57cec5SDimitry Andric /// Find the functions that use this Value and remove them from FnTree and
2450b57cec5SDimitry Andric /// queue the functions.
2460b57cec5SDimitry Andric void removeUsers(Value *V);
2470b57cec5SDimitry Andric
2480b57cec5SDimitry Andric /// Replace all direct calls of Old with calls of New. Will bitcast New if
2490b57cec5SDimitry Andric /// necessary to make types match.
2500b57cec5SDimitry Andric void replaceDirectCallers(Function *Old, Function *New);
2510b57cec5SDimitry Andric
2520b57cec5SDimitry Andric /// Merge two equivalent functions. Upon completion, G may be deleted, or may
2530b57cec5SDimitry Andric /// be converted into a thunk. In either case, it should never be visited
2540b57cec5SDimitry Andric /// again.
2550b57cec5SDimitry Andric void mergeTwoFunctions(Function *F, Function *G);
2560b57cec5SDimitry Andric
2570b57cec5SDimitry Andric /// Fill PDIUnrelatedWL with instructions from the entry block that are
2580b57cec5SDimitry Andric /// unrelated to parameter related debug info.
2590b57cec5SDimitry Andric void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
2600b57cec5SDimitry Andric std::vector<Instruction *> &PDIUnrelatedWL);
2610b57cec5SDimitry Andric
2620b57cec5SDimitry Andric /// Erase the rest of the CFG (i.e. barring the entry block).
2630b57cec5SDimitry Andric void eraseTail(Function *G);
2640b57cec5SDimitry Andric
2650b57cec5SDimitry Andric /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
2660b57cec5SDimitry Andric /// parameter debug info, from the entry block.
2670b57cec5SDimitry Andric void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
2680b57cec5SDimitry Andric
2690b57cec5SDimitry Andric /// Replace G with a simple tail call to bitcast(F). Also (unless
2700b57cec5SDimitry Andric /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
2710b57cec5SDimitry Andric /// delete G.
2720b57cec5SDimitry Andric void writeThunk(Function *F, Function *G);
2730b57cec5SDimitry Andric
2740b57cec5SDimitry Andric // Replace G with an alias to F (deleting function G)
2750b57cec5SDimitry Andric void writeAlias(Function *F, Function *G);
2760b57cec5SDimitry Andric
2770b57cec5SDimitry Andric // Replace G with an alias to F if possible, or a thunk to F if possible.
2780b57cec5SDimitry Andric // Returns false if neither is the case.
2790b57cec5SDimitry Andric bool writeThunkOrAlias(Function *F, Function *G);
2800b57cec5SDimitry Andric
2810b57cec5SDimitry Andric /// Replace function F with function G in the function tree.
2820b57cec5SDimitry Andric void replaceFunctionInTree(const FunctionNode &FN, Function *G);
2830b57cec5SDimitry Andric
2840b57cec5SDimitry Andric /// The set of all distinct functions. Use the insert() and remove() methods
2850b57cec5SDimitry Andric /// to modify it. The map allows efficient lookup and deferring of Functions.
2860b57cec5SDimitry Andric FnTreeType FnTree;
2870b57cec5SDimitry Andric
2880b57cec5SDimitry Andric // Map functions to the iterators of the FunctionNode which contains them
2890b57cec5SDimitry Andric // in the FnTree. This must be updated carefully whenever the FnTree is
2900b57cec5SDimitry Andric // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
2910b57cec5SDimitry Andric // dangling iterators into FnTree. The invariant that preserves this is that
2920b57cec5SDimitry Andric // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
2930b57cec5SDimitry Andric DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
2940b57cec5SDimitry Andric };
2950b57cec5SDimitry Andric } // end anonymous namespace
2960b57cec5SDimitry Andric
run(Module & M,ModuleAnalysisManager & AM)297480093f4SDimitry Andric PreservedAnalyses MergeFunctionsPass::run(Module &M,
298480093f4SDimitry Andric ModuleAnalysisManager &AM) {
299480093f4SDimitry Andric MergeFunctions MF;
300480093f4SDimitry Andric if (!MF.runOnModule(M))
301480093f4SDimitry Andric return PreservedAnalyses::all();
302480093f4SDimitry Andric return PreservedAnalyses::none();
3030b57cec5SDimitry Andric }
3040b57cec5SDimitry Andric
3050b57cec5SDimitry Andric #ifndef NDEBUG
doFunctionalCheck(std::vector<WeakTrackingVH> & Worklist)30681ad6265SDimitry Andric bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
30781ad6265SDimitry Andric if (const unsigned Max = NumFunctionsForVerificationCheck) {
3080b57cec5SDimitry Andric unsigned TripleNumber = 0;
3090b57cec5SDimitry Andric bool Valid = true;
3100b57cec5SDimitry Andric
31181ad6265SDimitry Andric dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n";
3120b57cec5SDimitry Andric
3130b57cec5SDimitry Andric unsigned i = 0;
3140b57cec5SDimitry Andric for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
3150b57cec5SDimitry Andric E = Worklist.end();
3160b57cec5SDimitry Andric I != E && i < Max; ++I, ++i) {
3170b57cec5SDimitry Andric unsigned j = i;
3180b57cec5SDimitry Andric for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
3190b57cec5SDimitry Andric ++J, ++j) {
3200b57cec5SDimitry Andric Function *F1 = cast<Function>(*I);
3210b57cec5SDimitry Andric Function *F2 = cast<Function>(*J);
3220b57cec5SDimitry Andric int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
3230b57cec5SDimitry Andric int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
3240b57cec5SDimitry Andric
3250b57cec5SDimitry Andric // If F1 <= F2, then F2 >= F1, otherwise report failure.
3260b57cec5SDimitry Andric if (Res1 != -Res2) {
32781ad6265SDimitry Andric dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
3280b57cec5SDimitry Andric << "\n";
3290b57cec5SDimitry Andric dbgs() << *F1 << '\n' << *F2 << '\n';
3300b57cec5SDimitry Andric Valid = false;
3310b57cec5SDimitry Andric }
3320b57cec5SDimitry Andric
3330b57cec5SDimitry Andric if (Res1 == 0)
3340b57cec5SDimitry Andric continue;
3350b57cec5SDimitry Andric
3360b57cec5SDimitry Andric unsigned k = j;
3370b57cec5SDimitry Andric for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
3380b57cec5SDimitry Andric ++k, ++K, ++TripleNumber) {
3390b57cec5SDimitry Andric if (K == J)
3400b57cec5SDimitry Andric continue;
3410b57cec5SDimitry Andric
3420b57cec5SDimitry Andric Function *F3 = cast<Function>(*K);
3430b57cec5SDimitry Andric int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
3440b57cec5SDimitry Andric int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
3450b57cec5SDimitry Andric
3460b57cec5SDimitry Andric bool Transitive = true;
3470b57cec5SDimitry Andric
3480b57cec5SDimitry Andric if (Res1 != 0 && Res1 == Res4) {
3490b57cec5SDimitry Andric // F1 > F2, F2 > F3 => F1 > F3
3500b57cec5SDimitry Andric Transitive = Res3 == Res1;
3510b57cec5SDimitry Andric } else if (Res3 != 0 && Res3 == -Res4) {
3520b57cec5SDimitry Andric // F1 > F3, F3 > F2 => F1 > F2
3530b57cec5SDimitry Andric Transitive = Res3 == Res1;
3540b57cec5SDimitry Andric } else if (Res4 != 0 && -Res3 == Res4) {
3550b57cec5SDimitry Andric // F2 > F3, F3 > F1 => F2 > F1
3560b57cec5SDimitry Andric Transitive = Res4 == -Res1;
3570b57cec5SDimitry Andric }
3580b57cec5SDimitry Andric
3590b57cec5SDimitry Andric if (!Transitive) {
36081ad6265SDimitry Andric dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: "
3610b57cec5SDimitry Andric << TripleNumber << "\n";
3620b57cec5SDimitry Andric dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
3630b57cec5SDimitry Andric << Res4 << "\n";
3640b57cec5SDimitry Andric dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
3650b57cec5SDimitry Andric Valid = false;
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric }
3680b57cec5SDimitry Andric }
3690b57cec5SDimitry Andric }
3700b57cec5SDimitry Andric
37181ad6265SDimitry Andric dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n";
3720b57cec5SDimitry Andric return Valid;
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric return true;
3750b57cec5SDimitry Andric }
3760b57cec5SDimitry Andric #endif
3770b57cec5SDimitry Andric
378*c9157d92SDimitry Andric /// Check whether \p F has an intrinsic which references
379*c9157d92SDimitry Andric /// distinct metadata as an operand. The most common
380*c9157d92SDimitry Andric /// instance of this would be CFI checks for function-local types.
hasDistinctMetadataIntrinsic(const Function & F)381*c9157d92SDimitry Andric static bool hasDistinctMetadataIntrinsic(const Function &F) {
382*c9157d92SDimitry Andric for (const BasicBlock &BB : F) {
383*c9157d92SDimitry Andric for (const Instruction &I : BB.instructionsWithoutDebug()) {
384*c9157d92SDimitry Andric if (!isa<IntrinsicInst>(&I))
385*c9157d92SDimitry Andric continue;
386*c9157d92SDimitry Andric
387*c9157d92SDimitry Andric for (Value *Op : I.operands()) {
388*c9157d92SDimitry Andric auto *MDL = dyn_cast<MetadataAsValue>(Op);
389*c9157d92SDimitry Andric if (!MDL)
390*c9157d92SDimitry Andric continue;
391*c9157d92SDimitry Andric if (MDNode *N = dyn_cast<MDNode>(MDL->getMetadata()))
392*c9157d92SDimitry Andric if (N->isDistinct())
393*c9157d92SDimitry Andric return true;
394*c9157d92SDimitry Andric }
395*c9157d92SDimitry Andric }
396*c9157d92SDimitry Andric }
397*c9157d92SDimitry Andric return false;
398*c9157d92SDimitry Andric }
399*c9157d92SDimitry Andric
4000b57cec5SDimitry Andric /// Check whether \p F is eligible for function merging.
isEligibleForMerging(Function & F)4010b57cec5SDimitry Andric static bool isEligibleForMerging(Function &F) {
402*c9157d92SDimitry Andric return !F.isDeclaration() && !F.hasAvailableExternallyLinkage() &&
403*c9157d92SDimitry Andric !hasDistinctMetadataIntrinsic(F);
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric
runOnModule(Module & M)4060b57cec5SDimitry Andric bool MergeFunctions::runOnModule(Module &M) {
4070b57cec5SDimitry Andric bool Changed = false;
4080b57cec5SDimitry Andric
40981ad6265SDimitry Andric SmallVector<GlobalValue *, 4> UsedV;
41081ad6265SDimitry Andric collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/false);
41181ad6265SDimitry Andric collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/true);
41281ad6265SDimitry Andric Used.insert(UsedV.begin(), UsedV.end());
41381ad6265SDimitry Andric
4140b57cec5SDimitry Andric // All functions in the module, ordered by hash. Functions with a unique
4150b57cec5SDimitry Andric // hash value are easily eliminated.
416*c9157d92SDimitry Andric std::vector<std::pair<IRHash, Function *>> HashedFuncs;
4170b57cec5SDimitry Andric for (Function &Func : M) {
4180b57cec5SDimitry Andric if (isEligibleForMerging(Func)) {
419*c9157d92SDimitry Andric HashedFuncs.push_back({StructuralHash(Func), &Func});
4200b57cec5SDimitry Andric }
4210b57cec5SDimitry Andric }
4220b57cec5SDimitry Andric
4230b57cec5SDimitry Andric llvm::stable_sort(HashedFuncs, less_first());
4240b57cec5SDimitry Andric
4250b57cec5SDimitry Andric auto S = HashedFuncs.begin();
4260b57cec5SDimitry Andric for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
4270b57cec5SDimitry Andric // If the hash value matches the previous value or the next one, we must
4280b57cec5SDimitry Andric // consider merging it. Otherwise it is dropped and never considered again.
4290b57cec5SDimitry Andric if ((I != S && std::prev(I)->first == I->first) ||
4300b57cec5SDimitry Andric (std::next(I) != IE && std::next(I)->first == I->first) ) {
4310b57cec5SDimitry Andric Deferred.push_back(WeakTrackingVH(I->second));
4320b57cec5SDimitry Andric }
4330b57cec5SDimitry Andric }
4340b57cec5SDimitry Andric
4350b57cec5SDimitry Andric do {
4360b57cec5SDimitry Andric std::vector<WeakTrackingVH> Worklist;
4370b57cec5SDimitry Andric Deferred.swap(Worklist);
4380b57cec5SDimitry Andric
43981ad6265SDimitry Andric LLVM_DEBUG(doFunctionalCheck(Worklist));
4400b57cec5SDimitry Andric
4410b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
4420b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
4430b57cec5SDimitry Andric
4440b57cec5SDimitry Andric // Insert functions and merge them.
4450b57cec5SDimitry Andric for (WeakTrackingVH &I : Worklist) {
4460b57cec5SDimitry Andric if (!I)
4470b57cec5SDimitry Andric continue;
4480b57cec5SDimitry Andric Function *F = cast<Function>(I);
4490b57cec5SDimitry Andric if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
4500b57cec5SDimitry Andric Changed |= insert(F);
4510b57cec5SDimitry Andric }
4520b57cec5SDimitry Andric }
4530b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
4540b57cec5SDimitry Andric } while (!Deferred.empty());
4550b57cec5SDimitry Andric
4560b57cec5SDimitry Andric FnTree.clear();
4570b57cec5SDimitry Andric FNodesInTree.clear();
4580b57cec5SDimitry Andric GlobalNumbers.clear();
45981ad6265SDimitry Andric Used.clear();
4600b57cec5SDimitry Andric
4610b57cec5SDimitry Andric return Changed;
4620b57cec5SDimitry Andric }
4630b57cec5SDimitry Andric
4640b57cec5SDimitry Andric // Replace direct callers of Old with New.
replaceDirectCallers(Function * Old,Function * New)4650b57cec5SDimitry Andric void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
466349cc55cSDimitry Andric for (Use &U : llvm::make_early_inc_range(Old->uses())) {
467349cc55cSDimitry Andric CallBase *CB = dyn_cast<CallBase>(U.getUser());
468349cc55cSDimitry Andric if (CB && CB->isCallee(&U)) {
469480093f4SDimitry Andric // Do not copy attributes from the called function to the call-site.
470480093f4SDimitry Andric // Function comparison ensures that the attributes are the same up to
471480093f4SDimitry Andric // type congruences in byval(), in which case we need to keep the byval
472480093f4SDimitry Andric // type of the call-site, not the callee function.
4735ffd83dbSDimitry Andric remove(CB->getFunction());
474*c9157d92SDimitry Andric U.set(New);
4750b57cec5SDimitry Andric }
4760b57cec5SDimitry Andric }
4770b57cec5SDimitry Andric }
4780b57cec5SDimitry Andric
4790b57cec5SDimitry Andric // Helper for writeThunk,
4800b57cec5SDimitry Andric // Selects proper bitcast operation,
4810b57cec5SDimitry Andric // but a bit simpler then CastInst::getCastOpcode.
createCast(IRBuilder<> & Builder,Value * V,Type * DestTy)4820b57cec5SDimitry Andric static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
4830b57cec5SDimitry Andric Type *SrcTy = V->getType();
4840b57cec5SDimitry Andric if (SrcTy->isStructTy()) {
4850b57cec5SDimitry Andric assert(DestTy->isStructTy());
4860b57cec5SDimitry Andric assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
48781ad6265SDimitry Andric Value *Result = PoisonValue::get(DestTy);
4880b57cec5SDimitry Andric for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
489bdd1243dSDimitry Andric Value *Element =
490bdd1243dSDimitry Andric createCast(Builder, Builder.CreateExtractValue(V, ArrayRef(I)),
4910b57cec5SDimitry Andric DestTy->getStructElementType(I));
4920b57cec5SDimitry Andric
493bdd1243dSDimitry Andric Result = Builder.CreateInsertValue(Result, Element, ArrayRef(I));
4940b57cec5SDimitry Andric }
4950b57cec5SDimitry Andric return Result;
4960b57cec5SDimitry Andric }
4970b57cec5SDimitry Andric assert(!DestTy->isStructTy());
4980b57cec5SDimitry Andric if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
4990b57cec5SDimitry Andric return Builder.CreateIntToPtr(V, DestTy);
5000b57cec5SDimitry Andric else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
5010b57cec5SDimitry Andric return Builder.CreatePtrToInt(V, DestTy);
5020b57cec5SDimitry Andric else
5030b57cec5SDimitry Andric return Builder.CreateBitCast(V, DestTy);
5040b57cec5SDimitry Andric }
5050b57cec5SDimitry Andric
5060b57cec5SDimitry Andric // Erase the instructions in PDIUnrelatedWL as they are unrelated to the
5070b57cec5SDimitry Andric // parameter debug info, from the entry block.
eraseInstsUnrelatedToPDI(std::vector<Instruction * > & PDIUnrelatedWL)5080b57cec5SDimitry Andric void MergeFunctions::eraseInstsUnrelatedToPDI(
5090b57cec5SDimitry Andric std::vector<Instruction *> &PDIUnrelatedWL) {
5100b57cec5SDimitry Andric LLVM_DEBUG(
5110b57cec5SDimitry Andric dbgs() << " Erasing instructions (in reverse order of appearance in "
5120b57cec5SDimitry Andric "entry block) unrelated to parameter debug info from entry "
5130b57cec5SDimitry Andric "block: {\n");
5140b57cec5SDimitry Andric while (!PDIUnrelatedWL.empty()) {
5150b57cec5SDimitry Andric Instruction *I = PDIUnrelatedWL.back();
5160b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
5170b57cec5SDimitry Andric LLVM_DEBUG(I->print(dbgs()));
5180b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
5190b57cec5SDimitry Andric I->eraseFromParent();
5200b57cec5SDimitry Andric PDIUnrelatedWL.pop_back();
5210b57cec5SDimitry Andric }
5220b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
5230b57cec5SDimitry Andric "debug info from entry block. \n");
5240b57cec5SDimitry Andric }
5250b57cec5SDimitry Andric
5260b57cec5SDimitry Andric // Reduce G to its entry block.
eraseTail(Function * G)5270b57cec5SDimitry Andric void MergeFunctions::eraseTail(Function *G) {
5280b57cec5SDimitry Andric std::vector<BasicBlock *> WorklistBB;
529fe6060f1SDimitry Andric for (BasicBlock &BB : drop_begin(*G)) {
530fe6060f1SDimitry Andric BB.dropAllReferences();
531fe6060f1SDimitry Andric WorklistBB.push_back(&BB);
5320b57cec5SDimitry Andric }
5330b57cec5SDimitry Andric while (!WorklistBB.empty()) {
5340b57cec5SDimitry Andric BasicBlock *BB = WorklistBB.back();
5350b57cec5SDimitry Andric BB->eraseFromParent();
5360b57cec5SDimitry Andric WorklistBB.pop_back();
5370b57cec5SDimitry Andric }
5380b57cec5SDimitry Andric }
5390b57cec5SDimitry Andric
5400b57cec5SDimitry Andric // We are interested in the following instructions from the entry block as being
5410b57cec5SDimitry Andric // related to parameter debug info:
5420b57cec5SDimitry Andric // - @llvm.dbg.declare
5430b57cec5SDimitry Andric // - stores from the incoming parameters to locations on the stack-frame
5440b57cec5SDimitry Andric // - allocas that create these locations on the stack-frame
5450b57cec5SDimitry Andric // - @llvm.dbg.value
5460b57cec5SDimitry Andric // - the entry block's terminator
5470b57cec5SDimitry Andric // The rest are unrelated to debug info for the parameters; fill up
5480b57cec5SDimitry Andric // PDIUnrelatedWL with such instructions.
filterInstsUnrelatedToPDI(BasicBlock * GEntryBlock,std::vector<Instruction * > & PDIUnrelatedWL)5490b57cec5SDimitry Andric void MergeFunctions::filterInstsUnrelatedToPDI(
5500b57cec5SDimitry Andric BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
5510b57cec5SDimitry Andric std::set<Instruction *> PDIRelated;
5520b57cec5SDimitry Andric for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
5530b57cec5SDimitry Andric BI != BIE; ++BI) {
5540b57cec5SDimitry Andric if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
5550b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Deciding: ");
5560b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs()));
5570b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
5580b57cec5SDimitry Andric DILocalVariable *DILocVar = DVI->getVariable();
5590b57cec5SDimitry Andric if (DILocVar->isParameter()) {
5600b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Include (parameter): ");
5610b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs()));
5620b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
5630b57cec5SDimitry Andric PDIRelated.insert(&*BI);
5640b57cec5SDimitry Andric } else {
5650b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
5660b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs()));
5670b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
5680b57cec5SDimitry Andric }
5690b57cec5SDimitry Andric } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
5700b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Deciding: ");
5710b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs()));
5720b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
5730b57cec5SDimitry Andric DILocalVariable *DILocVar = DDI->getVariable();
5740b57cec5SDimitry Andric if (DILocVar->isParameter()) {
5750b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Parameter: ");
5760b57cec5SDimitry Andric LLVM_DEBUG(DILocVar->print(dbgs()));
5770b57cec5SDimitry Andric AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
5780b57cec5SDimitry Andric if (AI) {
5790b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Processing alloca users: ");
5800b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
5810b57cec5SDimitry Andric for (User *U : AI->users()) {
5820b57cec5SDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
5830b57cec5SDimitry Andric if (Value *Arg = SI->getValueOperand()) {
584fe6060f1SDimitry Andric if (isa<Argument>(Arg)) {
5850b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Include: ");
5860b57cec5SDimitry Andric LLVM_DEBUG(AI->print(dbgs()));
5870b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
5880b57cec5SDimitry Andric PDIRelated.insert(AI);
5890b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Include (parameter): ");
5900b57cec5SDimitry Andric LLVM_DEBUG(SI->print(dbgs()));
5910b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
5920b57cec5SDimitry Andric PDIRelated.insert(SI);
5930b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Include: ");
5940b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs()));
5950b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
5960b57cec5SDimitry Andric PDIRelated.insert(&*BI);
5970b57cec5SDimitry Andric } else {
5980b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
5990b57cec5SDimitry Andric LLVM_DEBUG(SI->print(dbgs()));
6000b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
6010b57cec5SDimitry Andric }
6020b57cec5SDimitry Andric }
6030b57cec5SDimitry Andric } else {
6040b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Defer: ");
6050b57cec5SDimitry Andric LLVM_DEBUG(U->print(dbgs()));
6060b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
6070b57cec5SDimitry Andric }
6080b57cec5SDimitry Andric }
6090b57cec5SDimitry Andric } else {
6100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
6110b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs()));
6120b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric } else {
6150b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
6160b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs()));
6170b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
6180b57cec5SDimitry Andric }
6190b57cec5SDimitry Andric } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
6200b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
6210b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs()));
6220b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
6230b57cec5SDimitry Andric PDIRelated.insert(&*BI);
6240b57cec5SDimitry Andric } else {
6250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Defer: ");
6260b57cec5SDimitry Andric LLVM_DEBUG(BI->print(dbgs()));
6270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
6280b57cec5SDimitry Andric }
6290b57cec5SDimitry Andric }
6300b57cec5SDimitry Andric LLVM_DEBUG(
6310b57cec5SDimitry Andric dbgs()
6320b57cec5SDimitry Andric << " Report parameter debug info related/related instructions: {\n");
633fe6060f1SDimitry Andric for (Instruction &I : *GEntryBlock) {
634fe6060f1SDimitry Andric if (PDIRelated.find(&I) == PDIRelated.end()) {
6350b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " !PDIRelated: ");
636fe6060f1SDimitry Andric LLVM_DEBUG(I.print(dbgs()));
6370b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
638fe6060f1SDimitry Andric PDIUnrelatedWL.push_back(&I);
6390b57cec5SDimitry Andric } else {
6400b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " PDIRelated: ");
641fe6060f1SDimitry Andric LLVM_DEBUG(I.print(dbgs()));
6420b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
6430b57cec5SDimitry Andric }
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " }\n");
6460b57cec5SDimitry Andric }
6470b57cec5SDimitry Andric
6480b57cec5SDimitry Andric /// Whether this function may be replaced by a forwarding thunk.
canCreateThunkFor(Function * F)6490b57cec5SDimitry Andric static bool canCreateThunkFor(Function *F) {
6500b57cec5SDimitry Andric if (F->isVarArg())
6510b57cec5SDimitry Andric return false;
6520b57cec5SDimitry Andric
6530b57cec5SDimitry Andric // Don't merge tiny functions using a thunk, since it can just end up
6540b57cec5SDimitry Andric // making the function larger.
6550b57cec5SDimitry Andric if (F->size() == 1) {
656*c9157d92SDimitry Andric if (F->front().sizeWithoutDebug() < 2) {
6570b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
6580b57cec5SDimitry Andric << " is too small to bother creating a thunk for\n");
6590b57cec5SDimitry Andric return false;
6600b57cec5SDimitry Andric }
6610b57cec5SDimitry Andric }
6620b57cec5SDimitry Andric return true;
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric
665*c9157d92SDimitry Andric /// Copy metadata from one function to another.
copyMetadataIfPresent(Function * From,Function * To,StringRef Key)666*c9157d92SDimitry Andric static void copyMetadataIfPresent(Function *From, Function *To, StringRef Key) {
667*c9157d92SDimitry Andric if (MDNode *MD = From->getMetadata(Key)) {
668*c9157d92SDimitry Andric To->setMetadata(Key, MD);
669*c9157d92SDimitry Andric }
670*c9157d92SDimitry Andric }
671*c9157d92SDimitry Andric
6720b57cec5SDimitry Andric // Replace G with a simple tail call to bitcast(F). Also (unless
6730b57cec5SDimitry Andric // MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
6740b57cec5SDimitry Andric // delete G. Under MergeFunctionsPDI, we use G itself for creating
6750b57cec5SDimitry Andric // the thunk as we preserve the debug info (and associated instructions)
6760b57cec5SDimitry Andric // from G's entry block pertaining to G's incoming arguments which are
6770b57cec5SDimitry Andric // passed on as corresponding arguments in the call that G makes to F.
6780b57cec5SDimitry Andric // For better debugability, under MergeFunctionsPDI, we do not modify G's
6790b57cec5SDimitry Andric // call sites to point to F even when within the same translation unit.
writeThunk(Function * F,Function * G)6800b57cec5SDimitry Andric void MergeFunctions::writeThunk(Function *F, Function *G) {
6810b57cec5SDimitry Andric BasicBlock *GEntryBlock = nullptr;
6820b57cec5SDimitry Andric std::vector<Instruction *> PDIUnrelatedWL;
6830b57cec5SDimitry Andric BasicBlock *BB = nullptr;
6840b57cec5SDimitry Andric Function *NewG = nullptr;
6850b57cec5SDimitry Andric if (MergeFunctionsPDI) {
6860b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
6870b57cec5SDimitry Andric "function as thunk; retain original: "
6880b57cec5SDimitry Andric << G->getName() << "()\n");
6890b57cec5SDimitry Andric GEntryBlock = &G->getEntryBlock();
6900b57cec5SDimitry Andric LLVM_DEBUG(
6910b57cec5SDimitry Andric dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
6920b57cec5SDimitry Andric "debug info for "
6930b57cec5SDimitry Andric << G->getName() << "() {\n");
6940b57cec5SDimitry Andric filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
6950b57cec5SDimitry Andric GEntryBlock->getTerminator()->eraseFromParent();
6960b57cec5SDimitry Andric BB = GEntryBlock;
6970b57cec5SDimitry Andric } else {
6980b57cec5SDimitry Andric NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
6990b57cec5SDimitry Andric G->getAddressSpace(), "", G->getParent());
7000b57cec5SDimitry Andric NewG->setComdat(G->getComdat());
7010b57cec5SDimitry Andric BB = BasicBlock::Create(F->getContext(), "", NewG);
7020b57cec5SDimitry Andric }
7030b57cec5SDimitry Andric
7040b57cec5SDimitry Andric IRBuilder<> Builder(BB);
7050b57cec5SDimitry Andric Function *H = MergeFunctionsPDI ? G : NewG;
7060b57cec5SDimitry Andric SmallVector<Value *, 16> Args;
7070b57cec5SDimitry Andric unsigned i = 0;
7080b57cec5SDimitry Andric FunctionType *FFTy = F->getFunctionType();
7090b57cec5SDimitry Andric for (Argument &AI : H->args()) {
7100b57cec5SDimitry Andric Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
7110b57cec5SDimitry Andric ++i;
7120b57cec5SDimitry Andric }
7130b57cec5SDimitry Andric
7140b57cec5SDimitry Andric CallInst *CI = Builder.CreateCall(F, Args);
7150b57cec5SDimitry Andric ReturnInst *RI = nullptr;
716fe6060f1SDimitry Andric bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail &&
717fe6060f1SDimitry Andric G->getCallingConv() == CallingConv::SwiftTail;
718fe6060f1SDimitry Andric CI->setTailCallKind(isSwiftTailCall ? llvm::CallInst::TCK_MustTail
719fe6060f1SDimitry Andric : llvm::CallInst::TCK_Tail);
7200b57cec5SDimitry Andric CI->setCallingConv(F->getCallingConv());
7210b57cec5SDimitry Andric CI->setAttributes(F->getAttributes());
7220b57cec5SDimitry Andric if (H->getReturnType()->isVoidTy()) {
7230b57cec5SDimitry Andric RI = Builder.CreateRetVoid();
7240b57cec5SDimitry Andric } else {
7250b57cec5SDimitry Andric RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
7260b57cec5SDimitry Andric }
7270b57cec5SDimitry Andric
7280b57cec5SDimitry Andric if (MergeFunctionsPDI) {
7290b57cec5SDimitry Andric DISubprogram *DIS = G->getSubprogram();
7300b57cec5SDimitry Andric if (DIS) {
731e8d8bef9SDimitry Andric DebugLoc CIDbgLoc =
732e8d8bef9SDimitry Andric DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
733e8d8bef9SDimitry Andric DebugLoc RIDbgLoc =
734e8d8bef9SDimitry Andric DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
7350b57cec5SDimitry Andric CI->setDebugLoc(CIDbgLoc);
7360b57cec5SDimitry Andric RI->setDebugLoc(RIDbgLoc);
7370b57cec5SDimitry Andric } else {
7380b57cec5SDimitry Andric LLVM_DEBUG(
7390b57cec5SDimitry Andric dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
7400b57cec5SDimitry Andric << G->getName() << "()\n");
7410b57cec5SDimitry Andric }
7420b57cec5SDimitry Andric eraseTail(G);
7430b57cec5SDimitry Andric eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
7440b57cec5SDimitry Andric LLVM_DEBUG(
7450b57cec5SDimitry Andric dbgs() << "} // End of parameter related debug info filtering for: "
7460b57cec5SDimitry Andric << G->getName() << "()\n");
7470b57cec5SDimitry Andric } else {
7480b57cec5SDimitry Andric NewG->copyAttributesFrom(G);
7490b57cec5SDimitry Andric NewG->takeName(G);
750*c9157d92SDimitry Andric // Ensure CFI type metadata is propagated to the new function.
751*c9157d92SDimitry Andric copyMetadataIfPresent(G, NewG, "type");
752*c9157d92SDimitry Andric copyMetadataIfPresent(G, NewG, "kcfi_type");
7530b57cec5SDimitry Andric removeUsers(G);
7540b57cec5SDimitry Andric G->replaceAllUsesWith(NewG);
7550b57cec5SDimitry Andric G->eraseFromParent();
7560b57cec5SDimitry Andric }
7570b57cec5SDimitry Andric
7580b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
7590b57cec5SDimitry Andric ++NumThunksWritten;
7600b57cec5SDimitry Andric }
7610b57cec5SDimitry Andric
7620b57cec5SDimitry Andric // Whether this function may be replaced by an alias
canCreateAliasFor(Function * F)7630b57cec5SDimitry Andric static bool canCreateAliasFor(Function *F) {
7640b57cec5SDimitry Andric if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
7650b57cec5SDimitry Andric return false;
7660b57cec5SDimitry Andric
7670b57cec5SDimitry Andric // We should only see linkages supported by aliases here
7680b57cec5SDimitry Andric assert(F->hasLocalLinkage() || F->hasExternalLinkage()
7690b57cec5SDimitry Andric || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
7700b57cec5SDimitry Andric return true;
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric
7730b57cec5SDimitry Andric // Replace G with an alias to F (deleting function G)
writeAlias(Function * F,Function * G)7740b57cec5SDimitry Andric void MergeFunctions::writeAlias(Function *F, Function *G) {
7750b57cec5SDimitry Andric PointerType *PtrType = G->getType();
776fe6060f1SDimitry Andric auto *GA = GlobalAlias::create(G->getValueType(), PtrType->getAddressSpace(),
777*c9157d92SDimitry Andric G->getLinkage(), "", F, G->getParent());
7780b57cec5SDimitry Andric
779bdd1243dSDimitry Andric const MaybeAlign FAlign = F->getAlign();
780bdd1243dSDimitry Andric const MaybeAlign GAlign = G->getAlign();
781bdd1243dSDimitry Andric if (FAlign || GAlign)
782bdd1243dSDimitry Andric F->setAlignment(std::max(FAlign.valueOrOne(), GAlign.valueOrOne()));
783bdd1243dSDimitry Andric else
784bdd1243dSDimitry Andric F->setAlignment(std::nullopt);
7850b57cec5SDimitry Andric GA->takeName(G);
7860b57cec5SDimitry Andric GA->setVisibility(G->getVisibility());
7870b57cec5SDimitry Andric GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
7880b57cec5SDimitry Andric
7890b57cec5SDimitry Andric removeUsers(G);
7900b57cec5SDimitry Andric G->replaceAllUsesWith(GA);
7910b57cec5SDimitry Andric G->eraseFromParent();
7920b57cec5SDimitry Andric
7930b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
7940b57cec5SDimitry Andric ++NumAliasesWritten;
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric
7970b57cec5SDimitry Andric // Replace G with an alias to F if possible, or a thunk to F if
7980b57cec5SDimitry Andric // profitable. Returns false if neither is the case.
writeThunkOrAlias(Function * F,Function * G)7990b57cec5SDimitry Andric bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
8000b57cec5SDimitry Andric if (canCreateAliasFor(G)) {
8010b57cec5SDimitry Andric writeAlias(F, G);
8020b57cec5SDimitry Andric return true;
8030b57cec5SDimitry Andric }
8040b57cec5SDimitry Andric if (canCreateThunkFor(F)) {
8050b57cec5SDimitry Andric writeThunk(F, G);
8060b57cec5SDimitry Andric return true;
8070b57cec5SDimitry Andric }
8080b57cec5SDimitry Andric return false;
8090b57cec5SDimitry Andric }
8100b57cec5SDimitry Andric
8110b57cec5SDimitry Andric // Merge two equivalent functions. Upon completion, Function G is deleted.
mergeTwoFunctions(Function * F,Function * G)8120b57cec5SDimitry Andric void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
8130b57cec5SDimitry Andric if (F->isInterposable()) {
8140b57cec5SDimitry Andric assert(G->isInterposable());
8150b57cec5SDimitry Andric
8160b57cec5SDimitry Andric // Both writeThunkOrAlias() calls below must succeed, either because we can
8170b57cec5SDimitry Andric // create aliases for G and NewF, or because a thunk for F is profitable.
8180b57cec5SDimitry Andric // F here has the same signature as NewF below, so that's what we check.
8190b57cec5SDimitry Andric if (!canCreateThunkFor(F) &&
8200b57cec5SDimitry Andric (!canCreateAliasFor(F) || !canCreateAliasFor(G)))
8210b57cec5SDimitry Andric return;
8220b57cec5SDimitry Andric
8230b57cec5SDimitry Andric // Make them both thunks to the same internal function.
8240b57cec5SDimitry Andric Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
8250b57cec5SDimitry Andric F->getAddressSpace(), "", F->getParent());
8260b57cec5SDimitry Andric NewF->copyAttributesFrom(F);
8270b57cec5SDimitry Andric NewF->takeName(F);
828*c9157d92SDimitry Andric // Ensure CFI type metadata is propagated to the new function.
829*c9157d92SDimitry Andric copyMetadataIfPresent(F, NewF, "type");
830*c9157d92SDimitry Andric copyMetadataIfPresent(F, NewF, "kcfi_type");
8310b57cec5SDimitry Andric removeUsers(F);
8320b57cec5SDimitry Andric F->replaceAllUsesWith(NewF);
8330b57cec5SDimitry Andric
834bdd1243dSDimitry Andric // We collect alignment before writeThunkOrAlias that overwrites NewF and
835bdd1243dSDimitry Andric // G's content.
836bdd1243dSDimitry Andric const MaybeAlign NewFAlign = NewF->getAlign();
837bdd1243dSDimitry Andric const MaybeAlign GAlign = G->getAlign();
8380b57cec5SDimitry Andric
8390b57cec5SDimitry Andric writeThunkOrAlias(F, G);
8400b57cec5SDimitry Andric writeThunkOrAlias(F, NewF);
8410b57cec5SDimitry Andric
842bdd1243dSDimitry Andric if (NewFAlign || GAlign)
843bdd1243dSDimitry Andric F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne()));
844bdd1243dSDimitry Andric else
845bdd1243dSDimitry Andric F->setAlignment(std::nullopt);
8460b57cec5SDimitry Andric F->setLinkage(GlobalValue::PrivateLinkage);
8470b57cec5SDimitry Andric ++NumDoubleWeak;
8480b57cec5SDimitry Andric ++NumFunctionsMerged;
8490b57cec5SDimitry Andric } else {
8500b57cec5SDimitry Andric // For better debugability, under MergeFunctionsPDI, we do not modify G's
8510b57cec5SDimitry Andric // call sites to point to F even when within the same translation unit.
8520b57cec5SDimitry Andric if (!G->isInterposable() && !MergeFunctionsPDI) {
85381ad6265SDimitry Andric // Functions referred to by llvm.used/llvm.compiler.used are special:
85481ad6265SDimitry Andric // there are uses of the symbol name that are not visible to LLVM,
85581ad6265SDimitry Andric // usually from inline asm.
85681ad6265SDimitry Andric if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) {
8570b57cec5SDimitry Andric // G might have been a key in our GlobalNumberState, and it's illegal
8580b57cec5SDimitry Andric // to replace a key in ValueMap<GlobalValue *> with a non-global.
8590b57cec5SDimitry Andric GlobalNumbers.erase(G);
8600b57cec5SDimitry Andric // If G's address is not significant, replace it entirely.
8610b57cec5SDimitry Andric removeUsers(G);
862*c9157d92SDimitry Andric G->replaceAllUsesWith(F);
8630b57cec5SDimitry Andric } else {
8640b57cec5SDimitry Andric // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
8650b57cec5SDimitry Andric // above).
8660b57cec5SDimitry Andric replaceDirectCallers(G, F);
8670b57cec5SDimitry Andric }
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric
8700b57cec5SDimitry Andric // If G was internal then we may have replaced all uses of G with F. If so,
8710b57cec5SDimitry Andric // stop here and delete G. There's no need for a thunk. (See note on
8720b57cec5SDimitry Andric // MergeFunctionsPDI above).
8730b57cec5SDimitry Andric if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
8740b57cec5SDimitry Andric G->eraseFromParent();
8750b57cec5SDimitry Andric ++NumFunctionsMerged;
8760b57cec5SDimitry Andric return;
8770b57cec5SDimitry Andric }
8780b57cec5SDimitry Andric
8790b57cec5SDimitry Andric if (writeThunkOrAlias(F, G)) {
8800b57cec5SDimitry Andric ++NumFunctionsMerged;
8810b57cec5SDimitry Andric }
8820b57cec5SDimitry Andric }
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric
8850b57cec5SDimitry Andric /// Replace function F by function G.
replaceFunctionInTree(const FunctionNode & FN,Function * G)8860b57cec5SDimitry Andric void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
8870b57cec5SDimitry Andric Function *G) {
8880b57cec5SDimitry Andric Function *F = FN.getFunc();
8890b57cec5SDimitry Andric assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
8900b57cec5SDimitry Andric "The two functions must be equal");
8910b57cec5SDimitry Andric
8920b57cec5SDimitry Andric auto I = FNodesInTree.find(F);
8930b57cec5SDimitry Andric assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
8940b57cec5SDimitry Andric assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
8950b57cec5SDimitry Andric
8960b57cec5SDimitry Andric FnTreeType::iterator IterToFNInFnTree = I->second;
8970b57cec5SDimitry Andric assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
8980b57cec5SDimitry Andric // Remove F -> FN and insert G -> FN
8990b57cec5SDimitry Andric FNodesInTree.erase(I);
9000b57cec5SDimitry Andric FNodesInTree.insert({G, IterToFNInFnTree});
9010b57cec5SDimitry Andric // Replace F with G in FN, which is stored inside the FnTree.
9020b57cec5SDimitry Andric FN.replaceBy(G);
9030b57cec5SDimitry Andric }
9040b57cec5SDimitry Andric
9050b57cec5SDimitry Andric // Ordering for functions that are equal under FunctionComparator
isFuncOrderCorrect(const Function * F,const Function * G)9060b57cec5SDimitry Andric static bool isFuncOrderCorrect(const Function *F, const Function *G) {
9070b57cec5SDimitry Andric if (F->isInterposable() != G->isInterposable()) {
9080b57cec5SDimitry Andric // Strong before weak, because the weak function may call the strong
9090b57cec5SDimitry Andric // one, but not the other way around.
9100b57cec5SDimitry Andric return !F->isInterposable();
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
9130b57cec5SDimitry Andric // External before local, because we definitely have to keep the external
9140b57cec5SDimitry Andric // function, but may be able to drop the local one.
9150b57cec5SDimitry Andric return !F->hasLocalLinkage();
9160b57cec5SDimitry Andric }
9170b57cec5SDimitry Andric // Impose a total order (by name) on the replacement of functions. This is
9180b57cec5SDimitry Andric // important when operating on more than one module independently to prevent
9190b57cec5SDimitry Andric // cycles of thunks calling each other when the modules are linked together.
9200b57cec5SDimitry Andric return F->getName() <= G->getName();
9210b57cec5SDimitry Andric }
9220b57cec5SDimitry Andric
9230b57cec5SDimitry Andric // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
9240b57cec5SDimitry Andric // that was already inserted.
insert(Function * NewFunction)9250b57cec5SDimitry Andric bool MergeFunctions::insert(Function *NewFunction) {
9260b57cec5SDimitry Andric std::pair<FnTreeType::iterator, bool> Result =
9270b57cec5SDimitry Andric FnTree.insert(FunctionNode(NewFunction));
9280b57cec5SDimitry Andric
9290b57cec5SDimitry Andric if (Result.second) {
9300b57cec5SDimitry Andric assert(FNodesInTree.count(NewFunction) == 0);
9310b57cec5SDimitry Andric FNodesInTree.insert({NewFunction, Result.first});
9320b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
9330b57cec5SDimitry Andric << '\n');
9340b57cec5SDimitry Andric return false;
9350b57cec5SDimitry Andric }
9360b57cec5SDimitry Andric
9370b57cec5SDimitry Andric const FunctionNode &OldF = *Result.first;
9380b57cec5SDimitry Andric
9390b57cec5SDimitry Andric if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
9400b57cec5SDimitry Andric // Swap the two functions.
9410b57cec5SDimitry Andric Function *F = OldF.getFunc();
9420b57cec5SDimitry Andric replaceFunctionInTree(*Result.first, NewFunction);
9430b57cec5SDimitry Andric NewFunction = F;
9440b57cec5SDimitry Andric assert(OldF.getFunc() != F && "Must have swapped the functions.");
9450b57cec5SDimitry Andric }
9460b57cec5SDimitry Andric
9470b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName()
9480b57cec5SDimitry Andric << " == " << NewFunction->getName() << '\n');
9490b57cec5SDimitry Andric
9500b57cec5SDimitry Andric Function *DeleteF = NewFunction;
9510b57cec5SDimitry Andric mergeTwoFunctions(OldF.getFunc(), DeleteF);
9520b57cec5SDimitry Andric return true;
9530b57cec5SDimitry Andric }
9540b57cec5SDimitry Andric
9550b57cec5SDimitry Andric // Remove a function from FnTree. If it was already in FnTree, add
9560b57cec5SDimitry Andric // it to Deferred so that we'll look at it in the next round.
remove(Function * F)9570b57cec5SDimitry Andric void MergeFunctions::remove(Function *F) {
9580b57cec5SDimitry Andric auto I = FNodesInTree.find(F);
9590b57cec5SDimitry Andric if (I != FNodesInTree.end()) {
9600b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
9610b57cec5SDimitry Andric FnTree.erase(I->second);
9620b57cec5SDimitry Andric // I->second has been invalidated, remove it from the FNodesInTree map to
9630b57cec5SDimitry Andric // preserve the invariant.
9640b57cec5SDimitry Andric FNodesInTree.erase(I);
9650b57cec5SDimitry Andric Deferred.emplace_back(F);
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric }
9680b57cec5SDimitry Andric
9690b57cec5SDimitry Andric // For each instruction used by the value, remove() the function that contains
9700b57cec5SDimitry Andric // the instruction. This should happen right before a call to RAUW.
removeUsers(Value * V)9710b57cec5SDimitry Andric void MergeFunctions::removeUsers(Value *V) {
9720b57cec5SDimitry Andric for (User *U : V->users())
9730b57cec5SDimitry Andric if (auto *I = dyn_cast<Instruction>(U))
9740b57cec5SDimitry Andric remove(I->getFunction());
9750b57cec5SDimitry Andric }
976