LLVM API Documentation

MergeFunctions.cpp
Go to the documentation of this file.
00001 //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass looks for equivalent functions that are mergable and folds them.
00011 //
00012 // A hash is computed from the function, based on its type and number of
00013 // basic blocks.
00014 //
00015 // Once all hashes are computed, we perform an expensive equality comparison
00016 // on each function pair. This takes n^2/2 comparisons per bucket, so it's
00017 // important that the hash function be high quality. The equality comparison
00018 // iterates through each instruction in each basic block.
00019 //
00020 // When a match is found the functions are folded. If both functions are
00021 // overridable, we move the functionality into a new internal function and
00022 // leave two overridable thunks to it.
00023 //
00024 //===----------------------------------------------------------------------===//
00025 //
00026 // Future work:
00027 //
00028 // * virtual functions.
00029 //
00030 // Many functions have their address taken by the virtual function table for
00031 // the object they belong to. However, as long as it's only used for a lookup
00032 // and call, this is irrelevant, and we'd like to fold such functions.
00033 //
00034 // * switch from n^2 pair-wise comparisons to an n-way comparison for each
00035 // bucket.
00036 //
00037 // * be smarter about bitcasts.
00038 //
00039 // In order to fold functions, we will sometimes add either bitcast instructions
00040 // or bitcast constant expressions. Unfortunately, this can confound further
00041 // analysis since the two functions differ where one has a bitcast and the
00042 // other doesn't. We should learn to look through bitcasts.
00043 //
00044 //===----------------------------------------------------------------------===//
00045 
00046 #define DEBUG_TYPE "mergefunc"
00047 #include "llvm/Transforms/IPO.h"
00048 #include "llvm/ADT/DenseSet.h"
00049 #include "llvm/ADT/FoldingSet.h"
00050 #include "llvm/ADT/STLExtras.h"
00051 #include "llvm/ADT/SmallSet.h"
00052 #include "llvm/ADT/Statistic.h"
00053 #include "llvm/IR/CallSite.h"
00054 #include "llvm/IR/Constants.h"
00055 #include "llvm/IR/DataLayout.h"
00056 #include "llvm/IR/IRBuilder.h"
00057 #include "llvm/IR/InlineAsm.h"
00058 #include "llvm/IR/Instructions.h"
00059 #include "llvm/IR/LLVMContext.h"
00060 #include "llvm/IR/Module.h"
00061 #include "llvm/IR/Operator.h"
00062 #include "llvm/IR/ValueHandle.h"
00063 #include "llvm/Pass.h"
00064 #include "llvm/Support/Debug.h"
00065 #include "llvm/Support/ErrorHandling.h"
00066 #include "llvm/Support/raw_ostream.h"
00067 #include <vector>
00068 using namespace llvm;
00069 
00070 STATISTIC(NumFunctionsMerged, "Number of functions merged");
00071 STATISTIC(NumThunksWritten, "Number of thunks generated");
00072 STATISTIC(NumAliasesWritten, "Number of aliases generated");
00073 STATISTIC(NumDoubleWeak, "Number of new functions created");
00074 
00075 /// Returns the type id for a type to be hashed. We turn pointer types into
00076 /// integers here because the actual compare logic below considers pointers and
00077 /// integers of the same size as equal.
00078 static Type::TypeID getTypeIDForHash(Type *Ty) {
00079   if (Ty->isPointerTy())
00080     return Type::IntegerTyID;
00081   return Ty->getTypeID();
00082 }
00083 
00084 /// Creates a hash-code for the function which is the same for any two
00085 /// functions that will compare equal, without looking at the instructions
00086 /// inside the function.
00087 static unsigned profileFunction(const Function *F) {
00088   FunctionType *FTy = F->getFunctionType();
00089 
00090   FoldingSetNodeID ID;
00091   ID.AddInteger(F->size());
00092   ID.AddInteger(F->getCallingConv());
00093   ID.AddBoolean(F->hasGC());
00094   ID.AddBoolean(FTy->isVarArg());
00095   ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
00096   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
00097     ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
00098   return ID.ComputeHash();
00099 }
00100 
00101 namespace {
00102 
00103 /// ComparableFunction - A struct that pairs together functions with a
00104 /// DataLayout so that we can keep them together as elements in the DenseSet.
00105 class ComparableFunction {
00106 public:
00107   static const ComparableFunction EmptyKey;
00108   static const ComparableFunction TombstoneKey;
00109   static DataLayout * const LookupOnly;
00110 
00111   ComparableFunction(Function *Func, const DataLayout *DL)
00112     : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
00113 
00114   Function *getFunc() const { return Func; }
00115   unsigned getHash() const { return Hash; }
00116   const DataLayout *getDataLayout() const { return DL; }
00117 
00118   // Drops AssertingVH reference to the function. Outside of debug mode, this
00119   // does nothing.
00120   void release() {
00121     assert(Func &&
00122            "Attempted to release function twice, or release empty/tombstone!");
00123     Func = NULL;
00124   }
00125 
00126 private:
00127   explicit ComparableFunction(unsigned Hash)
00128     : Func(NULL), Hash(Hash), DL(NULL) {}
00129 
00130   AssertingVH<Function> Func;
00131   unsigned Hash;
00132   const DataLayout *DL;
00133 };
00134 
00135 const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
00136 const ComparableFunction ComparableFunction::TombstoneKey =
00137     ComparableFunction(1);
00138 DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
00139 
00140 }
00141 
00142 namespace llvm {
00143   template <>
00144   struct DenseMapInfo<ComparableFunction> {
00145     static ComparableFunction getEmptyKey() {
00146       return ComparableFunction::EmptyKey;
00147     }
00148     static ComparableFunction getTombstoneKey() {
00149       return ComparableFunction::TombstoneKey;
00150     }
00151     static unsigned getHashValue(const ComparableFunction &CF) {
00152       return CF.getHash();
00153     }
00154     static bool isEqual(const ComparableFunction &LHS,
00155                         const ComparableFunction &RHS);
00156   };
00157 }
00158 
00159 namespace {
00160 
00161 /// FunctionComparator - Compares two functions to determine whether or not
00162 /// they will generate machine code with the same behaviour. DataLayout is
00163 /// used if available. The comparator always fails conservatively (erring on the
00164 /// side of claiming that two functions are different).
00165 class FunctionComparator {
00166 public:
00167   FunctionComparator(const DataLayout *DL, const Function *F1,
00168                      const Function *F2)
00169     : F1(F1), F2(F2), DL(DL) {}
00170 
00171   /// Test whether the two functions have equivalent behaviour.
00172   bool compare();
00173 
00174 private:
00175   /// Test whether two basic blocks have equivalent behaviour.
00176   bool compare(const BasicBlock *BB1, const BasicBlock *BB2);
00177 
00178   /// Assign or look up previously assigned numbers for the two values, and
00179   /// return whether the numbers are equal. Numbers are assigned in the order
00180   /// visited.
00181   bool enumerate(const Value *V1, const Value *V2);
00182 
00183   /// Compare two Instructions for equivalence, similar to
00184   /// Instruction::isSameOperationAs but with modifications to the type
00185   /// comparison.
00186   bool isEquivalentOperation(const Instruction *I1,
00187                              const Instruction *I2) const;
00188 
00189   /// Compare two GEPs for equivalent pointer arithmetic.
00190   bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
00191   bool isEquivalentGEP(const GetElementPtrInst *GEP1,
00192                        const GetElementPtrInst *GEP2) {
00193     return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
00194   }
00195 
00196   /// cmpType - compares two types,
00197   /// defines total ordering among the types set.
00198   ///
00199   /// Return values:
00200   /// 0 if types are equal,
00201   /// -1 if Left is less than Right,
00202   /// +1 if Left is greater than Right.
00203   ///
00204   /// Description:
00205   /// Comparison is broken onto stages. Like in lexicographical comparison
00206   /// stage coming first has higher priority.
00207   /// On each explanation stage keep in mind total ordering properties.
00208   ///
00209   /// 0. Before comparison we coerce pointer types of 0 address space to
00210   /// integer.
00211   /// We also don't bother with same type at left and right, so
00212   /// just return 0 in this case.
00213   ///
00214   /// 1. If types are of different kind (different type IDs).
00215   ///    Return result of type IDs comparison, treating them as numbers.
00216   /// 2. If types are vectors or integers, compare Type* values as numbers.
00217   /// 3. Types has same ID, so check whether they belongs to the next group:
00218   /// * Void
00219   /// * Float
00220   /// * Double
00221   /// * X86_FP80
00222   /// * FP128
00223   /// * PPC_FP128
00224   /// * Label
00225   /// * Metadata
00226   /// If so - return 0, yes - we can treat these types as equal only because
00227   /// their IDs are same.
00228   /// 4. If Left and Right are pointers, return result of address space
00229   /// comparison (numbers comparison). We can treat pointer types of same
00230   /// address space as equal.
00231   /// 5. If types are complex.
00232   /// Then both Left and Right are to be expanded and their element types will
00233   /// be checked with the same way. If we get Res != 0 on some stage, return it.
00234   /// Otherwise return 0.
00235   /// 6. For all other cases put llvm_unreachable.
00236   int cmpType(Type *TyL, Type *TyR) const;
00237 
00238   bool isEquivalentType(Type *Ty1, Type *Ty2) const {
00239     return cmpType(Ty1, Ty2) == 0;
00240   }
00241 
00242   int cmpNumbers(uint64_t L, uint64_t R) const;
00243 
00244   // The two functions undergoing comparison.
00245   const Function *F1, *F2;
00246 
00247   const DataLayout *DL;
00248 
00249   DenseMap<const Value *, const Value *> id_map;
00250   DenseSet<const Value *> seen_values;
00251 };
00252 
00253 }
00254 
00255 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
00256   if (L < R) return -1;
00257   if (L > R) return 1;
00258   return 0;
00259 }
00260 
00261 /// cmpType - compares two types,
00262 /// defines total ordering among the types set.
00263 /// See method declaration comments for more details.
00264 int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
00265 
00266   PointerType *PTyL = dyn_cast<PointerType>(TyL);
00267   PointerType *PTyR = dyn_cast<PointerType>(TyR);
00268 
00269   if (DL) {
00270     if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
00271     if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
00272   }
00273 
00274   if (TyL == TyR)
00275     return 0;
00276 
00277   if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
00278     return Res;
00279 
00280   switch (TyL->getTypeID()) {
00281   default:
00282     llvm_unreachable("Unknown type!");
00283     // Fall through in Release mode.
00284   case Type::IntegerTyID:
00285   case Type::VectorTyID:
00286     // TyL == TyR would have returned true earlier.
00287     return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
00288 
00289   case Type::VoidTyID:
00290   case Type::FloatTyID:
00291   case Type::DoubleTyID:
00292   case Type::X86_FP80TyID:
00293   case Type::FP128TyID:
00294   case Type::PPC_FP128TyID:
00295   case Type::LabelTyID:
00296   case Type::MetadataTyID:
00297     return 0;
00298 
00299   case Type::PointerTyID: {
00300     assert(PTyL && PTyR && "Both types must be pointers here.");
00301     return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
00302   }
00303 
00304   case Type::StructTyID: {
00305     StructType *STyL = cast<StructType>(TyL);
00306     StructType *STyR = cast<StructType>(TyR);
00307     if (STyL->getNumElements() != STyR->getNumElements())
00308       return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
00309 
00310     if (STyL->isPacked() != STyR->isPacked())
00311       return cmpNumbers(STyL->isPacked(), STyR->isPacked());
00312 
00313     for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
00314       if (int Res = cmpType(STyL->getElementType(i),
00315                             STyR->getElementType(i)))
00316         return Res;
00317     }
00318     return 0;
00319   }
00320 
00321   case Type::FunctionTyID: {
00322     FunctionType *FTyL = cast<FunctionType>(TyL);
00323     FunctionType *FTyR = cast<FunctionType>(TyR);
00324     if (FTyL->getNumParams() != FTyR->getNumParams())
00325       return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
00326 
00327     if (FTyL->isVarArg() != FTyR->isVarArg())
00328       return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
00329 
00330     if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
00331       return Res;
00332 
00333     for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
00334       if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
00335         return Res;
00336     }
00337     return 0;
00338   }
00339 
00340   case Type::ArrayTyID: {
00341     ArrayType *ATyL = cast<ArrayType>(TyL);
00342     ArrayType *ATyR = cast<ArrayType>(TyR);
00343     if (ATyL->getNumElements() != ATyR->getNumElements())
00344       return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
00345     return cmpType(ATyL->getElementType(), ATyR->getElementType());
00346   }
00347   }
00348 }
00349 
00350 // Determine whether the two operations are the same except that pointer-to-A
00351 // and pointer-to-B are equivalent. This should be kept in sync with
00352 // Instruction::isSameOperationAs.
00353 bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
00354                                                const Instruction *I2) const {
00355   // Differences from Instruction::isSameOperationAs:
00356   //  * replace type comparison with calls to isEquivalentType.
00357   //  * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
00358   //  * because of the above, we don't test for the tail bit on calls later on
00359   if (I1->getOpcode() != I2->getOpcode() ||
00360       I1->getNumOperands() != I2->getNumOperands() ||
00361       !isEquivalentType(I1->getType(), I2->getType()) ||
00362       !I1->hasSameSubclassOptionalData(I2))
00363     return false;
00364 
00365   // We have two instructions of identical opcode and #operands.  Check to see
00366   // if all operands are the same type
00367   for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
00368     if (!isEquivalentType(I1->getOperand(i)->getType(),
00369                           I2->getOperand(i)->getType()))
00370       return false;
00371 
00372   // Check special state that is a part of some instructions.
00373   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
00374     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
00375            LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() &&
00376            LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
00377            LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
00378   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
00379     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
00380            SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() &&
00381            SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
00382            SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
00383   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
00384     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
00385   if (const CallInst *CI = dyn_cast<CallInst>(I1))
00386     return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
00387            CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
00388   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
00389     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
00390            CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes();
00391   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
00392     return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
00393   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
00394     return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
00395   if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
00396     return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
00397            FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
00398   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
00399     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
00400            CXI->getSuccessOrdering() ==
00401                cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
00402            CXI->getFailureOrdering() ==
00403                cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
00404            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
00405   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
00406     return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
00407            RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
00408            RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
00409            RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
00410 
00411   return true;
00412 }
00413 
00414 // Determine whether two GEP operations perform the same underlying arithmetic.
00415 bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
00416                                          const GEPOperator *GEP2) {
00417   unsigned AS = GEP1->getPointerAddressSpace();
00418   if (AS != GEP2->getPointerAddressSpace())
00419     return false;
00420 
00421   if (DL) {
00422     // When we have target data, we can reduce the GEP down to the value in bytes
00423     // added to the address.
00424     unsigned BitWidth = DL ? DL->getPointerSizeInBits(AS) : 1;
00425     APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
00426     if (GEP1->accumulateConstantOffset(*DL, Offset1) &&
00427         GEP2->accumulateConstantOffset(*DL, Offset2)) {
00428       return Offset1 == Offset2;
00429     }
00430   }
00431 
00432   if (GEP1->getPointerOperand()->getType() !=
00433       GEP2->getPointerOperand()->getType())
00434     return false;
00435 
00436   if (GEP1->getNumOperands() != GEP2->getNumOperands())
00437     return false;
00438 
00439   for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
00440     if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
00441       return false;
00442   }
00443 
00444   return true;
00445 }
00446 
00447 // Compare two values used by the two functions under pair-wise comparison. If
00448 // this is the first time the values are seen, they're added to the mapping so
00449 // that we will detect mismatches on next use.
00450 bool FunctionComparator::enumerate(const Value *V1, const Value *V2) {
00451   // Check for function @f1 referring to itself and function @f2 referring to
00452   // itself, or referring to each other, or both referring to either of them.
00453   // They're all equivalent if the two functions are otherwise equivalent.
00454   if (V1 == F1 && V2 == F2)
00455     return true;
00456   if (V1 == F2 && V2 == F1)
00457     return true;
00458 
00459   if (const Constant *C1 = dyn_cast<Constant>(V1)) {
00460     if (V1 == V2) return true;
00461     const Constant *C2 = dyn_cast<Constant>(V2);
00462     if (!C2) return false;
00463     // TODO: constant expressions with GEP or references to F1 or F2.
00464     if (C1->isNullValue() && C2->isNullValue() &&
00465         isEquivalentType(C1->getType(), C2->getType()))
00466       return true;
00467     // Try bitcasting C2 to C1's type. If the bitcast is legal and returns C1
00468     // then they must have equal bit patterns.
00469     return C1->getType()->canLosslesslyBitCastTo(C2->getType()) &&
00470       C1 == ConstantExpr::getBitCast(const_cast<Constant*>(C2), C1->getType());
00471   }
00472 
00473   if (isa<InlineAsm>(V1) || isa<InlineAsm>(V2))
00474     return V1 == V2;
00475 
00476   // Check that V1 maps to V2. If we find a value that V1 maps to then we simply
00477   // check whether it's equal to V2. When there is no mapping then we need to
00478   // ensure that V2 isn't already equivalent to something else. For this
00479   // purpose, we track the V2 values in a set.
00480 
00481   const Value *&map_elem = id_map[V1];
00482   if (map_elem)
00483     return map_elem == V2;
00484   if (!seen_values.insert(V2).second)
00485     return false;
00486   map_elem = V2;
00487   return true;
00488 }
00489 
00490 // Test whether two basic blocks have equivalent behaviour.
00491 bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) {
00492   BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
00493   BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
00494 
00495   do {
00496     if (!enumerate(F1I, F2I))
00497       return false;
00498 
00499     if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
00500       const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
00501       if (!GEP2)
00502         return false;
00503 
00504       if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
00505         return false;
00506 
00507       if (!isEquivalentGEP(GEP1, GEP2))
00508         return false;
00509     } else {
00510       if (!isEquivalentOperation(F1I, F2I))
00511         return false;
00512 
00513       assert(F1I->getNumOperands() == F2I->getNumOperands());
00514       for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
00515         Value *OpF1 = F1I->getOperand(i);
00516         Value *OpF2 = F2I->getOperand(i);
00517 
00518         if (!enumerate(OpF1, OpF2))
00519           return false;
00520 
00521         if (OpF1->getValueID() != OpF2->getValueID() ||
00522             !isEquivalentType(OpF1->getType(), OpF2->getType()))
00523           return false;
00524       }
00525     }
00526 
00527     ++F1I, ++F2I;
00528   } while (F1I != F1E && F2I != F2E);
00529 
00530   return F1I == F1E && F2I == F2E;
00531 }
00532 
00533 // Test whether the two functions have equivalent behaviour.
00534 bool FunctionComparator::compare() {
00535   // We need to recheck everything, but check the things that weren't included
00536   // in the hash first.
00537 
00538   if (F1->getAttributes() != F2->getAttributes())
00539     return false;
00540 
00541   if (F1->hasGC() != F2->hasGC())
00542     return false;
00543 
00544   if (F1->hasGC() && F1->getGC() != F2->getGC())
00545     return false;
00546 
00547   if (F1->hasSection() != F2->hasSection())
00548     return false;
00549 
00550   if (F1->hasSection() && F1->getSection() != F2->getSection())
00551     return false;
00552 
00553   if (F1->isVarArg() != F2->isVarArg())
00554     return false;
00555 
00556   // TODO: if it's internal and only used in direct calls, we could handle this
00557   // case too.
00558   if (F1->getCallingConv() != F2->getCallingConv())
00559     return false;
00560 
00561   if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
00562     return false;
00563 
00564   assert(F1->arg_size() == F2->arg_size() &&
00565          "Identically typed functions have different numbers of args!");
00566 
00567   // Visit the arguments so that they get enumerated in the order they're
00568   // passed in.
00569   for (Function::const_arg_iterator f1i = F1->arg_begin(),
00570          f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
00571     if (!enumerate(f1i, f2i))
00572       llvm_unreachable("Arguments repeat!");
00573   }
00574 
00575   // We do a CFG-ordered walk since the actual ordering of the blocks in the
00576   // linked list is immaterial. Our walk starts at the entry block for both
00577   // functions, then takes each block from each terminator in order. As an
00578   // artifact, this also means that unreachable blocks are ignored.
00579   SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
00580   SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
00581 
00582   F1BBs.push_back(&F1->getEntryBlock());
00583   F2BBs.push_back(&F2->getEntryBlock());
00584 
00585   VisitedBBs.insert(F1BBs[0]);
00586   while (!F1BBs.empty()) {
00587     const BasicBlock *F1BB = F1BBs.pop_back_val();
00588     const BasicBlock *F2BB = F2BBs.pop_back_val();
00589 
00590     if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
00591       return false;
00592 
00593     const TerminatorInst *F1TI = F1BB->getTerminator();
00594     const TerminatorInst *F2TI = F2BB->getTerminator();
00595 
00596     assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
00597     for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
00598       if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
00599         continue;
00600 
00601       F1BBs.push_back(F1TI->getSuccessor(i));
00602       F2BBs.push_back(F2TI->getSuccessor(i));
00603     }
00604   }
00605   return true;
00606 }
00607 
00608 namespace {
00609 
00610 /// MergeFunctions finds functions which will generate identical machine code,
00611 /// by considering all pointer types to be equivalent. Once identified,
00612 /// MergeFunctions will fold them by replacing a call to one to a call to a
00613 /// bitcast of the other.
00614 ///
00615 class MergeFunctions : public ModulePass {
00616 public:
00617   static char ID;
00618   MergeFunctions()
00619     : ModulePass(ID), HasGlobalAliases(false) {
00620     initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
00621   }
00622 
00623   bool runOnModule(Module &M) override;
00624 
00625 private:
00626   typedef DenseSet<ComparableFunction> FnSetType;
00627 
00628   /// A work queue of functions that may have been modified and should be
00629   /// analyzed again.
00630   std::vector<WeakVH> Deferred;
00631 
00632   /// Insert a ComparableFunction into the FnSet, or merge it away if it's
00633   /// equal to one that's already present.
00634   bool insert(ComparableFunction &NewF);
00635 
00636   /// Remove a Function from the FnSet and queue it up for a second sweep of
00637   /// analysis.
00638   void remove(Function *F);
00639 
00640   /// Find the functions that use this Value and remove them from FnSet and
00641   /// queue the functions.
00642   void removeUsers(Value *V);
00643 
00644   /// Replace all direct calls of Old with calls of New. Will bitcast New if
00645   /// necessary to make types match.
00646   void replaceDirectCallers(Function *Old, Function *New);
00647 
00648   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
00649   /// be converted into a thunk. In either case, it should never be visited
00650   /// again.
00651   void mergeTwoFunctions(Function *F, Function *G);
00652 
00653   /// Replace G with a thunk or an alias to F. Deletes G.
00654   void writeThunkOrAlias(Function *F, Function *G);
00655 
00656   /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
00657   /// of G with bitcast(F). Deletes G.
00658   void writeThunk(Function *F, Function *G);
00659 
00660   /// Replace G with an alias to F. Deletes G.
00661   void writeAlias(Function *F, Function *G);
00662 
00663   /// The set of all distinct functions. Use the insert() and remove() methods
00664   /// to modify it.
00665   FnSetType FnSet;
00666 
00667   /// DataLayout for more accurate GEP comparisons. May be NULL.
00668   const DataLayout *DL;
00669 
00670   /// Whether or not the target supports global aliases.
00671   bool HasGlobalAliases;
00672 };
00673 
00674 }  // end anonymous namespace
00675 
00676 char MergeFunctions::ID = 0;
00677 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
00678 
00679 ModulePass *llvm::createMergeFunctionsPass() {
00680   return new MergeFunctions();
00681 }
00682 
00683 bool MergeFunctions::runOnModule(Module &M) {
00684   bool Changed = false;
00685   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00686   DL = DLP ? &DLP->getDataLayout() : 0;
00687 
00688   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00689     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
00690       Deferred.push_back(WeakVH(I));
00691   }
00692   FnSet.resize(Deferred.size());
00693 
00694   do {
00695     std::vector<WeakVH> Worklist;
00696     Deferred.swap(Worklist);
00697 
00698     DEBUG(dbgs() << "size of module: " << M.size() << '\n');
00699     DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
00700 
00701     // Insert only strong functions and merge them. Strong function merging
00702     // always deletes one of them.
00703     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
00704            E = Worklist.end(); I != E; ++I) {
00705       if (!*I) continue;
00706       Function *F = cast<Function>(*I);
00707       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
00708           !F->mayBeOverridden()) {
00709         ComparableFunction CF = ComparableFunction(F, DL);
00710         Changed |= insert(CF);
00711       }
00712     }
00713 
00714     // Insert only weak functions and merge them. By doing these second we
00715     // create thunks to the strong function when possible. When two weak
00716     // functions are identical, we create a new strong function with two weak
00717     // weak thunks to it which are identical but not mergable.
00718     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
00719            E = Worklist.end(); I != E; ++I) {
00720       if (!*I) continue;
00721       Function *F = cast<Function>(*I);
00722       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
00723           F->mayBeOverridden()) {
00724         ComparableFunction CF = ComparableFunction(F, DL);
00725         Changed |= insert(CF);
00726       }
00727     }
00728     DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
00729   } while (!Deferred.empty());
00730 
00731   FnSet.clear();
00732 
00733   return Changed;
00734 }
00735 
00736 bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
00737                                                const ComparableFunction &RHS) {
00738   if (LHS.getFunc() == RHS.getFunc() &&
00739       LHS.getHash() == RHS.getHash())
00740     return true;
00741   if (!LHS.getFunc() || !RHS.getFunc())
00742     return false;
00743 
00744   // One of these is a special "underlying pointer comparison only" object.
00745   if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
00746       RHS.getDataLayout() == ComparableFunction::LookupOnly)
00747     return false;
00748 
00749   assert(LHS.getDataLayout() == RHS.getDataLayout() &&
00750          "Comparing functions for different targets");
00751 
00752   return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(),
00753                             RHS.getFunc()).compare();
00754 }
00755 
00756 // Replace direct callers of Old with New.
00757 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
00758   Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
00759   for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
00760     Use *U = &*UI;
00761     ++UI;
00762     CallSite CS(U->getUser());
00763     if (CS && CS.isCallee(U)) {
00764       remove(CS.getInstruction()->getParent()->getParent());
00765       U->set(BitcastNew);
00766     }
00767   }
00768 }
00769 
00770 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
00771 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
00772   if (HasGlobalAliases && G->hasUnnamedAddr()) {
00773     if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
00774         G->hasWeakLinkage()) {
00775       writeAlias(F, G);
00776       return;
00777     }
00778   }
00779 
00780   writeThunk(F, G);
00781 }
00782 
00783 // Helper for writeThunk,
00784 // Selects proper bitcast operation,
00785 // but a bit simpler then CastInst::getCastOpcode.
00786 static Value* createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
00787   Type *SrcTy = V->getType();
00788   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
00789     return Builder.CreateIntToPtr(V, DestTy);
00790   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
00791     return Builder.CreatePtrToInt(V, DestTy);
00792   else
00793     return Builder.CreateBitCast(V, DestTy);
00794 }
00795 
00796 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
00797 // of G with bitcast(F). Deletes G.
00798 void MergeFunctions::writeThunk(Function *F, Function *G) {
00799   if (!G->mayBeOverridden()) {
00800     // Redirect direct callers of G to F.
00801     replaceDirectCallers(G, F);
00802   }
00803 
00804   // If G was internal then we may have replaced all uses of G with F. If so,
00805   // stop here and delete G. There's no need for a thunk.
00806   if (G->hasLocalLinkage() && G->use_empty()) {
00807     G->eraseFromParent();
00808     return;
00809   }
00810 
00811   Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
00812                                     G->getParent());
00813   BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
00814   IRBuilder<false> Builder(BB);
00815 
00816   SmallVector<Value *, 16> Args;
00817   unsigned i = 0;
00818   FunctionType *FFTy = F->getFunctionType();
00819   for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
00820        AI != AE; ++AI) {
00821     Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
00822     ++i;
00823   }
00824 
00825   CallInst *CI = Builder.CreateCall(F, Args);
00826   CI->setTailCall();
00827   CI->setCallingConv(F->getCallingConv());
00828   if (NewG->getReturnType()->isVoidTy()) {
00829     Builder.CreateRetVoid();
00830   } else {
00831     Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
00832   }
00833 
00834   NewG->copyAttributesFrom(G);
00835   NewG->takeName(G);
00836   removeUsers(G);
00837   G->replaceAllUsesWith(NewG);
00838   G->eraseFromParent();
00839 
00840   DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
00841   ++NumThunksWritten;
00842 }
00843 
00844 // Replace G with an alias to F and delete G.
00845 void MergeFunctions::writeAlias(Function *F, Function *G) {
00846   Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
00847   GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
00848                                     BitcastF, G->getParent());
00849   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
00850   GA->takeName(G);
00851   GA->setVisibility(G->getVisibility());
00852   removeUsers(G);
00853   G->replaceAllUsesWith(GA);
00854   G->eraseFromParent();
00855 
00856   DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
00857   ++NumAliasesWritten;
00858 }
00859 
00860 // Merge two equivalent functions. Upon completion, Function G is deleted.
00861 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
00862   if (F->mayBeOverridden()) {
00863     assert(G->mayBeOverridden());
00864 
00865     if (HasGlobalAliases) {
00866       // Make them both thunks to the same internal function.
00867       Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
00868                                      F->getParent());
00869       H->copyAttributesFrom(F);
00870       H->takeName(F);
00871       removeUsers(F);
00872       F->replaceAllUsesWith(H);
00873 
00874       unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
00875 
00876       writeAlias(F, G);
00877       writeAlias(F, H);
00878 
00879       F->setAlignment(MaxAlignment);
00880       F->setLinkage(GlobalValue::PrivateLinkage);
00881     } else {
00882       // We can't merge them. Instead, pick one and update all direct callers
00883       // to call it and hope that we improve the instruction cache hit rate.
00884       replaceDirectCallers(G, F);
00885     }
00886 
00887     ++NumDoubleWeak;
00888   } else {
00889     writeThunkOrAlias(F, G);
00890   }
00891 
00892   ++NumFunctionsMerged;
00893 }
00894 
00895 // Insert a ComparableFunction into the FnSet, or merge it away if equal to one
00896 // that was already inserted.
00897 bool MergeFunctions::insert(ComparableFunction &NewF) {
00898   std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
00899   if (Result.second) {
00900     DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
00901     return false;
00902   }
00903 
00904   const ComparableFunction &OldF = *Result.first;
00905 
00906   // Don't merge tiny functions, since it can just end up making the function
00907   // larger.
00908   // FIXME: Should still merge them if they are unnamed_addr and produce an
00909   // alias.
00910   if (NewF.getFunc()->size() == 1) {
00911     if (NewF.getFunc()->front().size() <= 2) {
00912       DEBUG(dbgs() << NewF.getFunc()->getName()
00913             << " is to small to bother merging\n");
00914       return false;
00915     }
00916   }
00917 
00918   // Never thunk a strong function to a weak function.
00919   assert(!OldF.getFunc()->mayBeOverridden() ||
00920          NewF.getFunc()->mayBeOverridden());
00921 
00922   DEBUG(dbgs() << "  " << OldF.getFunc()->getName() << " == "
00923                << NewF.getFunc()->getName() << '\n');
00924 
00925   Function *DeleteF = NewF.getFunc();
00926   NewF.release();
00927   mergeTwoFunctions(OldF.getFunc(), DeleteF);
00928   return true;
00929 }
00930 
00931 // Remove a function from FnSet. If it was already in FnSet, add it to Deferred
00932 // so that we'll look at it in the next round.
00933 void MergeFunctions::remove(Function *F) {
00934   // We need to make sure we remove F, not a function "equal" to F per the
00935   // function equality comparator.
00936   //
00937   // The special "lookup only" ComparableFunction bypasses the expensive
00938   // function comparison in favour of a pointer comparison on the underlying
00939   // Function*'s.
00940   ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
00941   if (FnSet.erase(CF)) {
00942     DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
00943     Deferred.push_back(F);
00944   }
00945 }
00946 
00947 // For each instruction used by the value, remove() the function that contains
00948 // the instruction. This should happen right before a call to RAUW.
00949 void MergeFunctions::removeUsers(Value *V) {
00950   std::vector<Value *> Worklist;
00951   Worklist.push_back(V);
00952   while (!Worklist.empty()) {
00953     Value *V = Worklist.back();
00954     Worklist.pop_back();
00955 
00956     for (User *U : V->users()) {
00957       if (Instruction *I = dyn_cast<Instruction>(U)) {
00958         remove(I->getParent()->getParent());
00959       } else if (isa<GlobalValue>(U)) {
00960         // do nothing
00961       } else if (Constant *C = dyn_cast<Constant>(U)) {
00962         for (User *UU : C->users())
00963           Worklist.push_back(UU);
00964       }
00965     }
00966   }
00967 }