LLVM  mainline
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 // Order relation is defined on set of functions. It was made through
00013 // special function comparison procedure that returns
00014 // 0 when functions are equal,
00015 // -1 when Left function is less than right function, and
00016 // 1 for opposite case. We need total-ordering, so we need to maintain
00017 // four properties on the functions set:
00018 // a <= a (reflexivity)
00019 // if a <= b and b <= a then a = b (antisymmetry)
00020 // if a <= b and b <= c then a <= c (transitivity).
00021 // for all a and b: a <= b or b <= a (totality).
00022 //
00023 // Comparison iterates through each instruction in each basic block.
00024 // Functions are kept on binary tree. For each new function F we perform
00025 // lookup in binary tree.
00026 // In practice it works the following way:
00027 // -- We define Function* container class with custom "operator<" (FunctionPtr).
00028 // -- "FunctionPtr" instances are stored in std::set collection, so every
00029 //    std::set::insert operation will give you result in log(N) time.
00030 // 
00031 // As an optimization, a hash of the function structure is calculated first, and
00032 // two functions are only compared if they have the same hash. This hash is
00033 // cheap to compute, and has the property that if function F == G according to
00034 // the comparison function, then hash(F) == hash(G). This consistency property
00035 // is critical to ensuring all possible merging opportunities are exploited.
00036 // Collisions in the hash affect the speed of the pass but not the correctness
00037 // or determinism of the resulting transformation.
00038 //
00039 // When a match is found the functions are folded. If both functions are
00040 // overridable, we move the functionality into a new internal function and
00041 // leave two overridable thunks to it.
00042 //
00043 //===----------------------------------------------------------------------===//
00044 //
00045 // Future work:
00046 //
00047 // * virtual functions.
00048 //
00049 // Many functions have their address taken by the virtual function table for
00050 // the object they belong to. However, as long as it's only used for a lookup
00051 // and call, this is irrelevant, and we'd like to fold such functions.
00052 //
00053 // * be smarter about bitcasts.
00054 //
00055 // In order to fold functions, we will sometimes add either bitcast instructions
00056 // or bitcast constant expressions. Unfortunately, this can confound further
00057 // analysis since the two functions differ where one has a bitcast and the
00058 // other doesn't. We should learn to look through bitcasts.
00059 //
00060 // * Compare complex types with pointer types inside.
00061 // * Compare cross-reference cases.
00062 // * Compare complex expressions.
00063 //
00064 // All the three issues above could be described as ability to prove that
00065 // fA == fB == fC == fE == fF == fG in example below:
00066 //
00067 //  void fA() {
00068 //    fB();
00069 //  }
00070 //  void fB() {
00071 //    fA();
00072 //  }
00073 //
00074 //  void fE() {
00075 //    fF();
00076 //  }
00077 //  void fF() {
00078 //    fG();
00079 //  }
00080 //  void fG() {
00081 //    fE();
00082 //  }
00083 //
00084 // Simplest cross-reference case (fA <--> fB) was implemented in previous
00085 // versions of MergeFunctions, though it presented only in two function pairs
00086 // in test-suite (that counts >50k functions)
00087 // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
00088 // could cover much more cases.
00089 //
00090 //===----------------------------------------------------------------------===//
00091 
00092 #include "llvm/Transforms/IPO.h"
00093 #include "llvm/ADT/DenseSet.h"
00094 #include "llvm/ADT/FoldingSet.h"
00095 #include "llvm/ADT/STLExtras.h"
00096 #include "llvm/ADT/SmallSet.h"
00097 #include "llvm/ADT/Statistic.h"
00098 #include "llvm/ADT/Hashing.h"
00099 #include "llvm/IR/CallSite.h"
00100 #include "llvm/IR/Constants.h"
00101 #include "llvm/IR/DataLayout.h"
00102 #include "llvm/IR/IRBuilder.h"
00103 #include "llvm/IR/InlineAsm.h"
00104 #include "llvm/IR/Instructions.h"
00105 #include "llvm/IR/LLVMContext.h"
00106 #include "llvm/IR/Module.h"
00107 #include "llvm/IR/Operator.h"
00108 #include "llvm/IR/ValueHandle.h"
00109 #include "llvm/IR/ValueMap.h"
00110 #include "llvm/Pass.h"
00111 #include "llvm/Support/CommandLine.h"
00112 #include "llvm/Support/Debug.h"
00113 #include "llvm/Support/ErrorHandling.h"
00114 #include "llvm/Support/raw_ostream.h"
00115 #include <vector>
00116 
00117 using namespace llvm;
00118 
00119 #define DEBUG_TYPE "mergefunc"
00120 
00121 STATISTIC(NumFunctionsMerged, "Number of functions merged");
00122 STATISTIC(NumThunksWritten, "Number of thunks generated");
00123 STATISTIC(NumAliasesWritten, "Number of aliases generated");
00124 STATISTIC(NumDoubleWeak, "Number of new functions created");
00125 
00126 static cl::opt<unsigned> NumFunctionsForSanityCheck(
00127     "mergefunc-sanity",
00128     cl::desc("How many functions in module could be used for "
00129              "MergeFunctions pass sanity check. "
00130              "'0' disables this check. Works only with '-debug' key."),
00131     cl::init(0), cl::Hidden);
00132 
00133 namespace {
00134 
00135 /// GlobalNumberState assigns an integer to each global value in the program,
00136 /// which is used by the comparison routine to order references to globals. This
00137 /// state must be preserved throughout the pass, because Functions and other
00138 /// globals need to maintain their relative order. Globals are assigned a number
00139 /// when they are first visited. This order is deterministic, and so the
00140 /// assigned numbers are as well. When two functions are merged, neither number
00141 /// is updated. If the symbols are weak, this would be incorrect. If they are
00142 /// strong, then one will be replaced at all references to the other, and so
00143 /// direct callsites will now see one or the other symbol, and no update is
00144 /// necessary. Note that if we were guaranteed unique names, we could just
00145 /// compare those, but this would not work for stripped bitcodes or for those
00146 /// few symbols without a name.
00147 class GlobalNumberState {
00148   struct Config : ValueMapConfig<GlobalValue*> {
00149     enum { FollowRAUW = false };
00150   };
00151   // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW
00152   // occurs, the mapping does not change. Tracking changes is unnecessary, and
00153   // also problematic for weak symbols (which may be overwritten).
00154   typedef ValueMap<GlobalValue *, uint64_t, Config> ValueNumberMap;
00155   ValueNumberMap GlobalNumbers;
00156   // The next unused serial number to assign to a global.
00157   uint64_t NextNumber;
00158   public:
00159     GlobalNumberState() : GlobalNumbers(), NextNumber(0) {}
00160     uint64_t getNumber(GlobalValue* Global) {
00161       ValueNumberMap::iterator MapIter;
00162       bool Inserted;
00163       std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber});
00164       if (Inserted)
00165         NextNumber++;
00166       return MapIter->second;
00167     }
00168     void clear() {
00169       GlobalNumbers.clear();
00170     }
00171 };
00172 
00173 /// FunctionComparator - Compares two functions to determine whether or not
00174 /// they will generate machine code with the same behaviour. DataLayout is
00175 /// used if available. The comparator always fails conservatively (erring on the
00176 /// side of claiming that two functions are different).
00177 class FunctionComparator {
00178 public:
00179   FunctionComparator(const Function *F1, const Function *F2,
00180                      GlobalNumberState* GN)
00181       : FnL(F1), FnR(F2), GlobalNumbers(GN) {}
00182 
00183   /// Test whether the two functions have equivalent behaviour.
00184   int compare();
00185   /// Hash a function. Equivalent functions will have the same hash, and unequal
00186   /// functions will have different hashes with high probability.
00187   typedef uint64_t FunctionHash;
00188   static FunctionHash functionHash(Function &);
00189 
00190 private:
00191   /// Test whether two basic blocks have equivalent behaviour.
00192   int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR);
00193 
00194   /// Constants comparison.
00195   /// Its analog to lexicographical comparison between hypothetical numbers
00196   /// of next format:
00197   /// <bitcastability-trait><raw-bit-contents>
00198   ///
00199   /// 1. Bitcastability.
00200   /// Check whether L's type could be losslessly bitcasted to R's type.
00201   /// On this stage method, in case when lossless bitcast is not possible
00202   /// method returns -1 or 1, thus also defining which type is greater in
00203   /// context of bitcastability.
00204   /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
00205   ///          to the contents comparison.
00206   ///          If types differ, remember types comparison result and check
00207   ///          whether we still can bitcast types.
00208   /// Stage 1: Types that satisfies isFirstClassType conditions are always
00209   ///          greater then others.
00210   /// Stage 2: Vector is greater then non-vector.
00211   ///          If both types are vectors, then vector with greater bitwidth is
00212   ///          greater.
00213   ///          If both types are vectors with the same bitwidth, then types
00214   ///          are bitcastable, and we can skip other stages, and go to contents
00215   ///          comparison.
00216   /// Stage 3: Pointer types are greater than non-pointers. If both types are
00217   ///          pointers of the same address space - go to contents comparison.
00218   ///          Different address spaces: pointer with greater address space is
00219   ///          greater.
00220   /// Stage 4: Types are neither vectors, nor pointers. And they differ.
00221   ///          We don't know how to bitcast them. So, we better don't do it,
00222   ///          and return types comparison result (so it determines the
00223   ///          relationship among constants we don't know how to bitcast).
00224   ///
00225   /// Just for clearance, let's see how the set of constants could look
00226   /// on single dimension axis:
00227   ///
00228   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
00229   /// Where: NFCT - Not a FirstClassType
00230   ///        FCT - FirstClassTyp:
00231   ///
00232   /// 2. Compare raw contents.
00233   /// It ignores types on this stage and only compares bits from L and R.
00234   /// Returns 0, if L and R has equivalent contents.
00235   /// -1 or 1 if values are different.
00236   /// Pretty trivial:
00237   /// 2.1. If contents are numbers, compare numbers.
00238   ///    Ints with greater bitwidth are greater. Ints with same bitwidths
00239   ///    compared by their contents.
00240   /// 2.2. "And so on". Just to avoid discrepancies with comments
00241   /// perhaps it would be better to read the implementation itself.
00242   /// 3. And again about overall picture. Let's look back at how the ordered set
00243   /// of constants will look like:
00244   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
00245   ///
00246   /// Now look, what could be inside [FCT, "others"], for example:
00247   /// [FCT, "others"] =
00248   /// [
00249   ///   [double 0.1], [double 1.23],
00250   ///   [i32 1], [i32 2],
00251   ///   { double 1.0 },       ; StructTyID, NumElements = 1
00252   ///   { i32 1 },            ; StructTyID, NumElements = 1
00253   ///   { double 1, i32 1 },  ; StructTyID, NumElements = 2
00254   ///   { i32 1, double 1 }   ; StructTyID, NumElements = 2
00255   /// ]
00256   ///
00257   /// Let's explain the order. Float numbers will be less than integers, just
00258   /// because of cmpType terms: FloatTyID < IntegerTyID.
00259   /// Floats (with same fltSemantics) are sorted according to their value.
00260   /// Then you can see integers, and they are, like a floats,
00261   /// could be easy sorted among each others.
00262   /// The structures. Structures are grouped at the tail, again because of their
00263   /// TypeID: StructTyID > IntegerTyID > FloatTyID.
00264   /// Structures with greater number of elements are greater. Structures with
00265   /// greater elements going first are greater.
00266   /// The same logic with vectors, arrays and other possible complex types.
00267   ///
00268   /// Bitcastable constants.
00269   /// Let's assume, that some constant, belongs to some group of
00270   /// "so-called-equal" values with different types, and at the same time
00271   /// belongs to another group of constants with equal types
00272   /// and "really" equal values.
00273   ///
00274   /// Now, prove that this is impossible:
00275   ///
00276   /// If constant A with type TyA is bitcastable to B with type TyB, then:
00277   /// 1. All constants with equal types to TyA, are bitcastable to B. Since
00278   ///    those should be vectors (if TyA is vector), pointers
00279   ///    (if TyA is pointer), or else (if TyA equal to TyB), those types should
00280   ///    be equal to TyB.
00281   /// 2. All constants with non-equal, but bitcastable types to TyA, are
00282   ///    bitcastable to B.
00283   ///    Once again, just because we allow it to vectors and pointers only.
00284   ///    This statement could be expanded as below:
00285   /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
00286   ///      vector B, and thus bitcastable to B as well.
00287   /// 2.2. All pointers of the same address space, no matter what they point to,
00288   ///      bitcastable. So if C is pointer, it could be bitcasted to A and to B.
00289   /// So any constant equal or bitcastable to A is equal or bitcastable to B.
00290   /// QED.
00291   ///
00292   /// In another words, for pointers and vectors, we ignore top-level type and
00293   /// look at their particular properties (bit-width for vectors, and
00294   /// address space for pointers).
00295   /// If these properties are equal - compare their contents.
00296   int cmpConstants(const Constant *L, const Constant *R);
00297 
00298   /// Compares two global values by number. Uses the GlobalNumbersState to
00299   /// identify the same gobals across function calls.
00300   int cmpGlobalValues(GlobalValue *L, GlobalValue *R);
00301 
00302   /// Assign or look up previously assigned numbers for the two values, and
00303   /// return whether the numbers are equal. Numbers are assigned in the order
00304   /// visited.
00305   /// Comparison order:
00306   /// Stage 0: Value that is function itself is always greater then others.
00307   ///          If left and right values are references to their functions, then
00308   ///          they are equal.
00309   /// Stage 1: Constants are greater than non-constants.
00310   ///          If both left and right are constants, then the result of
00311   ///          cmpConstants is used as cmpValues result.
00312   /// Stage 2: InlineAsm instances are greater than others. If both left and
00313   ///          right are InlineAsm instances, InlineAsm* pointers casted to
00314   ///          integers and compared as numbers.
00315   /// Stage 3: For all other cases we compare order we meet these values in
00316   ///          their functions. If right value was met first during scanning,
00317   ///          then left value is greater.
00318   ///          In another words, we compare serial numbers, for more details
00319   ///          see comments for sn_mapL and sn_mapR.
00320   int cmpValues(const Value *L, const Value *R);
00321 
00322   /// Compare two Instructions for equivalence, similar to
00323   /// Instruction::isSameOperationAs but with modifications to the type
00324   /// comparison.
00325   /// Stages are listed in "most significant stage first" order:
00326   /// On each stage below, we do comparison between some left and right
00327   /// operation parts. If parts are non-equal, we assign parts comparison
00328   /// result to the operation comparison result and exit from method.
00329   /// Otherwise we proceed to the next stage.
00330   /// Stages:
00331   /// 1. Operations opcodes. Compared as numbers.
00332   /// 2. Number of operands.
00333   /// 3. Operation types. Compared with cmpType method.
00334   /// 4. Compare operation subclass optional data as stream of bytes:
00335   /// just convert it to integers and call cmpNumbers.
00336   /// 5. Compare in operation operand types with cmpType in
00337   /// most significant operand first order.
00338   /// 6. Last stage. Check operations for some specific attributes.
00339   /// For example, for Load it would be:
00340   /// 6.1.Load: volatile (as boolean flag)
00341   /// 6.2.Load: alignment (as integer numbers)
00342   /// 6.3.Load: synch-scope (as integer numbers)
00343   /// 6.4.Load: range metadata (as integer numbers)
00344   /// On this stage its better to see the code, since its not more than 10-15
00345   /// strings for particular instruction, and could change sometimes.
00346   int cmpOperations(const Instruction *L, const Instruction *R) const;
00347 
00348   /// Compare two GEPs for equivalent pointer arithmetic.
00349   /// Parts to be compared for each comparison stage,
00350   /// most significant stage first:
00351   /// 1. Address space. As numbers.
00352   /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
00353   /// 3. Pointer operand type (using cmpType method).
00354   /// 4. Number of operands.
00355   /// 5. Compare operands, using cmpValues method.
00356   int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR);
00357   int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
00358     return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
00359   }
00360 
00361   /// cmpType - compares two types,
00362   /// defines total ordering among the types set.
00363   ///
00364   /// Return values:
00365   /// 0 if types are equal,
00366   /// -1 if Left is less than Right,
00367   /// +1 if Left is greater than Right.
00368   ///
00369   /// Description:
00370   /// Comparison is broken onto stages. Like in lexicographical comparison
00371   /// stage coming first has higher priority.
00372   /// On each explanation stage keep in mind total ordering properties.
00373   ///
00374   /// 0. Before comparison we coerce pointer types of 0 address space to
00375   /// integer.
00376   /// We also don't bother with same type at left and right, so
00377   /// just return 0 in this case.
00378   ///
00379   /// 1. If types are of different kind (different type IDs).
00380   ///    Return result of type IDs comparison, treating them as numbers.
00381   /// 2. If types are integers, check that they have the same width. If they
00382   /// are vectors, check that they have the same count and subtype.
00383   /// 3. Types have the same ID, so check whether they are one of:
00384   /// * Void
00385   /// * Float
00386   /// * Double
00387   /// * X86_FP80
00388   /// * FP128
00389   /// * PPC_FP128
00390   /// * Label
00391   /// * Metadata
00392   /// We can treat these types as equal whenever their IDs are same.
00393   /// 4. If Left and Right are pointers, return result of address space
00394   /// comparison (numbers comparison). We can treat pointer types of same
00395   /// address space as equal.
00396   /// 5. If types are complex.
00397   /// Then both Left and Right are to be expanded and their element types will
00398   /// be checked with the same way. If we get Res != 0 on some stage, return it.
00399   /// Otherwise return 0.
00400   /// 6. For all other cases put llvm_unreachable.
00401   int cmpTypes(Type *TyL, Type *TyR) const;
00402 
00403   int cmpNumbers(uint64_t L, uint64_t R) const;
00404   int cmpAPInts(const APInt &L, const APInt &R) const;
00405   int cmpAPFloats(const APFloat &L, const APFloat &R) const;
00406   int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const;
00407   int cmpMem(StringRef L, StringRef R) const;
00408   int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
00409   int cmpRangeMetadata(const MDNode* L, const MDNode* R) const;
00410   int cmpOperandBundlesSchema(const Instruction *L, const Instruction *R) const;
00411 
00412   // The two functions undergoing comparison.
00413   const Function *FnL, *FnR;
00414 
00415   /// Assign serial numbers to values from left function, and values from
00416   /// right function.
00417   /// Explanation:
00418   /// Being comparing functions we need to compare values we meet at left and
00419   /// right sides.
00420   /// Its easy to sort things out for external values. It just should be
00421   /// the same value at left and right.
00422   /// But for local values (those were introduced inside function body)
00423   /// we have to ensure they were introduced at exactly the same place,
00424   /// and plays the same role.
00425   /// Let's assign serial number to each value when we meet it first time.
00426   /// Values that were met at same place will be with same serial numbers.
00427   /// In this case it would be good to explain few points about values assigned
00428   /// to BBs and other ways of implementation (see below).
00429   ///
00430   /// 1. Safety of BB reordering.
00431   /// It's safe to change the order of BasicBlocks in function.
00432   /// Relationship with other functions and serial numbering will not be
00433   /// changed in this case.
00434   /// As follows from FunctionComparator::compare(), we do CFG walk: we start
00435   /// from the entry, and then take each terminator. So it doesn't matter how in
00436   /// fact BBs are ordered in function. And since cmpValues are called during
00437   /// this walk, the numbering depends only on how BBs located inside the CFG.
00438   /// So the answer is - yes. We will get the same numbering.
00439   ///
00440   /// 2. Impossibility to use dominance properties of values.
00441   /// If we compare two instruction operands: first is usage of local
00442   /// variable AL from function FL, and second is usage of local variable AR
00443   /// from FR, we could compare their origins and check whether they are
00444   /// defined at the same place.
00445   /// But, we are still not able to compare operands of PHI nodes, since those
00446   /// could be operands from further BBs we didn't scan yet.
00447   /// So it's impossible to use dominance properties in general.
00448   DenseMap<const Value*, int> sn_mapL, sn_mapR;
00449 
00450   // The global state we will use
00451   GlobalNumberState* GlobalNumbers;
00452 };
00453 
00454 class FunctionNode {
00455   mutable AssertingVH<Function> F;
00456   FunctionComparator::FunctionHash Hash;
00457 public:
00458   // Note the hash is recalculated potentially multiple times, but it is cheap.
00459   FunctionNode(Function *F)
00460     : F(F), Hash(FunctionComparator::functionHash(*F))  {}
00461   Function *getFunc() const { return F; }
00462   FunctionComparator::FunctionHash getHash() const { return Hash; }
00463 
00464   /// Replace the reference to the function F by the function G, assuming their
00465   /// implementations are equal.
00466   void replaceBy(Function *G) const {
00467     F = G;
00468   }
00469 
00470   void release() { F = nullptr; }
00471 };
00472 } // end anonymous namespace
00473 
00474 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
00475   if (L < R) return -1;
00476   if (L > R) return 1;
00477   return 0;
00478 }
00479 
00480 int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
00481   if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
00482     return Res;
00483   if (L.ugt(R)) return 1;
00484   if (R.ugt(L)) return -1;
00485   return 0;
00486 }
00487 
00488 int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
00489   // Floats are ordered first by semantics (i.e. float, double, half, etc.),
00490   // then by value interpreted as a bitstring (aka APInt).
00491   const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics();
00492   if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL),
00493                            APFloat::semanticsPrecision(SR)))
00494     return Res;
00495   if (int Res = cmpNumbers(APFloat::semanticsMaxExponent(SL),
00496                            APFloat::semanticsMaxExponent(SR)))
00497     return Res;
00498   if (int Res = cmpNumbers(APFloat::semanticsMinExponent(SL),
00499                            APFloat::semanticsMinExponent(SR)))
00500     return Res;
00501   if (int Res = cmpNumbers(APFloat::semanticsSizeInBits(SL),
00502                            APFloat::semanticsSizeInBits(SR)))
00503     return Res;
00504   return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
00505 }
00506 
00507 int FunctionComparator::cmpMem(StringRef L, StringRef R) const {
00508   // Prevent heavy comparison, compare sizes first.
00509   if (int Res = cmpNumbers(L.size(), R.size()))
00510     return Res;
00511 
00512   // Compare strings lexicographically only when it is necessary: only when
00513   // strings are equal in size.
00514   return L.compare(R);
00515 }
00516 
00517 int FunctionComparator::cmpAttrs(const AttributeSet L,
00518                                  const AttributeSet R) const {
00519   if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
00520     return Res;
00521 
00522   for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
00523     AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
00524                            RE = R.end(i);
00525     for (; LI != LE && RI != RE; ++LI, ++RI) {
00526       Attribute LA = *LI;
00527       Attribute RA = *RI;
00528       if (LA < RA)
00529         return -1;
00530       if (RA < LA)
00531         return 1;
00532     }
00533     if (LI != LE)
00534       return 1;
00535     if (RI != RE)
00536       return -1;
00537   }
00538   return 0;
00539 }
00540 
00541 int FunctionComparator::cmpRangeMetadata(const MDNode* L,
00542                                          const MDNode* R) const {
00543   if (L == R)
00544     return 0;
00545   if (!L)
00546     return -1;
00547   if (!R)
00548     return 1;
00549   // Range metadata is a sequence of numbers. Make sure they are the same
00550   // sequence. 
00551   // TODO: Note that as this is metadata, it is possible to drop and/or merge
00552   // this data when considering functions to merge. Thus this comparison would
00553   // return 0 (i.e. equivalent), but merging would become more complicated
00554   // because the ranges would need to be unioned. It is not likely that
00555   // functions differ ONLY in this metadata if they are actually the same
00556   // function semantically.
00557   if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
00558     return Res;
00559   for (size_t I = 0; I < L->getNumOperands(); ++I) {
00560     ConstantInt* LLow = mdconst::extract<ConstantInt>(L->getOperand(I));
00561     ConstantInt* RLow = mdconst::extract<ConstantInt>(R->getOperand(I));
00562     if (int Res = cmpAPInts(LLow->getValue(), RLow->getValue()))
00563       return Res;
00564   }
00565   return 0;
00566 }
00567 
00568 int FunctionComparator::cmpOperandBundlesSchema(const Instruction *L,
00569                                                 const Instruction *R) const {
00570   ImmutableCallSite LCS(L);
00571   ImmutableCallSite RCS(R);
00572 
00573   assert(LCS && RCS && "Must be calls or invokes!");
00574   assert(LCS.isCall() == RCS.isCall() && "Can't compare otherwise!");
00575 
00576   if (int Res =
00577           cmpNumbers(LCS.getNumOperandBundles(), RCS.getNumOperandBundles()))
00578     return Res;
00579 
00580   for (unsigned i = 0, e = LCS.getNumOperandBundles(); i != e; ++i) {
00581     auto OBL = LCS.getOperandBundleAt(i);
00582     auto OBR = RCS.getOperandBundleAt(i);
00583 
00584     if (int Res = OBL.getTagName().compare(OBR.getTagName()))
00585       return Res;
00586 
00587     if (int Res = cmpNumbers(OBL.Inputs.size(), OBR.Inputs.size()))
00588       return Res;
00589   }
00590 
00591   return 0;
00592 }
00593 
00594 /// Constants comparison:
00595 /// 1. Check whether type of L constant could be losslessly bitcasted to R
00596 /// type.
00597 /// 2. Compare constant contents.
00598 /// For more details see declaration comments.
00599 int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
00600 
00601   Type *TyL = L->getType();
00602   Type *TyR = R->getType();
00603 
00604   // Check whether types are bitcastable. This part is just re-factored
00605   // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
00606   // we also pack into result which type is "less" for us.
00607   int TypesRes = cmpTypes(TyL, TyR);
00608   if (TypesRes != 0) {
00609     // Types are different, but check whether we can bitcast them.
00610     if (!TyL->isFirstClassType()) {
00611       if (TyR->isFirstClassType())
00612         return -1;
00613       // Neither TyL nor TyR are values of first class type. Return the result
00614       // of comparing the types
00615       return TypesRes;
00616     }
00617     if (!TyR->isFirstClassType()) {
00618       if (TyL->isFirstClassType())
00619         return 1;
00620       return TypesRes;
00621     }
00622 
00623     // Vector -> Vector conversions are always lossless if the two vector types
00624     // have the same size, otherwise not.
00625     unsigned TyLWidth = 0;
00626     unsigned TyRWidth = 0;
00627 
00628     if (auto *VecTyL = dyn_cast<VectorType>(TyL))
00629       TyLWidth = VecTyL->getBitWidth();
00630     if (auto *VecTyR = dyn_cast<VectorType>(TyR))
00631       TyRWidth = VecTyR->getBitWidth();
00632 
00633     if (TyLWidth != TyRWidth)
00634       return cmpNumbers(TyLWidth, TyRWidth);
00635 
00636     // Zero bit-width means neither TyL nor TyR are vectors.
00637     if (!TyLWidth) {
00638       PointerType *PTyL = dyn_cast<PointerType>(TyL);
00639       PointerType *PTyR = dyn_cast<PointerType>(TyR);
00640       if (PTyL && PTyR) {
00641         unsigned AddrSpaceL = PTyL->getAddressSpace();
00642         unsigned AddrSpaceR = PTyR->getAddressSpace();
00643         if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
00644           return Res;
00645       }
00646       if (PTyL)
00647         return 1;
00648       if (PTyR)
00649         return -1;
00650 
00651       // TyL and TyR aren't vectors, nor pointers. We don't know how to
00652       // bitcast them.
00653       return TypesRes;
00654     }
00655   }
00656 
00657   // OK, types are bitcastable, now check constant contents.
00658 
00659   if (L->isNullValue() && R->isNullValue())
00660     return TypesRes;
00661   if (L->isNullValue() && !R->isNullValue())
00662     return 1;
00663   if (!L->isNullValue() && R->isNullValue())
00664     return -1;
00665 
00666   auto GlobalValueL = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(L));
00667   auto GlobalValueR = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(R));
00668   if (GlobalValueL && GlobalValueR) {
00669     return cmpGlobalValues(GlobalValueL, GlobalValueR);
00670   }
00671 
00672   if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
00673     return Res;
00674 
00675   if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) {
00676     const auto *SeqR = cast<ConstantDataSequential>(R);
00677     // This handles ConstantDataArray and ConstantDataVector. Note that we
00678     // compare the two raw data arrays, which might differ depending on the host
00679     // endianness. This isn't a problem though, because the endiness of a module
00680     // will affect the order of the constants, but this order is the same
00681     // for a given input module and host platform.
00682     return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues());
00683   }
00684 
00685   switch (L->getValueID()) {
00686   case Value::UndefValueVal:
00687   case Value::ConstantTokenNoneVal:
00688     return TypesRes;
00689   case Value::ConstantIntVal: {
00690     const APInt &LInt = cast<ConstantInt>(L)->getValue();
00691     const APInt &RInt = cast<ConstantInt>(R)->getValue();
00692     return cmpAPInts(LInt, RInt);
00693   }
00694   case Value::ConstantFPVal: {
00695     const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
00696     const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
00697     return cmpAPFloats(LAPF, RAPF);
00698   }
00699   case Value::ConstantArrayVal: {
00700     const ConstantArray *LA = cast<ConstantArray>(L);
00701     const ConstantArray *RA = cast<ConstantArray>(R);
00702     uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
00703     uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
00704     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
00705       return Res;
00706     for (uint64_t i = 0; i < NumElementsL; ++i) {
00707       if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
00708                                  cast<Constant>(RA->getOperand(i))))
00709         return Res;
00710     }
00711     return 0;
00712   }
00713   case Value::ConstantStructVal: {
00714     const ConstantStruct *LS = cast<ConstantStruct>(L);
00715     const ConstantStruct *RS = cast<ConstantStruct>(R);
00716     unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
00717     unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
00718     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
00719       return Res;
00720     for (unsigned i = 0; i != NumElementsL; ++i) {
00721       if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
00722                                  cast<Constant>(RS->getOperand(i))))
00723         return Res;
00724     }
00725     return 0;
00726   }
00727   case Value::ConstantVectorVal: {
00728     const ConstantVector *LV = cast<ConstantVector>(L);
00729     const ConstantVector *RV = cast<ConstantVector>(R);
00730     unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
00731     unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
00732     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
00733       return Res;
00734     for (uint64_t i = 0; i < NumElementsL; ++i) {
00735       if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
00736                                  cast<Constant>(RV->getOperand(i))))
00737         return Res;
00738     }
00739     return 0;
00740   }
00741   case Value::ConstantExprVal: {
00742     const ConstantExpr *LE = cast<ConstantExpr>(L);
00743     const ConstantExpr *RE = cast<ConstantExpr>(R);
00744     unsigned NumOperandsL = LE->getNumOperands();
00745     unsigned NumOperandsR = RE->getNumOperands();
00746     if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
00747       return Res;
00748     for (unsigned i = 0; i < NumOperandsL; ++i) {
00749       if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
00750                                  cast<Constant>(RE->getOperand(i))))
00751         return Res;
00752     }
00753     return 0;
00754   }
00755   case Value::BlockAddressVal: {
00756     const BlockAddress *LBA = cast<BlockAddress>(L);
00757     const BlockAddress *RBA = cast<BlockAddress>(R);
00758     if (int Res = cmpValues(LBA->getFunction(), RBA->getFunction()))
00759       return Res;
00760     if (LBA->getFunction() == RBA->getFunction()) {
00761       // They are BBs in the same function. Order by which comes first in the
00762       // BB order of the function. This order is deterministic.
00763       Function* F = LBA->getFunction();
00764       BasicBlock *LBB = LBA->getBasicBlock();
00765       BasicBlock *RBB = RBA->getBasicBlock();
00766       if (LBB == RBB)
00767         return 0;
00768       for(BasicBlock &BB : F->getBasicBlockList()) {
00769         if (&BB == LBB) {
00770           assert(&BB != RBB);
00771           return -1;
00772         }
00773         if (&BB == RBB)
00774           return 1;
00775       }
00776       llvm_unreachable("Basic Block Address does not point to a basic block in "
00777                        "its function.");
00778       return -1;
00779     } else {
00780       // cmpValues said the functions are the same. So because they aren't
00781       // literally the same pointer, they must respectively be the left and
00782       // right functions.
00783       assert(LBA->getFunction() == FnL && RBA->getFunction() == FnR);
00784       // cmpValues will tell us if these are equivalent BasicBlocks, in the
00785       // context of their respective functions.
00786       return cmpValues(LBA->getBasicBlock(), RBA->getBasicBlock());
00787     }
00788   }
00789   default: // Unknown constant, abort.
00790     DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n");
00791     llvm_unreachable("Constant ValueID not recognized.");
00792     return -1;
00793   }
00794 }
00795 
00796 int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue* R) {
00797   return cmpNumbers(GlobalNumbers->getNumber(L), GlobalNumbers->getNumber(R));
00798 }
00799 
00800 /// cmpType - compares two types,
00801 /// defines total ordering among the types set.
00802 /// See method declaration comments for more details.
00803 int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
00804   PointerType *PTyL = dyn_cast<PointerType>(TyL);
00805   PointerType *PTyR = dyn_cast<PointerType>(TyR);
00806 
00807   const DataLayout &DL = FnL->getParent()->getDataLayout();
00808   if (PTyL && PTyL->getAddressSpace() == 0)
00809     TyL = DL.getIntPtrType(TyL);
00810   if (PTyR && PTyR->getAddressSpace() == 0)
00811     TyR = DL.getIntPtrType(TyR);
00812 
00813   if (TyL == TyR)
00814     return 0;
00815 
00816   if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
00817     return Res;
00818 
00819   switch (TyL->getTypeID()) {
00820   default:
00821     llvm_unreachable("Unknown type!");
00822     // Fall through in Release mode.
00823   case Type::IntegerTyID:
00824     return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(),
00825                       cast<IntegerType>(TyR)->getBitWidth());
00826   case Type::VectorTyID: {
00827     VectorType *VTyL = cast<VectorType>(TyL), *VTyR = cast<VectorType>(TyR);
00828     if (int Res = cmpNumbers(VTyL->getNumElements(), VTyR->getNumElements()))
00829       return Res;
00830     return cmpTypes(VTyL->getElementType(), VTyR->getElementType());
00831   }
00832   // TyL == TyR would have returned true earlier, because types are uniqued.
00833   case Type::VoidTyID:
00834   case Type::FloatTyID:
00835   case Type::DoubleTyID:
00836   case Type::X86_FP80TyID:
00837   case Type::FP128TyID:
00838   case Type::PPC_FP128TyID:
00839   case Type::LabelTyID:
00840   case Type::MetadataTyID:
00841   case Type::TokenTyID:
00842     return 0;
00843 
00844   case Type::PointerTyID: {
00845     assert(PTyL && PTyR && "Both types must be pointers here.");
00846     return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
00847   }
00848 
00849   case Type::StructTyID: {
00850     StructType *STyL = cast<StructType>(TyL);
00851     StructType *STyR = cast<StructType>(TyR);
00852     if (STyL->getNumElements() != STyR->getNumElements())
00853       return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
00854 
00855     if (STyL->isPacked() != STyR->isPacked())
00856       return cmpNumbers(STyL->isPacked(), STyR->isPacked());
00857 
00858     for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
00859       if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
00860         return Res;
00861     }
00862     return 0;
00863   }
00864 
00865   case Type::FunctionTyID: {
00866     FunctionType *FTyL = cast<FunctionType>(TyL);
00867     FunctionType *FTyR = cast<FunctionType>(TyR);
00868     if (FTyL->getNumParams() != FTyR->getNumParams())
00869       return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
00870 
00871     if (FTyL->isVarArg() != FTyR->isVarArg())
00872       return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
00873 
00874     if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
00875       return Res;
00876 
00877     for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
00878       if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
00879         return Res;
00880     }
00881     return 0;
00882   }
00883 
00884   case Type::ArrayTyID: {
00885     ArrayType *ATyL = cast<ArrayType>(TyL);
00886     ArrayType *ATyR = cast<ArrayType>(TyR);
00887     if (ATyL->getNumElements() != ATyR->getNumElements())
00888       return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
00889     return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
00890   }
00891   }
00892 }
00893 
00894 // Determine whether the two operations are the same except that pointer-to-A
00895 // and pointer-to-B are equivalent. This should be kept in sync with
00896 // Instruction::isSameOperationAs.
00897 // Read method declaration comments for more details.
00898 int FunctionComparator::cmpOperations(const Instruction *L,
00899                                       const Instruction *R) const {
00900   // Differences from Instruction::isSameOperationAs:
00901   //  * replace type comparison with calls to isEquivalentType.
00902   //  * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
00903   //  * because of the above, we don't test for the tail bit on calls later on
00904   if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
00905     return Res;
00906 
00907   if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
00908     return Res;
00909 
00910   if (int Res = cmpTypes(L->getType(), R->getType()))
00911     return Res;
00912 
00913   if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
00914                            R->getRawSubclassOptionalData()))
00915     return Res;
00916 
00917   if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
00918     if (int Res = cmpTypes(AI->getAllocatedType(),
00919                            cast<AllocaInst>(R)->getAllocatedType()))
00920       return Res;
00921     if (int Res =
00922             cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment()))
00923       return Res;
00924   }
00925 
00926   // We have two instructions of identical opcode and #operands.  Check to see
00927   // if all operands are the same type
00928   for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
00929     if (int Res =
00930             cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
00931       return Res;
00932   }
00933 
00934   // Check special state that is a part of some instructions.
00935   if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
00936     if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
00937       return Res;
00938     if (int Res =
00939             cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
00940       return Res;
00941     if (int Res =
00942             cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
00943       return Res;
00944     if (int Res =
00945             cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
00946       return Res;
00947     return cmpRangeMetadata(LI->getMetadata(LLVMContext::MD_range),
00948         cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
00949   }
00950   if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
00951     if (int Res =
00952             cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
00953       return Res;
00954     if (int Res =
00955             cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
00956       return Res;
00957     if (int Res =
00958             cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
00959       return Res;
00960     return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
00961   }
00962   if (const CmpInst *CI = dyn_cast<CmpInst>(L))
00963     return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
00964   if (const CallInst *CI = dyn_cast<CallInst>(L)) {
00965     if (int Res = cmpNumbers(CI->getCallingConv(),
00966                              cast<CallInst>(R)->getCallingConv()))
00967       return Res;
00968     if (int Res =
00969             cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
00970       return Res;
00971     if (int Res = cmpOperandBundlesSchema(CI, R))
00972       return Res;
00973     return cmpRangeMetadata(
00974         CI->getMetadata(LLVMContext::MD_range),
00975         cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
00976   }
00977   if (const InvokeInst *II = dyn_cast<InvokeInst>(L)) {
00978     if (int Res = cmpNumbers(II->getCallingConv(),
00979                              cast<InvokeInst>(R)->getCallingConv()))
00980       return Res;
00981     if (int Res =
00982             cmpAttrs(II->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
00983       return Res;
00984     if (int Res = cmpOperandBundlesSchema(II, R))
00985       return Res;
00986     return cmpRangeMetadata(
00987         II->getMetadata(LLVMContext::MD_range),
00988         cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
00989   }
00990   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
00991     ArrayRef<unsigned> LIndices = IVI->getIndices();
00992     ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
00993     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
00994       return Res;
00995     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
00996       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
00997         return Res;
00998     }
00999   }
01000   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
01001     ArrayRef<unsigned> LIndices = EVI->getIndices();
01002     ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
01003     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
01004       return Res;
01005     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
01006       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
01007         return Res;
01008     }
01009   }
01010   if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
01011     if (int Res =
01012             cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
01013       return Res;
01014     return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
01015   }
01016 
01017   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
01018     if (int Res = cmpNumbers(CXI->isVolatile(),
01019                              cast<AtomicCmpXchgInst>(R)->isVolatile()))
01020       return Res;
01021     if (int Res = cmpNumbers(CXI->isWeak(),
01022                              cast<AtomicCmpXchgInst>(R)->isWeak()))
01023       return Res;
01024     if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
01025                              cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
01026       return Res;
01027     if (int Res = cmpNumbers(CXI->getFailureOrdering(),
01028                              cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
01029       return Res;
01030     return cmpNumbers(CXI->getSynchScope(),
01031                       cast<AtomicCmpXchgInst>(R)->getSynchScope());
01032   }
01033   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
01034     if (int Res = cmpNumbers(RMWI->getOperation(),
01035                              cast<AtomicRMWInst>(R)->getOperation()))
01036       return Res;
01037     if (int Res = cmpNumbers(RMWI->isVolatile(),
01038                              cast<AtomicRMWInst>(R)->isVolatile()))
01039       return Res;
01040     if (int Res = cmpNumbers(RMWI->getOrdering(),
01041                              cast<AtomicRMWInst>(R)->getOrdering()))
01042       return Res;
01043     return cmpNumbers(RMWI->getSynchScope(),
01044                       cast<AtomicRMWInst>(R)->getSynchScope());
01045   }
01046   return 0;
01047 }
01048 
01049 // Determine whether two GEP operations perform the same underlying arithmetic.
01050 // Read method declaration comments for more details.
01051 int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
01052                                const GEPOperator *GEPR) {
01053 
01054   unsigned int ASL = GEPL->getPointerAddressSpace();
01055   unsigned int ASR = GEPR->getPointerAddressSpace();
01056 
01057   if (int Res = cmpNumbers(ASL, ASR))
01058     return Res;
01059 
01060   // When we have target data, we can reduce the GEP down to the value in bytes
01061   // added to the address.
01062   const DataLayout &DL = FnL->getParent()->getDataLayout();
01063   unsigned BitWidth = DL.getPointerSizeInBits(ASL);
01064   APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
01065   if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
01066       GEPR->accumulateConstantOffset(DL, OffsetR))
01067     return cmpAPInts(OffsetL, OffsetR);
01068   if (int Res = cmpTypes(GEPL->getSourceElementType(),
01069                          GEPR->getSourceElementType()))
01070     return Res;
01071 
01072   if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
01073     return Res;
01074 
01075   for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
01076     if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
01077       return Res;
01078   }
01079 
01080   return 0;
01081 }
01082 
01083 int FunctionComparator::cmpInlineAsm(const InlineAsm *L,
01084                                      const InlineAsm *R) const {
01085   // InlineAsm's are uniqued. If they are the same pointer, obviously they are
01086   // the same, otherwise compare the fields.
01087   if (L == R)
01088     return 0;
01089   if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType()))
01090     return Res;
01091   if (int Res = cmpMem(L->getAsmString(), R->getAsmString()))
01092     return Res;
01093   if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString()))
01094     return Res;
01095   if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects()))
01096     return Res;
01097   if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack()))
01098     return Res;
01099   if (int Res = cmpNumbers(L->getDialect(), R->getDialect()))
01100     return Res;
01101   llvm_unreachable("InlineAsm blocks were not uniqued.");
01102   return 0;
01103 }
01104 
01105 /// Compare two values used by the two functions under pair-wise comparison. If
01106 /// this is the first time the values are seen, they're added to the mapping so
01107 /// that we will detect mismatches on next use.
01108 /// See comments in declaration for more details.
01109 int FunctionComparator::cmpValues(const Value *L, const Value *R) {
01110   // Catch self-reference case.
01111   if (L == FnL) {
01112     if (R == FnR)
01113       return 0;
01114     return -1;
01115   }
01116   if (R == FnR) {
01117     if (L == FnL)
01118       return 0;
01119     return 1;
01120   }
01121 
01122   const Constant *ConstL = dyn_cast<Constant>(L);
01123   const Constant *ConstR = dyn_cast<Constant>(R);
01124   if (ConstL && ConstR) {
01125     if (L == R)
01126       return 0;
01127     return cmpConstants(ConstL, ConstR);
01128   }
01129 
01130   if (ConstL)
01131     return 1;
01132   if (ConstR)
01133     return -1;
01134 
01135   const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
01136   const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
01137 
01138   if (InlineAsmL && InlineAsmR)
01139     return cmpInlineAsm(InlineAsmL, InlineAsmR);
01140   if (InlineAsmL)
01141     return 1;
01142   if (InlineAsmR)
01143     return -1;
01144 
01145   auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
01146        RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
01147 
01148   return cmpNumbers(LeftSN.first->second, RightSN.first->second);
01149 }
01150 // Test whether two basic blocks have equivalent behaviour.
01151 int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL,
01152                                        const BasicBlock *BBR) {
01153   BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
01154   BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
01155 
01156   do {
01157     if (int Res = cmpValues(&*InstL, &*InstR))
01158       return Res;
01159 
01160     const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
01161     const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
01162 
01163     if (GEPL && !GEPR)
01164       return 1;
01165     if (GEPR && !GEPL)
01166       return -1;
01167 
01168     if (GEPL && GEPR) {
01169       if (int Res =
01170               cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
01171         return Res;
01172       if (int Res = cmpGEPs(GEPL, GEPR))
01173         return Res;
01174     } else {
01175       if (int Res = cmpOperations(&*InstL, &*InstR))
01176         return Res;
01177       assert(InstL->getNumOperands() == InstR->getNumOperands());
01178 
01179       for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
01180         Value *OpL = InstL->getOperand(i);
01181         Value *OpR = InstR->getOperand(i);
01182         if (int Res = cmpValues(OpL, OpR))
01183           return Res;
01184         // cmpValues should ensure this is true.
01185         assert(cmpTypes(OpL->getType(), OpR->getType()) == 0);
01186       }
01187     }
01188 
01189     ++InstL, ++InstR;
01190   } while (InstL != InstLE && InstR != InstRE);
01191 
01192   if (InstL != InstLE && InstR == InstRE)
01193     return 1;
01194   if (InstL == InstLE && InstR != InstRE)
01195     return -1;
01196   return 0;
01197 }
01198 
01199 // Test whether the two functions have equivalent behaviour.
01200 int FunctionComparator::compare() {
01201   sn_mapL.clear();
01202   sn_mapR.clear();
01203 
01204   if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
01205     return Res;
01206 
01207   if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
01208     return Res;
01209 
01210   if (FnL->hasGC()) {
01211     if (int Res = cmpMem(FnL->getGC(), FnR->getGC()))
01212       return Res;
01213   }
01214 
01215   if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
01216     return Res;
01217 
01218   if (FnL->hasSection()) {
01219     if (int Res = cmpMem(FnL->getSection(), FnR->getSection()))
01220       return Res;
01221   }
01222 
01223   if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
01224     return Res;
01225 
01226   // TODO: if it's internal and only used in direct calls, we could handle this
01227   // case too.
01228   if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
01229     return Res;
01230 
01231   if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
01232     return Res;
01233 
01234   assert(FnL->arg_size() == FnR->arg_size() &&
01235          "Identically typed functions have different numbers of args!");
01236 
01237   // Visit the arguments so that they get enumerated in the order they're
01238   // passed in.
01239   for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
01240                                     ArgRI = FnR->arg_begin(),
01241                                     ArgLE = FnL->arg_end();
01242        ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
01243     if (cmpValues(&*ArgLI, &*ArgRI) != 0)
01244       llvm_unreachable("Arguments repeat!");
01245   }
01246 
01247   // We do a CFG-ordered walk since the actual ordering of the blocks in the
01248   // linked list is immaterial. Our walk starts at the entry block for both
01249   // functions, then takes each block from each terminator in order. As an
01250   // artifact, this also means that unreachable blocks are ignored.
01251   SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
01252   SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
01253 
01254   FnLBBs.push_back(&FnL->getEntryBlock());
01255   FnRBBs.push_back(&FnR->getEntryBlock());
01256 
01257   VisitedBBs.insert(FnLBBs[0]);
01258   while (!FnLBBs.empty()) {
01259     const BasicBlock *BBL = FnLBBs.pop_back_val();
01260     const BasicBlock *BBR = FnRBBs.pop_back_val();
01261 
01262     if (int Res = cmpValues(BBL, BBR))
01263       return Res;
01264 
01265     if (int Res = cmpBasicBlocks(BBL, BBR))
01266       return Res;
01267 
01268     const TerminatorInst *TermL = BBL->getTerminator();
01269     const TerminatorInst *TermR = BBR->getTerminator();
01270 
01271     assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
01272     for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
01273       if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
01274         continue;
01275 
01276       FnLBBs.push_back(TermL->getSuccessor(i));
01277       FnRBBs.push_back(TermR->getSuccessor(i));
01278     }
01279   }
01280   return 0;
01281 }
01282 
01283 namespace {
01284 // Accumulate the hash of a sequence of 64-bit integers. This is similar to a
01285 // hash of a sequence of 64bit ints, but the entire input does not need to be
01286 // available at once. This interface is necessary for functionHash because it
01287 // needs to accumulate the hash as the structure of the function is traversed
01288 // without saving these values to an intermediate buffer. This form of hashing
01289 // is not often needed, as usually the object to hash is just read from a
01290 // buffer.
01291 class HashAccumulator64 {
01292   uint64_t Hash;
01293 public:
01294   // Initialize to random constant, so the state isn't zero.
01295   HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
01296   void add(uint64_t V) {
01297      Hash = llvm::hashing::detail::hash_16_bytes(Hash, V);
01298   }
01299   // No finishing is required, because the entire hash value is used.
01300   uint64_t getHash() { return Hash; }
01301 };
01302 } // end anonymous namespace
01303 
01304 // A function hash is calculated by considering only the number of arguments and
01305 // whether a function is varargs, the order of basic blocks (given by the
01306 // successors of each basic block in depth first order), and the order of
01307 // opcodes of each instruction within each of these basic blocks. This mirrors
01308 // the strategy compare() uses to compare functions by walking the BBs in depth
01309 // first order and comparing each instruction in sequence. Because this hash
01310 // does not look at the operands, it is insensitive to things such as the
01311 // target of calls and the constants used in the function, which makes it useful
01312 // when possibly merging functions which are the same modulo constants and call
01313 // targets.
01314 FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
01315   HashAccumulator64 H;
01316   H.add(F.isVarArg());
01317   H.add(F.arg_size());
01318   
01319   SmallVector<const BasicBlock *, 8> BBs;
01320   SmallSet<const BasicBlock *, 16> VisitedBBs;
01321 
01322   // Walk the blocks in the same order as FunctionComparator::cmpBasicBlocks(),
01323   // accumulating the hash of the function "structure." (BB and opcode sequence)
01324   BBs.push_back(&F.getEntryBlock());
01325   VisitedBBs.insert(BBs[0]);
01326   while (!BBs.empty()) {
01327     const BasicBlock *BB = BBs.pop_back_val();
01328     // This random value acts as a block header, as otherwise the partition of
01329     // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
01330     H.add(45798); 
01331     for (auto &Inst : *BB) {
01332       H.add(Inst.getOpcode());
01333     }
01334     const TerminatorInst *Term = BB->getTerminator();
01335     for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
01336       if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
01337         continue;
01338       BBs.push_back(Term->getSuccessor(i));
01339     }
01340   }
01341   return H.getHash();
01342 }
01343 
01344 
01345 namespace {
01346 
01347 /// MergeFunctions finds functions which will generate identical machine code,
01348 /// by considering all pointer types to be equivalent. Once identified,
01349 /// MergeFunctions will fold them by replacing a call to one to a call to a
01350 /// bitcast of the other.
01351 ///
01352 class MergeFunctions : public ModulePass {
01353 public:
01354   static char ID;
01355   MergeFunctions()
01356     : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)), FNodesInTree(),
01357       HasGlobalAliases(false) {
01358     initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
01359   }
01360 
01361   bool runOnModule(Module &M) override;
01362 
01363 private:
01364   // The function comparison operator is provided here so that FunctionNodes do
01365   // not need to become larger with another pointer.
01366   class FunctionNodeCmp {
01367     GlobalNumberState* GlobalNumbers;
01368   public:
01369     FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
01370     bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
01371       // Order first by hashes, then full function comparison.
01372       if (LHS.getHash() != RHS.getHash())
01373         return LHS.getHash() < RHS.getHash();
01374       FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
01375       return FCmp.compare() == -1;
01376     }
01377   };
01378   typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType;
01379 
01380   GlobalNumberState GlobalNumbers;
01381 
01382   /// A work queue of functions that may have been modified and should be
01383   /// analyzed again.
01384   std::vector<WeakVH> Deferred;
01385 
01386   /// Checks the rules of order relation introduced among functions set.
01387   /// Returns true, if sanity check has been passed, and false if failed.
01388   bool doSanityCheck(std::vector<WeakVH> &Worklist);
01389 
01390   /// Insert a ComparableFunction into the FnTree, or merge it away if it's
01391   /// equal to one that's already present.
01392   bool insert(Function *NewFunction);
01393 
01394   /// Remove a Function from the FnTree and queue it up for a second sweep of
01395   /// analysis.
01396   void remove(Function *F);
01397 
01398   /// Find the functions that use this Value and remove them from FnTree and
01399   /// queue the functions.
01400   void removeUsers(Value *V);
01401 
01402   /// Replace all direct calls of Old with calls of New. Will bitcast New if
01403   /// necessary to make types match.
01404   void replaceDirectCallers(Function *Old, Function *New);
01405 
01406   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
01407   /// be converted into a thunk. In either case, it should never be visited
01408   /// again.
01409   void mergeTwoFunctions(Function *F, Function *G);
01410 
01411   /// Replace G with a thunk or an alias to F. Deletes G.
01412   void writeThunkOrAlias(Function *F, Function *G);
01413 
01414   /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
01415   /// of G with bitcast(F). Deletes G.
01416   void writeThunk(Function *F, Function *G);
01417 
01418   /// Replace G with an alias to F. Deletes G.
01419   void writeAlias(Function *F, Function *G);
01420 
01421   /// Replace function F with function G in the function tree.
01422   void replaceFunctionInTree(const FunctionNode &FN, Function *G);
01423 
01424   /// The set of all distinct functions. Use the insert() and remove() methods
01425   /// to modify it. The map allows efficient lookup and deferring of Functions.
01426   FnTreeType FnTree;
01427   // Map functions to the iterators of the FunctionNode which contains them
01428   // in the FnTree. This must be updated carefully whenever the FnTree is
01429   // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
01430   // dangling iterators into FnTree. The invariant that preserves this is that
01431   // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
01432   ValueMap<Function*, FnTreeType::iterator> FNodesInTree;
01433 
01434   /// Whether or not the target supports global aliases.
01435   bool HasGlobalAliases;
01436 };
01437 
01438 } // end anonymous namespace
01439 
01440 char MergeFunctions::ID = 0;
01441 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
01442 
01443 ModulePass *llvm::createMergeFunctionsPass() {
01444   return new MergeFunctions();
01445 }
01446 
01447 bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
01448   if (const unsigned Max = NumFunctionsForSanityCheck) {
01449     unsigned TripleNumber = 0;
01450     bool Valid = true;
01451 
01452     dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
01453 
01454     unsigned i = 0;
01455     for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
01456          I != E && i < Max; ++I, ++i) {
01457       unsigned j = i;
01458       for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
01459         Function *F1 = cast<Function>(*I);
01460         Function *F2 = cast<Function>(*J);
01461         int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
01462         int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
01463 
01464         // If F1 <= F2, then F2 >= F1, otherwise report failure.
01465         if (Res1 != -Res2) {
01466           dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
01467                  << "\n";
01468           F1->dump();
01469           F2->dump();
01470           Valid = false;
01471         }
01472 
01473         if (Res1 == 0)
01474           continue;
01475 
01476         unsigned k = j;
01477         for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
01478              ++k, ++K, ++TripleNumber) {
01479           if (K == J)
01480             continue;
01481 
01482           Function *F3 = cast<Function>(*K);
01483           int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
01484           int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
01485 
01486           bool Transitive = true;
01487 
01488           if (Res1 != 0 && Res1 == Res4) {
01489             // F1 > F2, F2 > F3 => F1 > F3
01490             Transitive = Res3 == Res1;
01491           } else if (Res3 != 0 && Res3 == -Res4) {
01492             // F1 > F3, F3 > F2 => F1 > F2
01493             Transitive = Res3 == Res1;
01494           } else if (Res4 != 0 && -Res3 == Res4) {
01495             // F2 > F3, F3 > F1 => F2 > F1
01496             Transitive = Res4 == -Res1;
01497           }
01498 
01499           if (!Transitive) {
01500             dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
01501                    << TripleNumber << "\n";
01502             dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
01503                    << Res4 << "\n";
01504             F1->dump();
01505             F2->dump();
01506             F3->dump();
01507             Valid = false;
01508           }
01509         }
01510       }
01511     }
01512 
01513     dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
01514     return Valid;
01515   }
01516   return true;
01517 }
01518 
01519 bool MergeFunctions::runOnModule(Module &M) {
01520   bool Changed = false;
01521 
01522   // All functions in the module, ordered by hash. Functions with a unique
01523   // hash value are easily eliminated.
01524   std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
01525     HashedFuncs;
01526   for (Function &Func : M) {
01527     if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
01528       HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
01529     } 
01530   }
01531 
01532   std::stable_sort(
01533       HashedFuncs.begin(), HashedFuncs.end(),
01534       [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
01535          const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
01536         return a.first < b.first;
01537       });
01538 
01539   auto S = HashedFuncs.begin();
01540   for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
01541     // If the hash value matches the previous value or the next one, we must
01542     // consider merging it. Otherwise it is dropped and never considered again.
01543     if ((I != S && std::prev(I)->first == I->first) ||
01544         (std::next(I) != IE && std::next(I)->first == I->first) ) {
01545       Deferred.push_back(WeakVH(I->second));
01546     }
01547   }
01548   
01549   do {
01550     std::vector<WeakVH> Worklist;
01551     Deferred.swap(Worklist);
01552 
01553     DEBUG(doSanityCheck(Worklist));
01554 
01555     DEBUG(dbgs() << "size of module: " << M.size() << '\n');
01556     DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
01557 
01558     // Insert only strong functions and merge them. Strong function merging
01559     // always deletes one of them.
01560     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
01561            E = Worklist.end(); I != E; ++I) {
01562       if (!*I) continue;
01563       Function *F = cast<Function>(*I);
01564       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
01565           !F->mayBeOverridden()) {
01566         Changed |= insert(F);
01567       }
01568     }
01569 
01570     // Insert only weak functions and merge them. By doing these second we
01571     // create thunks to the strong function when possible. When two weak
01572     // functions are identical, we create a new strong function with two weak
01573     // weak thunks to it which are identical but not mergable.
01574     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
01575            E = Worklist.end(); I != E; ++I) {
01576       if (!*I) continue;
01577       Function *F = cast<Function>(*I);
01578       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
01579           F->mayBeOverridden()) {
01580         Changed |= insert(F);
01581       }
01582     }
01583     DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
01584   } while (!Deferred.empty());
01585 
01586   FnTree.clear();
01587   GlobalNumbers.clear();
01588 
01589   return Changed;
01590 }
01591 
01592 // Replace direct callers of Old with New.
01593 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
01594   Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
01595   for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
01596     Use *U = &*UI;
01597     ++UI;
01598     CallSite CS(U->getUser());
01599     if (CS && CS.isCallee(U)) {
01600       // Transfer the called function's attributes to the call site. Due to the
01601       // bitcast we will 'lose' ABI changing attributes because the 'called
01602       // function' is no longer a Function* but the bitcast. Code that looks up
01603       // the attributes from the called function will fail.
01604 
01605       // FIXME: This is not actually true, at least not anymore. The callsite
01606       // will always have the same ABI affecting attributes as the callee,
01607       // because otherwise the original input has UB. Note that Old and New
01608       // always have matching ABI, so no attributes need to be changed.
01609       // Transferring other attributes may help other optimizations, but that
01610       // should be done uniformly and not in this ad-hoc way.
01611       auto &Context = New->getContext();
01612       auto NewFuncAttrs = New->getAttributes();
01613       auto CallSiteAttrs = CS.getAttributes();
01614 
01615       CallSiteAttrs = CallSiteAttrs.addAttributes(
01616           Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
01617 
01618       for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
01619         AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
01620         if (Attrs.getNumSlots())
01621           CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
01622       }
01623 
01624       CS.setAttributes(CallSiteAttrs);
01625 
01626       remove(CS.getInstruction()->getParent()->getParent());
01627       U->set(BitcastNew);
01628     }
01629   }
01630 }
01631 
01632 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
01633 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
01634   if (HasGlobalAliases && G->hasUnnamedAddr()) {
01635     if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
01636         G->hasWeakLinkage()) {
01637       writeAlias(F, G);
01638       return;
01639     }
01640   }
01641 
01642   writeThunk(F, G);
01643 }
01644 
01645 // Helper for writeThunk,
01646 // Selects proper bitcast operation,
01647 // but a bit simpler then CastInst::getCastOpcode.
01648 static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
01649   Type *SrcTy = V->getType();
01650   if (SrcTy->isStructTy()) {
01651     assert(DestTy->isStructTy());
01652     assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
01653     Value *Result = UndefValue::get(DestTy);
01654     for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
01655       Value *Element = createCast(
01656           Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
01657           DestTy->getStructElementType(I));
01658 
01659       Result =
01660           Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
01661     }
01662     return Result;
01663   }
01664   assert(!DestTy->isStructTy());
01665   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
01666     return Builder.CreateIntToPtr(V, DestTy);
01667   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
01668     return Builder.CreatePtrToInt(V, DestTy);
01669   else
01670     return Builder.CreateBitCast(V, DestTy);
01671 }
01672 
01673 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
01674 // of G with bitcast(F). Deletes G.
01675 void MergeFunctions::writeThunk(Function *F, Function *G) {
01676   if (!G->mayBeOverridden()) {
01677     // Redirect direct callers of G to F.
01678     replaceDirectCallers(G, F);
01679   }
01680 
01681   // If G was internal then we may have replaced all uses of G with F. If so,
01682   // stop here and delete G. There's no need for a thunk.
01683   if (G->hasLocalLinkage() && G->use_empty()) {
01684     G->eraseFromParent();
01685     return;
01686   }
01687 
01688   Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
01689                                     G->getParent());
01690   BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
01691   IRBuilder<false> Builder(BB);
01692 
01693   SmallVector<Value *, 16> Args;
01694   unsigned i = 0;
01695   FunctionType *FFTy = F->getFunctionType();
01696   for (Argument & AI : NewG->args()) {
01697     Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
01698     ++i;
01699   }
01700 
01701   CallInst *CI = Builder.CreateCall(F, Args);
01702   CI->setTailCall();
01703   CI->setCallingConv(F->getCallingConv());
01704   CI->setAttributes(F->getAttributes());
01705   if (NewG->getReturnType()->isVoidTy()) {
01706     Builder.CreateRetVoid();
01707   } else {
01708     Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
01709   }
01710 
01711   NewG->copyAttributesFrom(G);
01712   NewG->takeName(G);
01713   removeUsers(G);
01714   G->replaceAllUsesWith(NewG);
01715   G->eraseFromParent();
01716 
01717   DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
01718   ++NumThunksWritten;
01719 }
01720 
01721 // Replace G with an alias to F and delete G.
01722 void MergeFunctions::writeAlias(Function *F, Function *G) {
01723   auto *GA = GlobalAlias::create(G->getLinkage(), "", F);
01724   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
01725   GA->takeName(G);
01726   GA->setVisibility(G->getVisibility());
01727   removeUsers(G);
01728   G->replaceAllUsesWith(GA);
01729   G->eraseFromParent();
01730 
01731   DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
01732   ++NumAliasesWritten;
01733 }
01734 
01735 // Merge two equivalent functions. Upon completion, Function G is deleted.
01736 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
01737   if (F->mayBeOverridden()) {
01738     assert(G->mayBeOverridden());
01739 
01740     // Make them both thunks to the same internal function.
01741     Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
01742                                    F->getParent());
01743     H->copyAttributesFrom(F);
01744     H->takeName(F);
01745     removeUsers(F);
01746     F->replaceAllUsesWith(H);
01747 
01748     unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
01749 
01750     if (HasGlobalAliases) {
01751       writeAlias(F, G);
01752       writeAlias(F, H);
01753     } else {
01754       writeThunk(F, G);
01755       writeThunk(F, H);
01756     }
01757 
01758     F->setAlignment(MaxAlignment);
01759     F->setLinkage(GlobalValue::PrivateLinkage);
01760     ++NumDoubleWeak;
01761   } else {
01762     writeThunkOrAlias(F, G);
01763   }
01764 
01765   ++NumFunctionsMerged;
01766 }
01767 
01768 /// Replace function F by function G.
01769 void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
01770                                            Function *G) {
01771   Function *F = FN.getFunc();
01772   assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
01773          "The two functions must be equal");
01774   
01775   auto I = FNodesInTree.find(F);
01776   assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
01777   assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
01778   
01779   FnTreeType::iterator IterToFNInFnTree = I->second;
01780   assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
01781   // Remove F -> FN and insert G -> FN
01782   FNodesInTree.erase(I);
01783   FNodesInTree.insert({G, IterToFNInFnTree});
01784   // Replace F with G in FN, which is stored inside the FnTree.
01785   FN.replaceBy(G);
01786 }
01787 
01788 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
01789 // that was already inserted.
01790 bool MergeFunctions::insert(Function *NewFunction) {
01791   std::pair<FnTreeType::iterator, bool> Result =
01792       FnTree.insert(FunctionNode(NewFunction));
01793 
01794   if (Result.second) {
01795     assert(FNodesInTree.count(NewFunction) == 0);
01796     FNodesInTree.insert({NewFunction, Result.first});
01797     DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
01798     return false;
01799   }
01800 
01801   const FunctionNode &OldF = *Result.first;
01802 
01803   // Don't merge tiny functions, since it can just end up making the function
01804   // larger.
01805   // FIXME: Should still merge them if they are unnamed_addr and produce an
01806   // alias.
01807   if (NewFunction->size() == 1) {
01808     if (NewFunction->front().size() <= 2) {
01809       DEBUG(dbgs() << NewFunction->getName()
01810                    << " is to small to bother merging\n");
01811       return false;
01812     }
01813   }
01814 
01815   // Impose a total order (by name) on the replacement of functions. This is
01816   // important when operating on more than one module independently to prevent
01817   // cycles of thunks calling each other when the modules are linked together.
01818   //
01819   // When one function is weak and the other is strong there is an order imposed
01820   // already. We process strong functions before weak functions.
01821   if ((OldF.getFunc()->mayBeOverridden() && NewFunction->mayBeOverridden()) ||
01822       (!OldF.getFunc()->mayBeOverridden() && !NewFunction->mayBeOverridden()))
01823     if (OldF.getFunc()->getName() > NewFunction->getName()) {
01824       // Swap the two functions.
01825       Function *F = OldF.getFunc();
01826       replaceFunctionInTree(*Result.first, NewFunction);
01827       NewFunction = F;
01828       assert(OldF.getFunc() != F && "Must have swapped the functions.");
01829     }
01830 
01831   // Never thunk a strong function to a weak function.
01832   assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
01833 
01834   DEBUG(dbgs() << "  " << OldF.getFunc()->getName()
01835                << " == " << NewFunction->getName() << '\n');
01836 
01837   Function *DeleteF = NewFunction;
01838   mergeTwoFunctions(OldF.getFunc(), DeleteF);
01839   return true;
01840 }
01841 
01842 // Remove a function from FnTree. If it was already in FnTree, add
01843 // it to Deferred so that we'll look at it in the next round.
01844 void MergeFunctions::remove(Function *F) {
01845   auto I = FNodesInTree.find(F);
01846   if (I != FNodesInTree.end()) {
01847     DEBUG(dbgs() << "Deferred " << F->getName()<< ".\n");
01848     FnTree.erase(I->second);
01849     // I->second has been invalidated, remove it from the FNodesInTree map to
01850     // preserve the invariant.
01851     FNodesInTree.erase(I);
01852     Deferred.emplace_back(F);
01853   }
01854 }
01855 
01856 // For each instruction used by the value, remove() the function that contains
01857 // the instruction. This should happen right before a call to RAUW.
01858 void MergeFunctions::removeUsers(Value *V) {
01859   std::vector<Value *> Worklist;
01860   Worklist.push_back(V);
01861   SmallSet<Value*, 8> Visited;
01862   Visited.insert(V);
01863   while (!Worklist.empty()) {
01864     Value *V = Worklist.back();
01865     Worklist.pop_back();
01866 
01867     for (User *U : V->users()) {
01868       if (Instruction *I = dyn_cast<Instruction>(U)) {
01869         remove(I->getParent()->getParent());
01870       } else if (isa<GlobalValue>(U)) {
01871         // do nothing
01872       } else if (Constant *C = dyn_cast<Constant>(U)) {
01873         for (User *UU : C->users()) {
01874           if (!Visited.insert(UU).second)
01875             Worklist.push_back(UU);
01876         }
01877       }
01878     }
01879   }
01880 }