1c9d2170f92b41aae2e1e82f2b05de160bc4782c
[oota-llvm.git] / lib / Transforms / IPO / MergeFunctions.cpp
1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass looks for equivalent functions that are mergable and folds them.
11 //
12 // Order relation is defined on set of functions. It was made through
13 // special function comparison procedure that returns
14 // 0 when functions are equal,
15 // -1 when Left function is less than right function, and
16 // 1 for opposite case. We need total-ordering, so we need to maintain
17 // four properties on the functions set:
18 // a <= a (reflexivity)
19 // if a <= b and b <= a then a = b (antisymmetry)
20 // if a <= b and b <= c then a <= c (transitivity).
21 // for all a and b: a <= b or b <= a (totality).
22 //
23 // Comparison iterates through each instruction in each basic block.
24 // Functions are kept on binary tree. For each new function F we perform
25 // lookup in binary tree.
26 // In practice it works the following way:
27 // -- We define Function* container class with custom "operator<" (FunctionPtr).
28 // -- "FunctionPtr" instances are stored in std::set collection, so every
29 //    std::set::insert operation will give you result in log(N) time.
30 // 
31 // As an optimization, a hash of the function structure is calculated first, and
32 // two functions are only compared if they have the same hash. This hash is
33 // cheap to compute, and has the property that if function F == G according to
34 // the comparison function, then hash(F) == hash(G). This consistency property
35 // is critical to ensuring all possible merging opportunities are exploited.
36 // Collisions in the hash affect the speed of the pass but not the correctness
37 // or determinism of the resulting transformation.
38 //
39 // When a match is found the functions are folded. If both functions are
40 // overridable, we move the functionality into a new internal function and
41 // leave two overridable thunks to it.
42 //
43 //===----------------------------------------------------------------------===//
44 //
45 // Future work:
46 //
47 // * virtual functions.
48 //
49 // Many functions have their address taken by the virtual function table for
50 // the object they belong to. However, as long as it's only used for a lookup
51 // and call, this is irrelevant, and we'd like to fold such functions.
52 //
53 // * be smarter about bitcasts.
54 //
55 // In order to fold functions, we will sometimes add either bitcast instructions
56 // or bitcast constant expressions. Unfortunately, this can confound further
57 // analysis since the two functions differ where one has a bitcast and the
58 // other doesn't. We should learn to look through bitcasts.
59 //
60 // * Compare complex types with pointer types inside.
61 // * Compare cross-reference cases.
62 // * Compare complex expressions.
63 //
64 // All the three issues above could be described as ability to prove that
65 // fA == fB == fC == fE == fF == fG in example below:
66 //
67 //  void fA() {
68 //    fB();
69 //  }
70 //  void fB() {
71 //    fA();
72 //  }
73 //
74 //  void fE() {
75 //    fF();
76 //  }
77 //  void fF() {
78 //    fG();
79 //  }
80 //  void fG() {
81 //    fE();
82 //  }
83 //
84 // Simplest cross-reference case (fA <--> fB) was implemented in previous
85 // versions of MergeFunctions, though it presented only in two function pairs
86 // in test-suite (that counts >50k functions)
87 // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
88 // could cover much more cases.
89 //
90 //===----------------------------------------------------------------------===//
91
92 #include "llvm/Transforms/IPO.h"
93 #include "llvm/ADT/DenseSet.h"
94 #include "llvm/ADT/FoldingSet.h"
95 #include "llvm/ADT/STLExtras.h"
96 #include "llvm/ADT/SmallSet.h"
97 #include "llvm/ADT/Statistic.h"
98 #include "llvm/ADT/Hashing.h"
99 #include "llvm/IR/CallSite.h"
100 #include "llvm/IR/Constants.h"
101 #include "llvm/IR/DataLayout.h"
102 #include "llvm/IR/IRBuilder.h"
103 #include "llvm/IR/InlineAsm.h"
104 #include "llvm/IR/Instructions.h"
105 #include "llvm/IR/LLVMContext.h"
106 #include "llvm/IR/Module.h"
107 #include "llvm/IR/Operator.h"
108 #include "llvm/IR/ValueHandle.h"
109 #include "llvm/Pass.h"
110 #include "llvm/Support/CommandLine.h"
111 #include "llvm/Support/Debug.h"
112 #include "llvm/Support/ErrorHandling.h"
113 #include "llvm/Support/raw_ostream.h"
114 #include <vector>
115 using namespace llvm;
116
117 #define DEBUG_TYPE "mergefunc"
118
119 STATISTIC(NumFunctionsMerged, "Number of functions merged");
120 STATISTIC(NumThunksWritten, "Number of thunks generated");
121 STATISTIC(NumAliasesWritten, "Number of aliases generated");
122 STATISTIC(NumDoubleWeak, "Number of new functions created");
123
124 static cl::opt<unsigned> NumFunctionsForSanityCheck(
125     "mergefunc-sanity",
126     cl::desc("How many functions in module could be used for "
127              "MergeFunctions pass sanity check. "
128              "'0' disables this check. Works only with '-debug' key."),
129     cl::init(0), cl::Hidden);
130
131 namespace {
132
133 /// FunctionComparator - Compares two functions to determine whether or not
134 /// they will generate machine code with the same behaviour. DataLayout is
135 /// used if available. The comparator always fails conservatively (erring on the
136 /// side of claiming that two functions are different).
137 class FunctionComparator {
138 public:
139   FunctionComparator(const Function *F1, const Function *F2)
140       : FnL(F1), FnR(F2) {}
141
142   /// Test whether the two functions have equivalent behaviour.
143   int compare();
144   /// Hash a function. Equivalent functions will have the same hash, and unequal
145   /// functions will have different hashes with high probability.
146   typedef uint64_t FunctionHash;
147   static FunctionHash functionHash(Function &);
148
149 private:
150   /// Test whether two basic blocks have equivalent behaviour.
151   int compare(const BasicBlock *BBL, const BasicBlock *BBR);
152
153   /// Constants comparison.
154   /// Its analog to lexicographical comparison between hypothetical numbers
155   /// of next format:
156   /// <bitcastability-trait><raw-bit-contents>
157   ///
158   /// 1. Bitcastability.
159   /// Check whether L's type could be losslessly bitcasted to R's type.
160   /// On this stage method, in case when lossless bitcast is not possible
161   /// method returns -1 or 1, thus also defining which type is greater in
162   /// context of bitcastability.
163   /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
164   ///          to the contents comparison.
165   ///          If types differ, remember types comparison result and check
166   ///          whether we still can bitcast types.
167   /// Stage 1: Types that satisfies isFirstClassType conditions are always
168   ///          greater then others.
169   /// Stage 2: Vector is greater then non-vector.
170   ///          If both types are vectors, then vector with greater bitwidth is
171   ///          greater.
172   ///          If both types are vectors with the same bitwidth, then types
173   ///          are bitcastable, and we can skip other stages, and go to contents
174   ///          comparison.
175   /// Stage 3: Pointer types are greater than non-pointers. If both types are
176   ///          pointers of the same address space - go to contents comparison.
177   ///          Different address spaces: pointer with greater address space is
178   ///          greater.
179   /// Stage 4: Types are neither vectors, nor pointers. And they differ.
180   ///          We don't know how to bitcast them. So, we better don't do it,
181   ///          and return types comparison result (so it determines the
182   ///          relationship among constants we don't know how to bitcast).
183   ///
184   /// Just for clearance, let's see how the set of constants could look
185   /// on single dimension axis:
186   ///
187   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
188   /// Where: NFCT - Not a FirstClassType
189   ///        FCT - FirstClassTyp:
190   ///
191   /// 2. Compare raw contents.
192   /// It ignores types on this stage and only compares bits from L and R.
193   /// Returns 0, if L and R has equivalent contents.
194   /// -1 or 1 if values are different.
195   /// Pretty trivial:
196   /// 2.1. If contents are numbers, compare numbers.
197   ///    Ints with greater bitwidth are greater. Ints with same bitwidths
198   ///    compared by their contents.
199   /// 2.2. "And so on". Just to avoid discrepancies with comments
200   /// perhaps it would be better to read the implementation itself.
201   /// 3. And again about overall picture. Let's look back at how the ordered set
202   /// of constants will look like:
203   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
204   ///
205   /// Now look, what could be inside [FCT, "others"], for example:
206   /// [FCT, "others"] =
207   /// [
208   ///   [double 0.1], [double 1.23],
209   ///   [i32 1], [i32 2],
210   ///   { double 1.0 },       ; StructTyID, NumElements = 1
211   ///   { i32 1 },            ; StructTyID, NumElements = 1
212   ///   { double 1, i32 1 },  ; StructTyID, NumElements = 2
213   ///   { i32 1, double 1 }   ; StructTyID, NumElements = 2
214   /// ]
215   ///
216   /// Let's explain the order. Float numbers will be less than integers, just
217   /// because of cmpType terms: FloatTyID < IntegerTyID.
218   /// Floats (with same fltSemantics) are sorted according to their value.
219   /// Then you can see integers, and they are, like a floats,
220   /// could be easy sorted among each others.
221   /// The structures. Structures are grouped at the tail, again because of their
222   /// TypeID: StructTyID > IntegerTyID > FloatTyID.
223   /// Structures with greater number of elements are greater. Structures with
224   /// greater elements going first are greater.
225   /// The same logic with vectors, arrays and other possible complex types.
226   ///
227   /// Bitcastable constants.
228   /// Let's assume, that some constant, belongs to some group of
229   /// "so-called-equal" values with different types, and at the same time
230   /// belongs to another group of constants with equal types
231   /// and "really" equal values.
232   ///
233   /// Now, prove that this is impossible:
234   ///
235   /// If constant A with type TyA is bitcastable to B with type TyB, then:
236   /// 1. All constants with equal types to TyA, are bitcastable to B. Since
237   ///    those should be vectors (if TyA is vector), pointers
238   ///    (if TyA is pointer), or else (if TyA equal to TyB), those types should
239   ///    be equal to TyB.
240   /// 2. All constants with non-equal, but bitcastable types to TyA, are
241   ///    bitcastable to B.
242   ///    Once again, just because we allow it to vectors and pointers only.
243   ///    This statement could be expanded as below:
244   /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
245   ///      vector B, and thus bitcastable to B as well.
246   /// 2.2. All pointers of the same address space, no matter what they point to,
247   ///      bitcastable. So if C is pointer, it could be bitcasted to A and to B.
248   /// So any constant equal or bitcastable to A is equal or bitcastable to B.
249   /// QED.
250   ///
251   /// In another words, for pointers and vectors, we ignore top-level type and
252   /// look at their particular properties (bit-width for vectors, and
253   /// address space for pointers).
254   /// If these properties are equal - compare their contents.
255   int cmpConstants(const Constant *L, const Constant *R);
256
257   /// Assign or look up previously assigned numbers for the two values, and
258   /// return whether the numbers are equal. Numbers are assigned in the order
259   /// visited.
260   /// Comparison order:
261   /// Stage 0: Value that is function itself is always greater then others.
262   ///          If left and right values are references to their functions, then
263   ///          they are equal.
264   /// Stage 1: Constants are greater than non-constants.
265   ///          If both left and right are constants, then the result of
266   ///          cmpConstants is used as cmpValues result.
267   /// Stage 2: InlineAsm instances are greater than others. If both left and
268   ///          right are InlineAsm instances, InlineAsm* pointers casted to
269   ///          integers and compared as numbers.
270   /// Stage 3: For all other cases we compare order we meet these values in
271   ///          their functions. If right value was met first during scanning,
272   ///          then left value is greater.
273   ///          In another words, we compare serial numbers, for more details
274   ///          see comments for sn_mapL and sn_mapR.
275   int cmpValues(const Value *L, const Value *R);
276
277   /// Compare two Instructions for equivalence, similar to
278   /// Instruction::isSameOperationAs but with modifications to the type
279   /// comparison.
280   /// Stages are listed in "most significant stage first" order:
281   /// On each stage below, we do comparison between some left and right
282   /// operation parts. If parts are non-equal, we assign parts comparison
283   /// result to the operation comparison result and exit from method.
284   /// Otherwise we proceed to the next stage.
285   /// Stages:
286   /// 1. Operations opcodes. Compared as numbers.
287   /// 2. Number of operands.
288   /// 3. Operation types. Compared with cmpType method.
289   /// 4. Compare operation subclass optional data as stream of bytes:
290   /// just convert it to integers and call cmpNumbers.
291   /// 5. Compare in operation operand types with cmpType in
292   /// most significant operand first order.
293   /// 6. Last stage. Check operations for some specific attributes.
294   /// For example, for Load it would be:
295   /// 6.1.Load: volatile (as boolean flag)
296   /// 6.2.Load: alignment (as integer numbers)
297   /// 6.3.Load: synch-scope (as integer numbers)
298   /// 6.4.Load: range metadata (as integer numbers)
299   /// On this stage its better to see the code, since its not more than 10-15
300   /// strings for particular instruction, and could change sometimes.
301   int cmpOperations(const Instruction *L, const Instruction *R) const;
302
303   /// Compare two GEPs for equivalent pointer arithmetic.
304   /// Parts to be compared for each comparison stage,
305   /// most significant stage first:
306   /// 1. Address space. As numbers.
307   /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
308   /// 3. Pointer operand type (using cmpType method).
309   /// 4. Number of operands.
310   /// 5. Compare operands, using cmpValues method.
311   int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR);
312   int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
313     return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
314   }
315
316   /// cmpType - compares two types,
317   /// defines total ordering among the types set.
318   ///
319   /// Return values:
320   /// 0 if types are equal,
321   /// -1 if Left is less than Right,
322   /// +1 if Left is greater than Right.
323   ///
324   /// Description:
325   /// Comparison is broken onto stages. Like in lexicographical comparison
326   /// stage coming first has higher priority.
327   /// On each explanation stage keep in mind total ordering properties.
328   ///
329   /// 0. Before comparison we coerce pointer types of 0 address space to
330   /// integer.
331   /// We also don't bother with same type at left and right, so
332   /// just return 0 in this case.
333   ///
334   /// 1. If types are of different kind (different type IDs).
335   ///    Return result of type IDs comparison, treating them as numbers.
336   /// 2. If types are vectors or integers, compare Type* values as numbers.
337   /// 3. Types has same ID, so check whether they belongs to the next group:
338   /// * Void
339   /// * Float
340   /// * Double
341   /// * X86_FP80
342   /// * FP128
343   /// * PPC_FP128
344   /// * Label
345   /// * Metadata
346   /// If so - return 0, yes - we can treat these types as equal only because
347   /// their IDs are same.
348   /// 4. If Left and Right are pointers, return result of address space
349   /// comparison (numbers comparison). We can treat pointer types of same
350   /// address space as equal.
351   /// 5. If types are complex.
352   /// Then both Left and Right are to be expanded and their element types will
353   /// be checked with the same way. If we get Res != 0 on some stage, return it.
354   /// Otherwise return 0.
355   /// 6. For all other cases put llvm_unreachable.
356   int cmpTypes(Type *TyL, Type *TyR) const;
357
358   int cmpNumbers(uint64_t L, uint64_t R) const;
359
360   int cmpAPInts(const APInt &L, const APInt &R) const;
361   int cmpAPFloats(const APFloat &L, const APFloat &R) const;
362   int cmpStrings(StringRef L, StringRef R) const;
363   int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
364
365   // The two functions undergoing comparison.
366   const Function *FnL, *FnR;
367
368   /// Assign serial numbers to values from left function, and values from
369   /// right function.
370   /// Explanation:
371   /// Being comparing functions we need to compare values we meet at left and
372   /// right sides.
373   /// Its easy to sort things out for external values. It just should be
374   /// the same value at left and right.
375   /// But for local values (those were introduced inside function body)
376   /// we have to ensure they were introduced at exactly the same place,
377   /// and plays the same role.
378   /// Let's assign serial number to each value when we meet it first time.
379   /// Values that were met at same place will be with same serial numbers.
380   /// In this case it would be good to explain few points about values assigned
381   /// to BBs and other ways of implementation (see below).
382   ///
383   /// 1. Safety of BB reordering.
384   /// It's safe to change the order of BasicBlocks in function.
385   /// Relationship with other functions and serial numbering will not be
386   /// changed in this case.
387   /// As follows from FunctionComparator::compare(), we do CFG walk: we start
388   /// from the entry, and then take each terminator. So it doesn't matter how in
389   /// fact BBs are ordered in function. And since cmpValues are called during
390   /// this walk, the numbering depends only on how BBs located inside the CFG.
391   /// So the answer is - yes. We will get the same numbering.
392   ///
393   /// 2. Impossibility to use dominance properties of values.
394   /// If we compare two instruction operands: first is usage of local
395   /// variable AL from function FL, and second is usage of local variable AR
396   /// from FR, we could compare their origins and check whether they are
397   /// defined at the same place.
398   /// But, we are still not able to compare operands of PHI nodes, since those
399   /// could be operands from further BBs we didn't scan yet.
400   /// So it's impossible to use dominance properties in general.
401   DenseMap<const Value*, int> sn_mapL, sn_mapR;
402 };
403
404 class FunctionNode {
405   mutable AssertingVH<Function> F;
406   FunctionComparator::FunctionHash Hash;
407
408 public:
409   // Note the hash is recalculated potentially multiple times, but it is cheap.
410   FunctionNode(Function *F) : F(F), Hash(FunctionComparator::functionHash(*F)){}
411   Function *getFunc() const { return F; }
412
413   /// Replace the reference to the function F by the function G, assuming their
414   /// implementations are equal.
415   void replaceBy(Function *G) const {
416     assert(!(*this < FunctionNode(G)) && !(FunctionNode(G) < *this) &&
417            "The two functions must be equal");
418
419     F = G;
420   }
421
422   void release() { F = 0; }
423   bool operator<(const FunctionNode &RHS) const {
424     // Order first by hashes, then full function comparison.
425     if (Hash != RHS.Hash)
426       return Hash < RHS.Hash;
427     return (FunctionComparator(F, RHS.getFunc()).compare()) == -1;
428   }
429 };
430 }
431
432 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
433   if (L < R) return -1;
434   if (L > R) return 1;
435   return 0;
436 }
437
438 int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
439   if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
440     return Res;
441   if (L.ugt(R)) return 1;
442   if (R.ugt(L)) return -1;
443   return 0;
444 }
445
446 int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
447   if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
448                            (uint64_t)&R.getSemantics()))
449     return Res;
450   return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
451 }
452
453 int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
454   // Prevent heavy comparison, compare sizes first.
455   if (int Res = cmpNumbers(L.size(), R.size()))
456     return Res;
457
458   // Compare strings lexicographically only when it is necessary: only when
459   // strings are equal in size.
460   return L.compare(R);
461 }
462
463 int FunctionComparator::cmpAttrs(const AttributeSet L,
464                                  const AttributeSet R) const {
465   if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
466     return Res;
467
468   for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
469     AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
470                            RE = R.end(i);
471     for (; LI != LE && RI != RE; ++LI, ++RI) {
472       Attribute LA = *LI;
473       Attribute RA = *RI;
474       if (LA < RA)
475         return -1;
476       if (RA < LA)
477         return 1;
478     }
479     if (LI != LE)
480       return 1;
481     if (RI != RE)
482       return -1;
483   }
484   return 0;
485 }
486
487 /// Constants comparison:
488 /// 1. Check whether type of L constant could be losslessly bitcasted to R
489 /// type.
490 /// 2. Compare constant contents.
491 /// For more details see declaration comments.
492 int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
493
494   Type *TyL = L->getType();
495   Type *TyR = R->getType();
496
497   // Check whether types are bitcastable. This part is just re-factored
498   // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
499   // we also pack into result which type is "less" for us.
500   int TypesRes = cmpTypes(TyL, TyR);
501   if (TypesRes != 0) {
502     // Types are different, but check whether we can bitcast them.
503     if (!TyL->isFirstClassType()) {
504       if (TyR->isFirstClassType())
505         return -1;
506       // Neither TyL nor TyR are values of first class type. Return the result
507       // of comparing the types
508       return TypesRes;
509     }
510     if (!TyR->isFirstClassType()) {
511       if (TyL->isFirstClassType())
512         return 1;
513       return TypesRes;
514     }
515
516     // Vector -> Vector conversions are always lossless if the two vector types
517     // have the same size, otherwise not.
518     unsigned TyLWidth = 0;
519     unsigned TyRWidth = 0;
520
521     if (auto *VecTyL = dyn_cast<VectorType>(TyL))
522       TyLWidth = VecTyL->getBitWidth();
523     if (auto *VecTyR = dyn_cast<VectorType>(TyR))
524       TyRWidth = VecTyR->getBitWidth();
525
526     if (TyLWidth != TyRWidth)
527       return cmpNumbers(TyLWidth, TyRWidth);
528
529     // Zero bit-width means neither TyL nor TyR are vectors.
530     if (!TyLWidth) {
531       PointerType *PTyL = dyn_cast<PointerType>(TyL);
532       PointerType *PTyR = dyn_cast<PointerType>(TyR);
533       if (PTyL && PTyR) {
534         unsigned AddrSpaceL = PTyL->getAddressSpace();
535         unsigned AddrSpaceR = PTyR->getAddressSpace();
536         if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
537           return Res;
538       }
539       if (PTyL)
540         return 1;
541       if (PTyR)
542         return -1;
543
544       // TyL and TyR aren't vectors, nor pointers. We don't know how to
545       // bitcast them.
546       return TypesRes;
547     }
548   }
549
550   // OK, types are bitcastable, now check constant contents.
551
552   if (L->isNullValue() && R->isNullValue())
553     return TypesRes;
554   if (L->isNullValue() && !R->isNullValue())
555     return 1;
556   if (!L->isNullValue() && R->isNullValue())
557     return -1;
558
559   if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
560     return Res;
561
562   switch (L->getValueID()) {
563   case Value::UndefValueVal: return TypesRes;
564   case Value::ConstantIntVal: {
565     const APInt &LInt = cast<ConstantInt>(L)->getValue();
566     const APInt &RInt = cast<ConstantInt>(R)->getValue();
567     return cmpAPInts(LInt, RInt);
568   }
569   case Value::ConstantFPVal: {
570     const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
571     const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
572     return cmpAPFloats(LAPF, RAPF);
573   }
574   case Value::ConstantArrayVal: {
575     const ConstantArray *LA = cast<ConstantArray>(L);
576     const ConstantArray *RA = cast<ConstantArray>(R);
577     uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
578     uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
579     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
580       return Res;
581     for (uint64_t i = 0; i < NumElementsL; ++i) {
582       if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
583                                  cast<Constant>(RA->getOperand(i))))
584         return Res;
585     }
586     return 0;
587   }
588   case Value::ConstantStructVal: {
589     const ConstantStruct *LS = cast<ConstantStruct>(L);
590     const ConstantStruct *RS = cast<ConstantStruct>(R);
591     unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
592     unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
593     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
594       return Res;
595     for (unsigned i = 0; i != NumElementsL; ++i) {
596       if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
597                                  cast<Constant>(RS->getOperand(i))))
598         return Res;
599     }
600     return 0;
601   }
602   case Value::ConstantVectorVal: {
603     const ConstantVector *LV = cast<ConstantVector>(L);
604     const ConstantVector *RV = cast<ConstantVector>(R);
605     unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
606     unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
607     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
608       return Res;
609     for (uint64_t i = 0; i < NumElementsL; ++i) {
610       if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
611                                  cast<Constant>(RV->getOperand(i))))
612         return Res;
613     }
614     return 0;
615   }
616   case Value::ConstantExprVal: {
617     const ConstantExpr *LE = cast<ConstantExpr>(L);
618     const ConstantExpr *RE = cast<ConstantExpr>(R);
619     unsigned NumOperandsL = LE->getNumOperands();
620     unsigned NumOperandsR = RE->getNumOperands();
621     if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
622       return Res;
623     for (unsigned i = 0; i < NumOperandsL; ++i) {
624       if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
625                                  cast<Constant>(RE->getOperand(i))))
626         return Res;
627     }
628     return 0;
629   }
630   case Value::FunctionVal:
631   case Value::GlobalVariableVal:
632   case Value::GlobalAliasVal:
633   default: // Unknown constant, cast L and R pointers to numbers and compare.
634     return cmpNumbers((uint64_t)L, (uint64_t)R);
635   }
636 }
637
638 /// cmpType - compares two types,
639 /// defines total ordering among the types set.
640 /// See method declaration comments for more details.
641 int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
642
643   PointerType *PTyL = dyn_cast<PointerType>(TyL);
644   PointerType *PTyR = dyn_cast<PointerType>(TyR);
645
646   const DataLayout &DL = FnL->getParent()->getDataLayout();
647   if (PTyL && PTyL->getAddressSpace() == 0)
648     TyL = DL.getIntPtrType(TyL);
649   if (PTyR && PTyR->getAddressSpace() == 0)
650     TyR = DL.getIntPtrType(TyR);
651
652   if (TyL == TyR)
653     return 0;
654
655   if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
656     return Res;
657
658   switch (TyL->getTypeID()) {
659   default:
660     llvm_unreachable("Unknown type!");
661     // Fall through in Release mode.
662   case Type::IntegerTyID:
663   case Type::VectorTyID:
664     // TyL == TyR would have returned true earlier.
665     return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
666
667   case Type::VoidTyID:
668   case Type::FloatTyID:
669   case Type::DoubleTyID:
670   case Type::X86_FP80TyID:
671   case Type::FP128TyID:
672   case Type::PPC_FP128TyID:
673   case Type::LabelTyID:
674   case Type::MetadataTyID:
675   case Type::TokenTyID:
676     return 0;
677
678   case Type::PointerTyID: {
679     assert(PTyL && PTyR && "Both types must be pointers here.");
680     return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
681   }
682
683   case Type::StructTyID: {
684     StructType *STyL = cast<StructType>(TyL);
685     StructType *STyR = cast<StructType>(TyR);
686     if (STyL->getNumElements() != STyR->getNumElements())
687       return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
688
689     if (STyL->isPacked() != STyR->isPacked())
690       return cmpNumbers(STyL->isPacked(), STyR->isPacked());
691
692     for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
693       if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
694         return Res;
695     }
696     return 0;
697   }
698
699   case Type::FunctionTyID: {
700     FunctionType *FTyL = cast<FunctionType>(TyL);
701     FunctionType *FTyR = cast<FunctionType>(TyR);
702     if (FTyL->getNumParams() != FTyR->getNumParams())
703       return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
704
705     if (FTyL->isVarArg() != FTyR->isVarArg())
706       return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
707
708     if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
709       return Res;
710
711     for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
712       if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
713         return Res;
714     }
715     return 0;
716   }
717
718   case Type::ArrayTyID: {
719     ArrayType *ATyL = cast<ArrayType>(TyL);
720     ArrayType *ATyR = cast<ArrayType>(TyR);
721     if (ATyL->getNumElements() != ATyR->getNumElements())
722       return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
723     return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
724   }
725   }
726 }
727
728 // Determine whether the two operations are the same except that pointer-to-A
729 // and pointer-to-B are equivalent. This should be kept in sync with
730 // Instruction::isSameOperationAs.
731 // Read method declaration comments for more details.
732 int FunctionComparator::cmpOperations(const Instruction *L,
733                                       const Instruction *R) const {
734   // Differences from Instruction::isSameOperationAs:
735   //  * replace type comparison with calls to isEquivalentType.
736   //  * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
737   //  * because of the above, we don't test for the tail bit on calls later on
738   if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
739     return Res;
740
741   if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
742     return Res;
743
744   if (int Res = cmpTypes(L->getType(), R->getType()))
745     return Res;
746
747   if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
748                            R->getRawSubclassOptionalData()))
749     return Res;
750
751   if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
752     if (int Res = cmpTypes(AI->getAllocatedType(),
753                            cast<AllocaInst>(R)->getAllocatedType()))
754       return Res;
755     if (int Res =
756             cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment()))
757       return Res;
758   }
759
760   // We have two instructions of identical opcode and #operands.  Check to see
761   // if all operands are the same type
762   for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
763     if (int Res =
764             cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
765       return Res;
766   }
767
768   // Check special state that is a part of some instructions.
769   if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
770     if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
771       return Res;
772     if (int Res =
773             cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
774       return Res;
775     if (int Res =
776             cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
777       return Res;
778     if (int Res =
779             cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
780       return Res;
781     return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
782                       (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
783   }
784   if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
785     if (int Res =
786             cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
787       return Res;
788     if (int Res =
789             cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
790       return Res;
791     if (int Res =
792             cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
793       return Res;
794     return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
795   }
796   if (const CmpInst *CI = dyn_cast<CmpInst>(L))
797     return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
798   if (const CallInst *CI = dyn_cast<CallInst>(L)) {
799     if (int Res = cmpNumbers(CI->getCallingConv(),
800                              cast<CallInst>(R)->getCallingConv()))
801       return Res;
802     if (int Res =
803             cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
804       return Res;
805     return cmpNumbers(
806         (uint64_t)CI->getMetadata(LLVMContext::MD_range),
807         (uint64_t)cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
808   }
809   if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
810     if (int Res = cmpNumbers(CI->getCallingConv(),
811                              cast<InvokeInst>(R)->getCallingConv()))
812       return Res;
813     if (int Res =
814             cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
815       return Res;
816     return cmpNumbers(
817         (uint64_t)CI->getMetadata(LLVMContext::MD_range),
818         (uint64_t)cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
819   }
820   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
821     ArrayRef<unsigned> LIndices = IVI->getIndices();
822     ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
823     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
824       return Res;
825     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
826       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
827         return Res;
828     }
829   }
830   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
831     ArrayRef<unsigned> LIndices = EVI->getIndices();
832     ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
833     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
834       return Res;
835     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
836       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
837         return Res;
838     }
839   }
840   if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
841     if (int Res =
842             cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
843       return Res;
844     return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
845   }
846
847   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
848     if (int Res = cmpNumbers(CXI->isVolatile(),
849                              cast<AtomicCmpXchgInst>(R)->isVolatile()))
850       return Res;
851     if (int Res = cmpNumbers(CXI->isWeak(),
852                              cast<AtomicCmpXchgInst>(R)->isWeak()))
853       return Res;
854     if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
855                              cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
856       return Res;
857     if (int Res = cmpNumbers(CXI->getFailureOrdering(),
858                              cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
859       return Res;
860     return cmpNumbers(CXI->getSynchScope(),
861                       cast<AtomicCmpXchgInst>(R)->getSynchScope());
862   }
863   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
864     if (int Res = cmpNumbers(RMWI->getOperation(),
865                              cast<AtomicRMWInst>(R)->getOperation()))
866       return Res;
867     if (int Res = cmpNumbers(RMWI->isVolatile(),
868                              cast<AtomicRMWInst>(R)->isVolatile()))
869       return Res;
870     if (int Res = cmpNumbers(RMWI->getOrdering(),
871                              cast<AtomicRMWInst>(R)->getOrdering()))
872       return Res;
873     return cmpNumbers(RMWI->getSynchScope(),
874                       cast<AtomicRMWInst>(R)->getSynchScope());
875   }
876   return 0;
877 }
878
879 // Determine whether two GEP operations perform the same underlying arithmetic.
880 // Read method declaration comments for more details.
881 int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
882                                const GEPOperator *GEPR) {
883
884   unsigned int ASL = GEPL->getPointerAddressSpace();
885   unsigned int ASR = GEPR->getPointerAddressSpace();
886
887   if (int Res = cmpNumbers(ASL, ASR))
888     return Res;
889
890   // When we have target data, we can reduce the GEP down to the value in bytes
891   // added to the address.
892   const DataLayout &DL = FnL->getParent()->getDataLayout();
893   unsigned BitWidth = DL.getPointerSizeInBits(ASL);
894   APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
895   if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
896       GEPR->accumulateConstantOffset(DL, OffsetR))
897     return cmpAPInts(OffsetL, OffsetR);
898
899   if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
900                            (uint64_t)GEPR->getPointerOperand()->getType()))
901     return Res;
902
903   if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
904     return Res;
905
906   for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
907     if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
908       return Res;
909   }
910
911   return 0;
912 }
913
914 /// Compare two values used by the two functions under pair-wise comparison. If
915 /// this is the first time the values are seen, they're added to the mapping so
916 /// that we will detect mismatches on next use.
917 /// See comments in declaration for more details.
918 int FunctionComparator::cmpValues(const Value *L, const Value *R) {
919   // Catch self-reference case.
920   if (L == FnL) {
921     if (R == FnR)
922       return 0;
923     return -1;
924   }
925   if (R == FnR) {
926     if (L == FnL)
927       return 0;
928     return 1;
929   }
930
931   const Constant *ConstL = dyn_cast<Constant>(L);
932   const Constant *ConstR = dyn_cast<Constant>(R);
933   if (ConstL && ConstR) {
934     if (L == R)
935       return 0;
936     return cmpConstants(ConstL, ConstR);
937   }
938
939   if (ConstL)
940     return 1;
941   if (ConstR)
942     return -1;
943
944   const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
945   const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
946
947   if (InlineAsmL && InlineAsmR)
948     return cmpNumbers((uint64_t)L, (uint64_t)R);
949   if (InlineAsmL)
950     return 1;
951   if (InlineAsmR)
952     return -1;
953
954   auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
955        RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
956
957   return cmpNumbers(LeftSN.first->second, RightSN.first->second);
958 }
959 // Test whether two basic blocks have equivalent behaviour.
960 int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
961   BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
962   BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
963
964   do {
965     if (int Res = cmpValues(InstL, InstR))
966       return Res;
967
968     const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
969     const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
970
971     if (GEPL && !GEPR)
972       return 1;
973     if (GEPR && !GEPL)
974       return -1;
975
976     if (GEPL && GEPR) {
977       if (int Res =
978               cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
979         return Res;
980       if (int Res = cmpGEPs(GEPL, GEPR))
981         return Res;
982     } else {
983       if (int Res = cmpOperations(InstL, InstR))
984         return Res;
985       assert(InstL->getNumOperands() == InstR->getNumOperands());
986
987       for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
988         Value *OpL = InstL->getOperand(i);
989         Value *OpR = InstR->getOperand(i);
990         if (int Res = cmpValues(OpL, OpR))
991           return Res;
992         if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
993           return Res;
994         // TODO: Already checked in cmpOperation
995         if (int Res = cmpTypes(OpL->getType(), OpR->getType()))
996           return Res;
997       }
998     }
999
1000     ++InstL, ++InstR;
1001   } while (InstL != InstLE && InstR != InstRE);
1002
1003   if (InstL != InstLE && InstR == InstRE)
1004     return 1;
1005   if (InstL == InstLE && InstR != InstRE)
1006     return -1;
1007   return 0;
1008 }
1009
1010 // Test whether the two functions have equivalent behaviour.
1011 int FunctionComparator::compare() {
1012
1013   sn_mapL.clear();
1014   sn_mapR.clear();
1015
1016   if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1017     return Res;
1018
1019   if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1020     return Res;
1021
1022   if (FnL->hasGC()) {
1023     if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
1024       return Res;
1025   }
1026
1027   if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1028     return Res;
1029
1030   if (FnL->hasSection()) {
1031     if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
1032       return Res;
1033   }
1034
1035   if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1036     return Res;
1037
1038   // TODO: if it's internal and only used in direct calls, we could handle this
1039   // case too.
1040   if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1041     return Res;
1042
1043   if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
1044     return Res;
1045
1046   assert(FnL->arg_size() == FnR->arg_size() &&
1047          "Identically typed functions have different numbers of args!");
1048
1049   // Visit the arguments so that they get enumerated in the order they're
1050   // passed in.
1051   for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1052                                     ArgRI = FnR->arg_begin(),
1053                                     ArgLE = FnL->arg_end();
1054        ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1055     if (cmpValues(ArgLI, ArgRI) != 0)
1056       llvm_unreachable("Arguments repeat!");
1057   }
1058
1059   // We do a CFG-ordered walk since the actual ordering of the blocks in the
1060   // linked list is immaterial. Our walk starts at the entry block for both
1061   // functions, then takes each block from each terminator in order. As an
1062   // artifact, this also means that unreachable blocks are ignored.
1063   SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
1064   SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
1065
1066   FnLBBs.push_back(&FnL->getEntryBlock());
1067   FnRBBs.push_back(&FnR->getEntryBlock());
1068
1069   VisitedBBs.insert(FnLBBs[0]);
1070   while (!FnLBBs.empty()) {
1071     const BasicBlock *BBL = FnLBBs.pop_back_val();
1072     const BasicBlock *BBR = FnRBBs.pop_back_val();
1073
1074     if (int Res = cmpValues(BBL, BBR))
1075       return Res;
1076
1077     if (int Res = compare(BBL, BBR))
1078       return Res;
1079
1080     const TerminatorInst *TermL = BBL->getTerminator();
1081     const TerminatorInst *TermR = BBR->getTerminator();
1082
1083     assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1084     for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
1085       if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
1086         continue;
1087
1088       FnLBBs.push_back(TermL->getSuccessor(i));
1089       FnRBBs.push_back(TermR->getSuccessor(i));
1090     }
1091   }
1092   return 0;
1093 }
1094
1095 // Accumulate the hash of a sequence of 64-bit integers. This is similar to a
1096 // hash of a sequence of 64bit ints, but the entire input does not need to be
1097 // available at once. This interface is necessary for functionHash because it
1098 // needs to accumulate the hash as the structure of the function is traversed
1099 // without saving these values to an intermediate buffer. This form of hashing
1100 // is not often needed, as usually the object to hash is just read from a
1101 // buffer.
1102 class HashAccumulator64 {
1103   uint64_t Hash;
1104 public:
1105   // Initialize to random constant, so the state isn't zero.
1106   HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
1107   void add(uint64_t V) {
1108      Hash = llvm::hashing::detail::hash_16_bytes(Hash, V);
1109   }
1110   // No finishing is required, because the entire hash value is used.
1111   uint64_t getHash() { return Hash; }
1112 };
1113
1114 // A function hash is calculated by considering only the number of arguments and
1115 // whether a function is varargs, the order of basic blocks (given by the
1116 // successors of each basic block in depth first order), and the order of
1117 // opcodes of each instruction within each of these basic blocks. This mirrors
1118 // the strategy compare() uses to compare functions by walking the BBs in depth
1119 // first order and comparing each instruction in sequence. Because this hash
1120 // does not look at the operands, it is insensitive to things such as the
1121 // target of calls and the constants used in the function, which makes it useful
1122 // when possibly merging functions which are the same modulo constants and call
1123 // targets.
1124 FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
1125   HashAccumulator64 H;
1126   H.add(F.isVarArg());
1127   H.add(F.arg_size());
1128   
1129   SmallVector<const BasicBlock *, 8> BBs;
1130   SmallSet<const BasicBlock *, 16> VisitedBBs;
1131
1132   // Walk the blocks in the same order as FunctionComparator::compare(),
1133   // accumulating the hash of the function "structure." (BB and opcode sequence)
1134   BBs.push_back(&F.getEntryBlock());
1135   VisitedBBs.insert(BBs[0]);
1136   while (!BBs.empty()) {
1137     const BasicBlock *BB = BBs.pop_back_val();
1138     // This random value acts as a block header, as otherwise the partition of
1139     // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
1140     H.add(45798); 
1141     for (auto &Inst : *BB) {
1142       H.add(Inst.getOpcode());
1143     }
1144     const TerminatorInst *Term = BB->getTerminator();
1145     for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
1146       if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
1147         continue;
1148       BBs.push_back(Term->getSuccessor(i));
1149     }
1150   }
1151   return H.getHash();
1152 }
1153
1154
1155 namespace {
1156
1157 /// MergeFunctions finds functions which will generate identical machine code,
1158 /// by considering all pointer types to be equivalent. Once identified,
1159 /// MergeFunctions will fold them by replacing a call to one to a call to a
1160 /// bitcast of the other.
1161 ///
1162 class MergeFunctions : public ModulePass {
1163 public:
1164   static char ID;
1165   MergeFunctions()
1166     : ModulePass(ID), HasGlobalAliases(false) {
1167     initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1168   }
1169
1170   bool runOnModule(Module &M) override;
1171
1172 private:
1173   typedef std::set<FunctionNode> FnTreeType;
1174
1175   /// A work queue of functions that may have been modified and should be
1176   /// analyzed again.
1177   std::vector<WeakVH> Deferred;
1178
1179   /// Checks the rules of order relation introduced among functions set.
1180   /// Returns true, if sanity check has been passed, and false if failed.
1181   bool doSanityCheck(std::vector<WeakVH> &Worklist);
1182
1183   /// Insert a ComparableFunction into the FnTree, or merge it away if it's
1184   /// equal to one that's already present.
1185   bool insert(Function *NewFunction);
1186
1187   /// Remove a Function from the FnTree and queue it up for a second sweep of
1188   /// analysis.
1189   void remove(Function *F);
1190
1191   /// Find the functions that use this Value and remove them from FnTree and
1192   /// queue the functions.
1193   void removeUsers(Value *V);
1194
1195   /// Replace all direct calls of Old with calls of New. Will bitcast New if
1196   /// necessary to make types match.
1197   void replaceDirectCallers(Function *Old, Function *New);
1198
1199   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1200   /// be converted into a thunk. In either case, it should never be visited
1201   /// again.
1202   void mergeTwoFunctions(Function *F, Function *G);
1203
1204   /// Replace G with a thunk or an alias to F. Deletes G.
1205   void writeThunkOrAlias(Function *F, Function *G);
1206
1207   /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1208   /// of G with bitcast(F). Deletes G.
1209   void writeThunk(Function *F, Function *G);
1210
1211   /// Replace G with an alias to F. Deletes G.
1212   void writeAlias(Function *F, Function *G);
1213
1214   /// Replace function F with function G in the function tree.
1215   void replaceFunctionInTree(FnTreeType::iterator &IterToF, Function *G);
1216
1217   /// The set of all distinct functions. Use the insert() and remove() methods
1218   /// to modify it.
1219   FnTreeType FnTree;
1220
1221   /// Whether or not the target supports global aliases.
1222   bool HasGlobalAliases;
1223 };
1224
1225 }  // end anonymous namespace
1226
1227 char MergeFunctions::ID = 0;
1228 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1229
1230 ModulePass *llvm::createMergeFunctionsPass() {
1231   return new MergeFunctions();
1232 }
1233
1234 bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1235   if (const unsigned Max = NumFunctionsForSanityCheck) {
1236     unsigned TripleNumber = 0;
1237     bool Valid = true;
1238
1239     dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1240
1241     unsigned i = 0;
1242     for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1243          I != E && i < Max; ++I, ++i) {
1244       unsigned j = i;
1245       for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1246         Function *F1 = cast<Function>(*I);
1247         Function *F2 = cast<Function>(*J);
1248         int Res1 = FunctionComparator(F1, F2).compare();
1249         int Res2 = FunctionComparator(F2, F1).compare();
1250
1251         // If F1 <= F2, then F2 >= F1, otherwise report failure.
1252         if (Res1 != -Res2) {
1253           dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1254                  << "\n";
1255           F1->dump();
1256           F2->dump();
1257           Valid = false;
1258         }
1259
1260         if (Res1 == 0)
1261           continue;
1262
1263         unsigned k = j;
1264         for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1265              ++k, ++K, ++TripleNumber) {
1266           if (K == J)
1267             continue;
1268
1269           Function *F3 = cast<Function>(*K);
1270           int Res3 = FunctionComparator(F1, F3).compare();
1271           int Res4 = FunctionComparator(F2, F3).compare();
1272
1273           bool Transitive = true;
1274
1275           if (Res1 != 0 && Res1 == Res4) {
1276             // F1 > F2, F2 > F3 => F1 > F3
1277             Transitive = Res3 == Res1;
1278           } else if (Res3 != 0 && Res3 == -Res4) {
1279             // F1 > F3, F3 > F2 => F1 > F2
1280             Transitive = Res3 == Res1;
1281           } else if (Res4 != 0 && -Res3 == Res4) {
1282             // F2 > F3, F3 > F1 => F2 > F1
1283             Transitive = Res4 == -Res1;
1284           }
1285
1286           if (!Transitive) {
1287             dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1288                    << TripleNumber << "\n";
1289             dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1290                    << Res4 << "\n";
1291             F1->dump();
1292             F2->dump();
1293             F3->dump();
1294             Valid = false;
1295           }
1296         }
1297       }
1298     }
1299
1300     dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1301     return Valid;
1302   }
1303   return true;
1304 }
1305
1306 bool MergeFunctions::runOnModule(Module &M) {
1307   bool Changed = false;
1308
1309   // All functions in the module, ordered by hash. Functions with a unique
1310   // hash value are easily eliminated.
1311   std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
1312     HashedFuncs;
1313   for (Function &Func : M) {
1314     if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
1315       HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
1316     } 
1317   }
1318
1319   std::sort(HashedFuncs.begin(), HashedFuncs.end());
1320
1321   auto S = HashedFuncs.begin();
1322   for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
1323     // If the hash value matches the previous value or the next one, we must
1324     // consider merging it. Otherwise it is dropped and never considered again.
1325     if ((I != S && std::prev(I)->first == I->first) ||
1326         (std::next(I) != IE && std::next(I)->first == I->first) ) {
1327       Deferred.push_back(WeakVH(I->second));
1328     }
1329   }
1330   
1331   do {
1332     std::vector<WeakVH> Worklist;
1333     Deferred.swap(Worklist);
1334
1335     DEBUG(doSanityCheck(Worklist));
1336
1337     DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1338     DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1339
1340     // Insert only strong functions and merge them. Strong function merging
1341     // always deletes one of them.
1342     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1343            E = Worklist.end(); I != E; ++I) {
1344       if (!*I) continue;
1345       Function *F = cast<Function>(*I);
1346       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1347           !F->mayBeOverridden()) {
1348         Changed |= insert(F);
1349       }
1350     }
1351
1352     // Insert only weak functions and merge them. By doing these second we
1353     // create thunks to the strong function when possible. When two weak
1354     // functions are identical, we create a new strong function with two weak
1355     // weak thunks to it which are identical but not mergable.
1356     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1357            E = Worklist.end(); I != E; ++I) {
1358       if (!*I) continue;
1359       Function *F = cast<Function>(*I);
1360       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1361           F->mayBeOverridden()) {
1362         Changed |= insert(F);
1363       }
1364     }
1365     DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
1366   } while (!Deferred.empty());
1367
1368   FnTree.clear();
1369
1370   return Changed;
1371 }
1372
1373 // Replace direct callers of Old with New.
1374 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1375   Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
1376   for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1377     Use *U = &*UI;
1378     ++UI;
1379     CallSite CS(U->getUser());
1380     if (CS && CS.isCallee(U)) {
1381       // Transfer the called function's attributes to the call site. Due to the
1382       // bitcast we will 'loose' ABI changing attributes because the 'called
1383       // function' is no longer a Function* but the bitcast. Code that looks up
1384       // the attributes from the called function will fail.
1385       auto &Context = New->getContext();
1386       auto NewFuncAttrs = New->getAttributes();
1387       auto CallSiteAttrs = CS.getAttributes();
1388
1389       CallSiteAttrs = CallSiteAttrs.addAttributes(
1390           Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
1391
1392       for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
1393         AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
1394         if (Attrs.getNumSlots())
1395           CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
1396       }
1397
1398       CS.setAttributes(CallSiteAttrs);
1399
1400       remove(CS.getInstruction()->getParent()->getParent());
1401       U->set(BitcastNew);
1402     }
1403   }
1404 }
1405
1406 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1407 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
1408   if (HasGlobalAliases && G->hasUnnamedAddr()) {
1409     if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1410         G->hasWeakLinkage()) {
1411       writeAlias(F, G);
1412       return;
1413     }
1414   }
1415
1416   writeThunk(F, G);
1417 }
1418
1419 // Helper for writeThunk,
1420 // Selects proper bitcast operation,
1421 // but a bit simpler then CastInst::getCastOpcode.
1422 static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
1423   Type *SrcTy = V->getType();
1424   if (SrcTy->isStructTy()) {
1425     assert(DestTy->isStructTy());
1426     assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1427     Value *Result = UndefValue::get(DestTy);
1428     for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1429       Value *Element = createCast(
1430           Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
1431           DestTy->getStructElementType(I));
1432
1433       Result =
1434           Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
1435     }
1436     return Result;
1437   }
1438   assert(!DestTy->isStructTy());
1439   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1440     return Builder.CreateIntToPtr(V, DestTy);
1441   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1442     return Builder.CreatePtrToInt(V, DestTy);
1443   else
1444     return Builder.CreateBitCast(V, DestTy);
1445 }
1446
1447 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
1448 // of G with bitcast(F). Deletes G.
1449 void MergeFunctions::writeThunk(Function *F, Function *G) {
1450   if (!G->mayBeOverridden()) {
1451     // Redirect direct callers of G to F.
1452     replaceDirectCallers(G, F);
1453   }
1454
1455   // If G was internal then we may have replaced all uses of G with F. If so,
1456   // stop here and delete G. There's no need for a thunk.
1457   if (G->hasLocalLinkage() && G->use_empty()) {
1458     G->eraseFromParent();
1459     return;
1460   }
1461
1462   Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1463                                     G->getParent());
1464   BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
1465   IRBuilder<false> Builder(BB);
1466
1467   SmallVector<Value *, 16> Args;
1468   unsigned i = 0;
1469   FunctionType *FFTy = F->getFunctionType();
1470   for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1471        AI != AE; ++AI) {
1472     Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
1473     ++i;
1474   }
1475
1476   CallInst *CI = Builder.CreateCall(F, Args);
1477   CI->setTailCall();
1478   CI->setCallingConv(F->getCallingConv());
1479   if (NewG->getReturnType()->isVoidTy()) {
1480     Builder.CreateRetVoid();
1481   } else {
1482     Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
1483   }
1484
1485   NewG->copyAttributesFrom(G);
1486   NewG->takeName(G);
1487   removeUsers(G);
1488   G->replaceAllUsesWith(NewG);
1489   G->eraseFromParent();
1490
1491   DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
1492   ++NumThunksWritten;
1493 }
1494
1495 // Replace G with an alias to F and delete G.
1496 void MergeFunctions::writeAlias(Function *F, Function *G) {
1497   PointerType *PTy = G->getType();
1498   auto *GA = GlobalAlias::create(PTy, G->getLinkage(), "", F);
1499   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1500   GA->takeName(G);
1501   GA->setVisibility(G->getVisibility());
1502   removeUsers(G);
1503   G->replaceAllUsesWith(GA);
1504   G->eraseFromParent();
1505
1506   DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
1507   ++NumAliasesWritten;
1508 }
1509
1510 // Merge two equivalent functions. Upon completion, Function G is deleted.
1511 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
1512   if (F->mayBeOverridden()) {
1513     assert(G->mayBeOverridden());
1514
1515     // Make them both thunks to the same internal function.
1516     Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1517                                    F->getParent());
1518     H->copyAttributesFrom(F);
1519     H->takeName(F);
1520     removeUsers(F);
1521     F->replaceAllUsesWith(H);
1522
1523     unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1524
1525     if (HasGlobalAliases) {
1526       writeAlias(F, G);
1527       writeAlias(F, H);
1528     } else {
1529       writeThunk(F, G);
1530       writeThunk(F, H);
1531     }
1532
1533     F->setAlignment(MaxAlignment);
1534     F->setLinkage(GlobalValue::PrivateLinkage);
1535     ++NumDoubleWeak;
1536   } else {
1537     writeThunkOrAlias(F, G);
1538   }
1539
1540   ++NumFunctionsMerged;
1541 }
1542
1543 /// Replace function F for function G in the map.
1544 void MergeFunctions::replaceFunctionInTree(FnTreeType::iterator &IterToF,
1545                                            Function *G) {
1546   Function *F = IterToF->getFunc();
1547
1548   // A total order is already guaranteed otherwise because we process strong
1549   // functions before weak functions.
1550   assert(((F->mayBeOverridden() && G->mayBeOverridden()) ||
1551           (!F->mayBeOverridden() && !G->mayBeOverridden())) &&
1552          "Only change functions if both are strong or both are weak");
1553   (void)F;
1554
1555   IterToF->replaceBy(G);
1556 }
1557
1558 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
1559 // that was already inserted.
1560 bool MergeFunctions::insert(Function *NewFunction) {
1561   std::pair<FnTreeType::iterator, bool> Result =
1562       FnTree.insert(FunctionNode(NewFunction));
1563
1564   if (Result.second) {
1565     DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
1566     return false;
1567   }
1568
1569   const FunctionNode &OldF = *Result.first;
1570
1571   // Don't merge tiny functions, since it can just end up making the function
1572   // larger.
1573   // FIXME: Should still merge them if they are unnamed_addr and produce an
1574   // alias.
1575   if (NewFunction->size() == 1) {
1576     if (NewFunction->front().size() <= 2) {
1577       DEBUG(dbgs() << NewFunction->getName()
1578                    << " is to small to bother merging\n");
1579       return false;
1580     }
1581   }
1582
1583   // Impose a total order (by name) on the replacement of functions. This is
1584   // important when operating on more than one module independently to prevent
1585   // cycles of thunks calling each other when the modules are linked together.
1586   //
1587   // When one function is weak and the other is strong there is an order imposed
1588   // already. We process strong functions before weak functions.
1589   if ((OldF.getFunc()->mayBeOverridden() && NewFunction->mayBeOverridden()) ||
1590       (!OldF.getFunc()->mayBeOverridden() && !NewFunction->mayBeOverridden()))
1591     if (OldF.getFunc()->getName() > NewFunction->getName()) {
1592       // Swap the two functions.
1593       Function *F = OldF.getFunc();
1594       replaceFunctionInTree(Result.first, NewFunction);
1595       NewFunction = F;
1596       assert(OldF.getFunc() != F && "Must have swapped the functions.");
1597     }
1598
1599   // Never thunk a strong function to a weak function.
1600   assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
1601
1602   DEBUG(dbgs() << "  " << OldF.getFunc()->getName()
1603                << " == " << NewFunction->getName() << '\n');
1604
1605   Function *DeleteF = NewFunction;
1606   mergeTwoFunctions(OldF.getFunc(), DeleteF);
1607   return true;
1608 }
1609
1610 // Remove a function from FnTree. If it was already in FnTree, add
1611 // it to Deferred so that we'll look at it in the next round.
1612 void MergeFunctions::remove(Function *F) {
1613   // We need to make sure we remove F, not a function "equal" to F per the
1614   // function equality comparator.
1615   FnTreeType::iterator found = FnTree.find(FunctionNode(F));
1616   size_t Erased = 0;
1617   if (found != FnTree.end() && found->getFunc() == F) {
1618     Erased = 1;
1619     FnTree.erase(found);
1620   }
1621
1622   if (Erased) {
1623     DEBUG(dbgs() << "Removed " << F->getName()
1624                  << " from set and deferred it.\n");
1625     Deferred.emplace_back(F);
1626   }
1627 }
1628
1629 // For each instruction used by the value, remove() the function that contains
1630 // the instruction. This should happen right before a call to RAUW.
1631 void MergeFunctions::removeUsers(Value *V) {
1632   std::vector<Value *> Worklist;
1633   Worklist.push_back(V);
1634   SmallSet<Value*, 8> Visited;
1635   Visited.insert(V);
1636   while (!Worklist.empty()) {
1637     Value *V = Worklist.back();
1638     Worklist.pop_back();
1639
1640     for (User *U : V->users()) {
1641       if (Instruction *I = dyn_cast<Instruction>(U)) {
1642         remove(I->getParent()->getParent());
1643       } else if (isa<GlobalValue>(U)) {
1644         // do nothing
1645       } else if (Constant *C = dyn_cast<Constant>(U)) {
1646         for (User *UU : C->users()) {
1647           if (!Visited.insert(UU).second)
1648             Worklist.push_back(UU);
1649         }
1650       }
1651     }
1652   }
1653 }