1 //===- FunctionComparator.h - Function Comparator -------------------------===//
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 file implements the FunctionComparator and GlobalNumberState classes
11 // which are used by the MergeFunctions pass for comparing functions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/FunctionComparator.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/IR/CallSite.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/InlineAsm.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "functioncomparator"
27 
28 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
29   if (L < R) return -1;
30   if (L > R) return 1;
31   return 0;
32 }
33 
34 int FunctionComparator::cmpOrderings(AtomicOrdering L, AtomicOrdering R) const {
35   if ((int)L < (int)R) return -1;
36   if ((int)L > (int)R) return 1;
37   return 0;
38 }
39 
40 int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
41   if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
42     return Res;
43   if (L.ugt(R)) return 1;
44   if (R.ugt(L)) return -1;
45   return 0;
46 }
47 
48 int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
49   // Floats are ordered first by semantics (i.e. float, double, half, etc.),
50   // then by value interpreted as a bitstring (aka APInt).
51   const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics();
52   if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL),
53                            APFloat::semanticsPrecision(SR)))
54     return Res;
55   if (int Res = cmpNumbers(APFloat::semanticsMaxExponent(SL),
56                            APFloat::semanticsMaxExponent(SR)))
57     return Res;
58   if (int Res = cmpNumbers(APFloat::semanticsMinExponent(SL),
59                            APFloat::semanticsMinExponent(SR)))
60     return Res;
61   if (int Res = cmpNumbers(APFloat::semanticsSizeInBits(SL),
62                            APFloat::semanticsSizeInBits(SR)))
63     return Res;
64   return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
65 }
66 
67 int FunctionComparator::cmpMem(StringRef L, StringRef R) const {
68   // Prevent heavy comparison, compare sizes first.
69   if (int Res = cmpNumbers(L.size(), R.size()))
70     return Res;
71 
72   // Compare strings lexicographically only when it is necessary: only when
73   // strings are equal in size.
74   return L.compare(R);
75 }
76 
77 int FunctionComparator::cmpAttrs(const AttributeSet L,
78                                  const AttributeSet R) const {
79   if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
80     return Res;
81 
82   for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
83     AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
84                            RE = R.end(i);
85     for (; LI != LE && RI != RE; ++LI, ++RI) {
86       Attribute LA = *LI;
87       Attribute RA = *RI;
88       if (LA < RA)
89         return -1;
90       if (RA < LA)
91         return 1;
92     }
93     if (LI != LE)
94       return 1;
95     if (RI != RE)
96       return -1;
97   }
98   return 0;
99 }
100 
101 int FunctionComparator::cmpRangeMetadata(const MDNode *L,
102                                          const MDNode *R) const {
103   if (L == R)
104     return 0;
105   if (!L)
106     return -1;
107   if (!R)
108     return 1;
109   // Range metadata is a sequence of numbers. Make sure they are the same
110   // sequence.
111   // TODO: Note that as this is metadata, it is possible to drop and/or merge
112   // this data when considering functions to merge. Thus this comparison would
113   // return 0 (i.e. equivalent), but merging would become more complicated
114   // because the ranges would need to be unioned. It is not likely that
115   // functions differ ONLY in this metadata if they are actually the same
116   // function semantically.
117   if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
118     return Res;
119   for (size_t I = 0; I < L->getNumOperands(); ++I) {
120     ConstantInt *LLow = mdconst::extract<ConstantInt>(L->getOperand(I));
121     ConstantInt *RLow = mdconst::extract<ConstantInt>(R->getOperand(I));
122     if (int Res = cmpAPInts(LLow->getValue(), RLow->getValue()))
123       return Res;
124   }
125   return 0;
126 }
127 
128 int FunctionComparator::cmpOperandBundlesSchema(const Instruction *L,
129                                                 const Instruction *R) const {
130   ImmutableCallSite LCS(L);
131   ImmutableCallSite RCS(R);
132 
133   assert(LCS && RCS && "Must be calls or invokes!");
134   assert(LCS.isCall() == RCS.isCall() && "Can't compare otherwise!");
135 
136   if (int Res =
137           cmpNumbers(LCS.getNumOperandBundles(), RCS.getNumOperandBundles()))
138     return Res;
139 
140   for (unsigned i = 0, e = LCS.getNumOperandBundles(); i != e; ++i) {
141     auto OBL = LCS.getOperandBundleAt(i);
142     auto OBR = RCS.getOperandBundleAt(i);
143 
144     if (int Res = OBL.getTagName().compare(OBR.getTagName()))
145       return Res;
146 
147     if (int Res = cmpNumbers(OBL.Inputs.size(), OBR.Inputs.size()))
148       return Res;
149   }
150 
151   return 0;
152 }
153 
154 /// Constants comparison:
155 /// 1. Check whether type of L constant could be losslessly bitcasted to R
156 /// type.
157 /// 2. Compare constant contents.
158 /// For more details see declaration comments.
159 int FunctionComparator::cmpConstants(const Constant *L,
160                                      const Constant *R) const {
161 
162   Type *TyL = L->getType();
163   Type *TyR = R->getType();
164 
165   // Check whether types are bitcastable. This part is just re-factored
166   // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
167   // we also pack into result which type is "less" for us.
168   int TypesRes = cmpTypes(TyL, TyR);
169   if (TypesRes != 0) {
170     // Types are different, but check whether we can bitcast them.
171     if (!TyL->isFirstClassType()) {
172       if (TyR->isFirstClassType())
173         return -1;
174       // Neither TyL nor TyR are values of first class type. Return the result
175       // of comparing the types
176       return TypesRes;
177     }
178     if (!TyR->isFirstClassType()) {
179       if (TyL->isFirstClassType())
180         return 1;
181       return TypesRes;
182     }
183 
184     // Vector -> Vector conversions are always lossless if the two vector types
185     // have the same size, otherwise not.
186     unsigned TyLWidth = 0;
187     unsigned TyRWidth = 0;
188 
189     if (auto *VecTyL = dyn_cast<VectorType>(TyL))
190       TyLWidth = VecTyL->getBitWidth();
191     if (auto *VecTyR = dyn_cast<VectorType>(TyR))
192       TyRWidth = VecTyR->getBitWidth();
193 
194     if (TyLWidth != TyRWidth)
195       return cmpNumbers(TyLWidth, TyRWidth);
196 
197     // Zero bit-width means neither TyL nor TyR are vectors.
198     if (!TyLWidth) {
199       PointerType *PTyL = dyn_cast<PointerType>(TyL);
200       PointerType *PTyR = dyn_cast<PointerType>(TyR);
201       if (PTyL && PTyR) {
202         unsigned AddrSpaceL = PTyL->getAddressSpace();
203         unsigned AddrSpaceR = PTyR->getAddressSpace();
204         if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
205           return Res;
206       }
207       if (PTyL)
208         return 1;
209       if (PTyR)
210         return -1;
211 
212       // TyL and TyR aren't vectors, nor pointers. We don't know how to
213       // bitcast them.
214       return TypesRes;
215     }
216   }
217 
218   // OK, types are bitcastable, now check constant contents.
219 
220   if (L->isNullValue() && R->isNullValue())
221     return TypesRes;
222   if (L->isNullValue() && !R->isNullValue())
223     return 1;
224   if (!L->isNullValue() && R->isNullValue())
225     return -1;
226 
227   auto GlobalValueL = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(L));
228   auto GlobalValueR = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(R));
229   if (GlobalValueL && GlobalValueR) {
230     return cmpGlobalValues(GlobalValueL, GlobalValueR);
231   }
232 
233   if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
234     return Res;
235 
236   if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) {
237     const auto *SeqR = cast<ConstantDataSequential>(R);
238     // This handles ConstantDataArray and ConstantDataVector. Note that we
239     // compare the two raw data arrays, which might differ depending on the host
240     // endianness. This isn't a problem though, because the endiness of a module
241     // will affect the order of the constants, but this order is the same
242     // for a given input module and host platform.
243     return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues());
244   }
245 
246   switch (L->getValueID()) {
247   case Value::UndefValueVal:
248   case Value::ConstantTokenNoneVal:
249     return TypesRes;
250   case Value::ConstantIntVal: {
251     const APInt &LInt = cast<ConstantInt>(L)->getValue();
252     const APInt &RInt = cast<ConstantInt>(R)->getValue();
253     return cmpAPInts(LInt, RInt);
254   }
255   case Value::ConstantFPVal: {
256     const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
257     const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
258     return cmpAPFloats(LAPF, RAPF);
259   }
260   case Value::ConstantArrayVal: {
261     const ConstantArray *LA = cast<ConstantArray>(L);
262     const ConstantArray *RA = cast<ConstantArray>(R);
263     uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
264     uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
265     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
266       return Res;
267     for (uint64_t i = 0; i < NumElementsL; ++i) {
268       if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
269                                  cast<Constant>(RA->getOperand(i))))
270         return Res;
271     }
272     return 0;
273   }
274   case Value::ConstantStructVal: {
275     const ConstantStruct *LS = cast<ConstantStruct>(L);
276     const ConstantStruct *RS = cast<ConstantStruct>(R);
277     unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
278     unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
279     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
280       return Res;
281     for (unsigned i = 0; i != NumElementsL; ++i) {
282       if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
283                                  cast<Constant>(RS->getOperand(i))))
284         return Res;
285     }
286     return 0;
287   }
288   case Value::ConstantVectorVal: {
289     const ConstantVector *LV = cast<ConstantVector>(L);
290     const ConstantVector *RV = cast<ConstantVector>(R);
291     unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
292     unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
293     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
294       return Res;
295     for (uint64_t i = 0; i < NumElementsL; ++i) {
296       if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
297                                  cast<Constant>(RV->getOperand(i))))
298         return Res;
299     }
300     return 0;
301   }
302   case Value::ConstantExprVal: {
303     const ConstantExpr *LE = cast<ConstantExpr>(L);
304     const ConstantExpr *RE = cast<ConstantExpr>(R);
305     unsigned NumOperandsL = LE->getNumOperands();
306     unsigned NumOperandsR = RE->getNumOperands();
307     if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
308       return Res;
309     for (unsigned i = 0; i < NumOperandsL; ++i) {
310       if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
311                                  cast<Constant>(RE->getOperand(i))))
312         return Res;
313     }
314     return 0;
315   }
316   case Value::BlockAddressVal: {
317     const BlockAddress *LBA = cast<BlockAddress>(L);
318     const BlockAddress *RBA = cast<BlockAddress>(R);
319     if (int Res = cmpValues(LBA->getFunction(), RBA->getFunction()))
320       return Res;
321     if (LBA->getFunction() == RBA->getFunction()) {
322       // They are BBs in the same function. Order by which comes first in the
323       // BB order of the function. This order is deterministic.
324       Function* F = LBA->getFunction();
325       BasicBlock *LBB = LBA->getBasicBlock();
326       BasicBlock *RBB = RBA->getBasicBlock();
327       if (LBB == RBB)
328         return 0;
329       for(BasicBlock &BB : F->getBasicBlockList()) {
330         if (&BB == LBB) {
331           assert(&BB != RBB);
332           return -1;
333         }
334         if (&BB == RBB)
335           return 1;
336       }
337       llvm_unreachable("Basic Block Address does not point to a basic block in "
338                        "its function.");
339       return -1;
340     } else {
341       // cmpValues said the functions are the same. So because they aren't
342       // literally the same pointer, they must respectively be the left and
343       // right functions.
344       assert(LBA->getFunction() == FnL && RBA->getFunction() == FnR);
345       // cmpValues will tell us if these are equivalent BasicBlocks, in the
346       // context of their respective functions.
347       return cmpValues(LBA->getBasicBlock(), RBA->getBasicBlock());
348     }
349   }
350   default: // Unknown constant, abort.
351     DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n");
352     llvm_unreachable("Constant ValueID not recognized.");
353     return -1;
354   }
355 }
356 
357 int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue *R) const {
358   uint64_t LNumber = GlobalNumbers->getNumber(L);
359   uint64_t RNumber = GlobalNumbers->getNumber(R);
360   return cmpNumbers(LNumber, RNumber);
361 }
362 
363 /// cmpType - compares two types,
364 /// defines total ordering among the types set.
365 /// See method declaration comments for more details.
366 int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
367   PointerType *PTyL = dyn_cast<PointerType>(TyL);
368   PointerType *PTyR = dyn_cast<PointerType>(TyR);
369 
370   const DataLayout &DL = FnL->getParent()->getDataLayout();
371   if (PTyL && PTyL->getAddressSpace() == 0)
372     TyL = DL.getIntPtrType(TyL);
373   if (PTyR && PTyR->getAddressSpace() == 0)
374     TyR = DL.getIntPtrType(TyR);
375 
376   if (TyL == TyR)
377     return 0;
378 
379   if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
380     return Res;
381 
382   switch (TyL->getTypeID()) {
383   default:
384     llvm_unreachable("Unknown type!");
385     // Fall through in Release mode.
386     LLVM_FALLTHROUGH;
387   case Type::IntegerTyID:
388     return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(),
389                       cast<IntegerType>(TyR)->getBitWidth());
390   case Type::VectorTyID: {
391     VectorType *VTyL = cast<VectorType>(TyL), *VTyR = cast<VectorType>(TyR);
392     if (int Res = cmpNumbers(VTyL->getNumElements(), VTyR->getNumElements()))
393       return Res;
394     return cmpTypes(VTyL->getElementType(), VTyR->getElementType());
395   }
396   // TyL == TyR would have returned true earlier, because types are uniqued.
397   case Type::VoidTyID:
398   case Type::FloatTyID:
399   case Type::DoubleTyID:
400   case Type::X86_FP80TyID:
401   case Type::FP128TyID:
402   case Type::PPC_FP128TyID:
403   case Type::LabelTyID:
404   case Type::MetadataTyID:
405   case Type::TokenTyID:
406     return 0;
407 
408   case Type::PointerTyID: {
409     assert(PTyL && PTyR && "Both types must be pointers here.");
410     return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
411   }
412 
413   case Type::StructTyID: {
414     StructType *STyL = cast<StructType>(TyL);
415     StructType *STyR = cast<StructType>(TyR);
416     if (STyL->getNumElements() != STyR->getNumElements())
417       return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
418 
419     if (STyL->isPacked() != STyR->isPacked())
420       return cmpNumbers(STyL->isPacked(), STyR->isPacked());
421 
422     for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
423       if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
424         return Res;
425     }
426     return 0;
427   }
428 
429   case Type::FunctionTyID: {
430     FunctionType *FTyL = cast<FunctionType>(TyL);
431     FunctionType *FTyR = cast<FunctionType>(TyR);
432     if (FTyL->getNumParams() != FTyR->getNumParams())
433       return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
434 
435     if (FTyL->isVarArg() != FTyR->isVarArg())
436       return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
437 
438     if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
439       return Res;
440 
441     for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
442       if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
443         return Res;
444     }
445     return 0;
446   }
447 
448   case Type::ArrayTyID: {
449     ArrayType *ATyL = cast<ArrayType>(TyL);
450     ArrayType *ATyR = cast<ArrayType>(TyR);
451     if (ATyL->getNumElements() != ATyR->getNumElements())
452       return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
453     return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
454   }
455   }
456 }
457 
458 // Determine whether the two operations are the same except that pointer-to-A
459 // and pointer-to-B are equivalent. This should be kept in sync with
460 // Instruction::isSameOperationAs.
461 // Read method declaration comments for more details.
462 int FunctionComparator::cmpOperations(const Instruction *L,
463                                       const Instruction *R,
464                                       bool &needToCmpOperands) const {
465   needToCmpOperands = true;
466   if (int Res = cmpValues(L, R))
467     return Res;
468 
469   // Differences from Instruction::isSameOperationAs:
470   //  * replace type comparison with calls to cmpTypes.
471   //  * we test for I->getRawSubclassOptionalData (nuw/nsw/tail) at the top.
472   //  * because of the above, we don't test for the tail bit on calls later on.
473   if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
474     return Res;
475 
476   if (const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(L)) {
477     needToCmpOperands = false;
478     const GetElementPtrInst *GEPR = cast<GetElementPtrInst>(R);
479     if (int Res =
480             cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
481       return Res;
482     return cmpGEPs(GEPL, GEPR);
483   }
484 
485   if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
486     return Res;
487 
488   if (int Res = cmpTypes(L->getType(), R->getType()))
489     return Res;
490 
491   if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
492                            R->getRawSubclassOptionalData()))
493     return Res;
494 
495   // We have two instructions of identical opcode and #operands.  Check to see
496   // if all operands are the same type
497   for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
498     if (int Res =
499             cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
500       return Res;
501   }
502 
503   // Check special state that is a part of some instructions.
504   if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
505     if (int Res = cmpTypes(AI->getAllocatedType(),
506                            cast<AllocaInst>(R)->getAllocatedType()))
507       return Res;
508     return cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment());
509   }
510   if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
511     if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
512       return Res;
513     if (int Res =
514             cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
515       return Res;
516     if (int Res =
517             cmpOrderings(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
518       return Res;
519     if (int Res =
520             cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
521       return Res;
522     return cmpRangeMetadata(LI->getMetadata(LLVMContext::MD_range),
523         cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
524   }
525   if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
526     if (int Res =
527             cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
528       return Res;
529     if (int Res =
530             cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
531       return Res;
532     if (int Res =
533             cmpOrderings(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
534       return Res;
535     return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
536   }
537   if (const CmpInst *CI = dyn_cast<CmpInst>(L))
538     return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
539   if (const CallInst *CI = dyn_cast<CallInst>(L)) {
540     if (int Res = cmpNumbers(CI->getCallingConv(),
541                              cast<CallInst>(R)->getCallingConv()))
542       return Res;
543     if (int Res =
544             cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
545       return Res;
546     if (int Res = cmpOperandBundlesSchema(CI, R))
547       return Res;
548     return cmpRangeMetadata(
549         CI->getMetadata(LLVMContext::MD_range),
550         cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
551   }
552   if (const InvokeInst *II = dyn_cast<InvokeInst>(L)) {
553     if (int Res = cmpNumbers(II->getCallingConv(),
554                              cast<InvokeInst>(R)->getCallingConv()))
555       return Res;
556     if (int Res =
557             cmpAttrs(II->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
558       return Res;
559     if (int Res = cmpOperandBundlesSchema(II, R))
560       return Res;
561     return cmpRangeMetadata(
562         II->getMetadata(LLVMContext::MD_range),
563         cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
564   }
565   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
566     ArrayRef<unsigned> LIndices = IVI->getIndices();
567     ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
568     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
569       return Res;
570     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
571       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
572         return Res;
573     }
574     return 0;
575   }
576   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
577     ArrayRef<unsigned> LIndices = EVI->getIndices();
578     ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
579     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
580       return Res;
581     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
582       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
583         return Res;
584     }
585   }
586   if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
587     if (int Res =
588             cmpOrderings(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
589       return Res;
590     return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
591   }
592   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
593     if (int Res = cmpNumbers(CXI->isVolatile(),
594                              cast<AtomicCmpXchgInst>(R)->isVolatile()))
595       return Res;
596     if (int Res = cmpNumbers(CXI->isWeak(),
597                              cast<AtomicCmpXchgInst>(R)->isWeak()))
598       return Res;
599     if (int Res =
600             cmpOrderings(CXI->getSuccessOrdering(),
601                          cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
602       return Res;
603     if (int Res =
604             cmpOrderings(CXI->getFailureOrdering(),
605                          cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
606       return Res;
607     return cmpNumbers(CXI->getSynchScope(),
608                       cast<AtomicCmpXchgInst>(R)->getSynchScope());
609   }
610   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
611     if (int Res = cmpNumbers(RMWI->getOperation(),
612                              cast<AtomicRMWInst>(R)->getOperation()))
613       return Res;
614     if (int Res = cmpNumbers(RMWI->isVolatile(),
615                              cast<AtomicRMWInst>(R)->isVolatile()))
616       return Res;
617     if (int Res = cmpOrderings(RMWI->getOrdering(),
618                              cast<AtomicRMWInst>(R)->getOrdering()))
619       return Res;
620     return cmpNumbers(RMWI->getSynchScope(),
621                       cast<AtomicRMWInst>(R)->getSynchScope());
622   }
623   if (const PHINode *PNL = dyn_cast<PHINode>(L)) {
624     const PHINode *PNR = cast<PHINode>(R);
625     // Ensure that in addition to the incoming values being identical
626     // (checked by the caller of this function), the incoming blocks
627     // are also identical.
628     for (unsigned i = 0, e = PNL->getNumIncomingValues(); i != e; ++i) {
629       if (int Res =
630               cmpValues(PNL->getIncomingBlock(i), PNR->getIncomingBlock(i)))
631         return Res;
632     }
633   }
634   return 0;
635 }
636 
637 // Determine whether two GEP operations perform the same underlying arithmetic.
638 // Read method declaration comments for more details.
639 int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
640                                 const GEPOperator *GEPR) const {
641 
642   unsigned int ASL = GEPL->getPointerAddressSpace();
643   unsigned int ASR = GEPR->getPointerAddressSpace();
644 
645   if (int Res = cmpNumbers(ASL, ASR))
646     return Res;
647 
648   // When we have target data, we can reduce the GEP down to the value in bytes
649   // added to the address.
650   const DataLayout &DL = FnL->getParent()->getDataLayout();
651   unsigned BitWidth = DL.getPointerSizeInBits(ASL);
652   APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
653   if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
654       GEPR->accumulateConstantOffset(DL, OffsetR))
655     return cmpAPInts(OffsetL, OffsetR);
656   if (int Res = cmpTypes(GEPL->getSourceElementType(),
657                          GEPR->getSourceElementType()))
658     return Res;
659 
660   if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
661     return Res;
662 
663   for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
664     if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
665       return Res;
666   }
667 
668   return 0;
669 }
670 
671 int FunctionComparator::cmpInlineAsm(const InlineAsm *L,
672                                      const InlineAsm *R) const {
673   // InlineAsm's are uniqued. If they are the same pointer, obviously they are
674   // the same, otherwise compare the fields.
675   if (L == R)
676     return 0;
677   if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType()))
678     return Res;
679   if (int Res = cmpMem(L->getAsmString(), R->getAsmString()))
680     return Res;
681   if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString()))
682     return Res;
683   if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects()))
684     return Res;
685   if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack()))
686     return Res;
687   if (int Res = cmpNumbers(L->getDialect(), R->getDialect()))
688     return Res;
689   llvm_unreachable("InlineAsm blocks were not uniqued.");
690   return 0;
691 }
692 
693 /// Compare two values used by the two functions under pair-wise comparison. If
694 /// this is the first time the values are seen, they're added to the mapping so
695 /// that we will detect mismatches on next use.
696 /// See comments in declaration for more details.
697 int FunctionComparator::cmpValues(const Value *L, const Value *R) const {
698   // Catch self-reference case.
699   if (L == FnL) {
700     if (R == FnR)
701       return 0;
702     return -1;
703   }
704   if (R == FnR) {
705     if (L == FnL)
706       return 0;
707     return 1;
708   }
709 
710   const Constant *ConstL = dyn_cast<Constant>(L);
711   const Constant *ConstR = dyn_cast<Constant>(R);
712   if (ConstL && ConstR) {
713     if (L == R)
714       return 0;
715     return cmpConstants(ConstL, ConstR);
716   }
717 
718   if (ConstL)
719     return 1;
720   if (ConstR)
721     return -1;
722 
723   const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
724   const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
725 
726   if (InlineAsmL && InlineAsmR)
727     return cmpInlineAsm(InlineAsmL, InlineAsmR);
728   if (InlineAsmL)
729     return 1;
730   if (InlineAsmR)
731     return -1;
732 
733   auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
734        RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
735 
736   return cmpNumbers(LeftSN.first->second, RightSN.first->second);
737 }
738 
739 // Test whether two basic blocks have equivalent behaviour.
740 int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL,
741                                        const BasicBlock *BBR) const {
742   BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
743   BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
744 
745   do {
746     bool needToCmpOperands = true;
747     if (int Res = cmpOperations(&*InstL, &*InstR, needToCmpOperands))
748       return Res;
749     if (needToCmpOperands) {
750       assert(InstL->getNumOperands() == InstR->getNumOperands());
751 
752       for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
753         Value *OpL = InstL->getOperand(i);
754         Value *OpR = InstR->getOperand(i);
755         if (int Res = cmpValues(OpL, OpR))
756           return Res;
757         // cmpValues should ensure this is true.
758         assert(cmpTypes(OpL->getType(), OpR->getType()) == 0);
759       }
760     }
761 
762     ++InstL;
763     ++InstR;
764   } while (InstL != InstLE && InstR != InstRE);
765 
766   if (InstL != InstLE && InstR == InstRE)
767     return 1;
768   if (InstL == InstLE && InstR != InstRE)
769     return -1;
770   return 0;
771 }
772 
773 int FunctionComparator::compareSignature() const {
774   if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
775     return Res;
776 
777   if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
778     return Res;
779 
780   if (FnL->hasGC()) {
781     if (int Res = cmpMem(FnL->getGC(), FnR->getGC()))
782       return Res;
783   }
784 
785   if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
786     return Res;
787 
788   if (FnL->hasSection()) {
789     if (int Res = cmpMem(FnL->getSection(), FnR->getSection()))
790       return Res;
791   }
792 
793   if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
794     return Res;
795 
796   // TODO: if it's internal and only used in direct calls, we could handle this
797   // case too.
798   if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
799     return Res;
800 
801   if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
802     return Res;
803 
804   assert(FnL->arg_size() == FnR->arg_size() &&
805          "Identically typed functions have different numbers of args!");
806 
807   // Visit the arguments so that they get enumerated in the order they're
808   // passed in.
809   for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
810        ArgRI = FnR->arg_begin(),
811        ArgLE = FnL->arg_end();
812        ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
813     if (cmpValues(&*ArgLI, &*ArgRI) != 0)
814       llvm_unreachable("Arguments repeat!");
815   }
816   return 0;
817 }
818 
819 // Test whether the two functions have equivalent behaviour.
820 int FunctionComparator::compare() {
821   beginCompare();
822 
823   if (int Res = compareSignature())
824     return Res;
825 
826   // We do a CFG-ordered walk since the actual ordering of the blocks in the
827   // linked list is immaterial. Our walk starts at the entry block for both
828   // functions, then takes each block from each terminator in order. As an
829   // artifact, this also means that unreachable blocks are ignored.
830   SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
831   SmallPtrSet<const BasicBlock *, 32> VisitedBBs; // in terms of F1.
832 
833   FnLBBs.push_back(&FnL->getEntryBlock());
834   FnRBBs.push_back(&FnR->getEntryBlock());
835 
836   VisitedBBs.insert(FnLBBs[0]);
837   while (!FnLBBs.empty()) {
838     const BasicBlock *BBL = FnLBBs.pop_back_val();
839     const BasicBlock *BBR = FnRBBs.pop_back_val();
840 
841     if (int Res = cmpValues(BBL, BBR))
842       return Res;
843 
844     if (int Res = cmpBasicBlocks(BBL, BBR))
845       return Res;
846 
847     const TerminatorInst *TermL = BBL->getTerminator();
848     const TerminatorInst *TermR = BBR->getTerminator();
849 
850     assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
851     for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
852       if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
853         continue;
854 
855       FnLBBs.push_back(TermL->getSuccessor(i));
856       FnRBBs.push_back(TermR->getSuccessor(i));
857     }
858   }
859   return 0;
860 }
861 
862 namespace {
863 
864 // Accumulate the hash of a sequence of 64-bit integers. This is similar to a
865 // hash of a sequence of 64bit ints, but the entire input does not need to be
866 // available at once. This interface is necessary for functionHash because it
867 // needs to accumulate the hash as the structure of the function is traversed
868 // without saving these values to an intermediate buffer. This form of hashing
869 // is not often needed, as usually the object to hash is just read from a
870 // buffer.
871 class HashAccumulator64 {
872   uint64_t Hash;
873 public:
874   // Initialize to random constant, so the state isn't zero.
875   HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
876   void add(uint64_t V) {
877      Hash = llvm::hashing::detail::hash_16_bytes(Hash, V);
878   }
879   // No finishing is required, because the entire hash value is used.
880   uint64_t getHash() { return Hash; }
881 };
882 } // end anonymous namespace
883 
884 // A function hash is calculated by considering only the number of arguments and
885 // whether a function is varargs, the order of basic blocks (given by the
886 // successors of each basic block in depth first order), and the order of
887 // opcodes of each instruction within each of these basic blocks. This mirrors
888 // the strategy compare() uses to compare functions by walking the BBs in depth
889 // first order and comparing each instruction in sequence. Because this hash
890 // does not look at the operands, it is insensitive to things such as the
891 // target of calls and the constants used in the function, which makes it useful
892 // when possibly merging functions which are the same modulo constants and call
893 // targets.
894 FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
895   HashAccumulator64 H;
896   H.add(F.isVarArg());
897   H.add(F.arg_size());
898 
899   SmallVector<const BasicBlock *, 8> BBs;
900   SmallSet<const BasicBlock *, 16> VisitedBBs;
901 
902   // Walk the blocks in the same order as FunctionComparator::cmpBasicBlocks(),
903   // accumulating the hash of the function "structure." (BB and opcode sequence)
904   BBs.push_back(&F.getEntryBlock());
905   VisitedBBs.insert(BBs[0]);
906   while (!BBs.empty()) {
907     const BasicBlock *BB = BBs.pop_back_val();
908     // This random value acts as a block header, as otherwise the partition of
909     // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
910     H.add(45798);
911     for (auto &Inst : *BB) {
912       H.add(Inst.getOpcode());
913     }
914     const TerminatorInst *Term = BB->getTerminator();
915     for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
916       if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
917         continue;
918       BBs.push_back(Term->getSuccessor(i));
919     }
920   }
921   return H.getHash();
922 }
923 
924 
925