10b57cec5SDimitry Andric //===-- DifferenceEngine.cpp - Structural function/module comparison ------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This header defines the implementation of the LLVM difference
100b57cec5SDimitry Andric // engine, which structurally compares global values within a module.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "DifferenceEngine.h"
150b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
160b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
175ffd83dbSDimitry Andric #include "llvm/ADT/SmallString.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/StringSet.h"
200b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
210b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
220b57cec5SDimitry Andric #include "llvm/IR/Function.h"
230b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
240b57cec5SDimitry Andric #include "llvm/IR/Module.h"
250b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
260b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
270b57cec5SDimitry Andric #include "llvm/Support/type_traits.h"
280b57cec5SDimitry Andric #include <utility>
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric using namespace llvm;
310b57cec5SDimitry Andric 
320b57cec5SDimitry Andric namespace {
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric /// A priority queue, implemented as a heap.
350b57cec5SDimitry Andric template <class T, class Sorter, unsigned InlineCapacity>
360b57cec5SDimitry Andric class PriorityQueue {
370b57cec5SDimitry Andric   Sorter Precedes;
380b57cec5SDimitry Andric   llvm::SmallVector<T, InlineCapacity> Storage;
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric public:
PriorityQueue(const Sorter & Precedes)410b57cec5SDimitry Andric   PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric   /// Checks whether the heap is empty.
empty() const440b57cec5SDimitry Andric   bool empty() const { return Storage.empty(); }
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric   /// Insert a new value on the heap.
insert(const T & V)470b57cec5SDimitry Andric   void insert(const T &V) {
480b57cec5SDimitry Andric     unsigned Index = Storage.size();
490b57cec5SDimitry Andric     Storage.push_back(V);
500b57cec5SDimitry Andric     if (Index == 0) return;
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric     T *data = Storage.data();
530b57cec5SDimitry Andric     while (true) {
540b57cec5SDimitry Andric       unsigned Target = (Index + 1) / 2 - 1;
550b57cec5SDimitry Andric       if (!Precedes(data[Index], data[Target])) return;
560b57cec5SDimitry Andric       std::swap(data[Index], data[Target]);
570b57cec5SDimitry Andric       if (Target == 0) return;
580b57cec5SDimitry Andric       Index = Target;
590b57cec5SDimitry Andric     }
600b57cec5SDimitry Andric   }
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric   /// Remove the minimum value in the heap.  Only valid on a non-empty heap.
remove_min()630b57cec5SDimitry Andric   T remove_min() {
640b57cec5SDimitry Andric     assert(!empty());
650b57cec5SDimitry Andric     T tmp = Storage[0];
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric     unsigned NewSize = Storage.size() - 1;
680b57cec5SDimitry Andric     if (NewSize) {
690b57cec5SDimitry Andric       // Move the slot at the end to the beginning.
70af732203SDimitry Andric       if (std::is_trivially_copyable<T>::value)
710b57cec5SDimitry Andric         Storage[0] = Storage[NewSize];
720b57cec5SDimitry Andric       else
730b57cec5SDimitry Andric         std::swap(Storage[0], Storage[NewSize]);
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric       // Bubble the root up as necessary.
760b57cec5SDimitry Andric       unsigned Index = 0;
770b57cec5SDimitry Andric       while (true) {
780b57cec5SDimitry Andric         // With a 1-based index, the children would be Index*2 and Index*2+1.
790b57cec5SDimitry Andric         unsigned R = (Index + 1) * 2;
800b57cec5SDimitry Andric         unsigned L = R - 1;
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric         // If R is out of bounds, we're done after this in any case.
830b57cec5SDimitry Andric         if (R >= NewSize) {
840b57cec5SDimitry Andric           // If L is also out of bounds, we're done immediately.
850b57cec5SDimitry Andric           if (L >= NewSize) break;
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric           // Otherwise, test whether we should swap L and Index.
880b57cec5SDimitry Andric           if (Precedes(Storage[L], Storage[Index]))
890b57cec5SDimitry Andric             std::swap(Storage[L], Storage[Index]);
900b57cec5SDimitry Andric           break;
910b57cec5SDimitry Andric         }
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric         // Otherwise, we need to compare with the smaller of L and R.
940b57cec5SDimitry Andric         // Prefer R because it's closer to the end of the array.
950b57cec5SDimitry Andric         unsigned IndexToTest = (Precedes(Storage[L], Storage[R]) ? L : R);
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric         // If Index is >= the min of L and R, then heap ordering is restored.
980b57cec5SDimitry Andric         if (!Precedes(Storage[IndexToTest], Storage[Index]))
990b57cec5SDimitry Andric           break;
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric         // Otherwise, keep bubbling up.
1020b57cec5SDimitry Andric         std::swap(Storage[IndexToTest], Storage[Index]);
1030b57cec5SDimitry Andric         Index = IndexToTest;
1040b57cec5SDimitry Andric       }
1050b57cec5SDimitry Andric     }
1060b57cec5SDimitry Andric     Storage.pop_back();
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric     return tmp;
1090b57cec5SDimitry Andric   }
1100b57cec5SDimitry Andric };
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric /// A function-scope difference engine.
1130b57cec5SDimitry Andric class FunctionDifferenceEngine {
1140b57cec5SDimitry Andric   DifferenceEngine &Engine;
1150b57cec5SDimitry Andric 
116*5f7ddb14SDimitry Andric   // Some initializers may reference the variable we're currently checking. This
117*5f7ddb14SDimitry Andric   // can cause an infinite loop. The Saved[LR]HS ivars can be checked to prevent
118*5f7ddb14SDimitry Andric   // recursing.
119*5f7ddb14SDimitry Andric   const Value *SavedLHS;
120*5f7ddb14SDimitry Andric   const Value *SavedRHS;
121*5f7ddb14SDimitry Andric 
1220b57cec5SDimitry Andric   /// The current mapping from old local values to new local values.
123*5f7ddb14SDimitry Andric   DenseMap<const Value *, const Value *> Values;
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   /// The current mapping from old blocks to new blocks.
126*5f7ddb14SDimitry Andric   DenseMap<const BasicBlock *, const BasicBlock *> Blocks;
1270b57cec5SDimitry Andric 
128*5f7ddb14SDimitry Andric   DenseSet<std::pair<const Value *, const Value *>> TentativeValues;
1290b57cec5SDimitry Andric 
getUnprocPredCount(const BasicBlock * Block) const130*5f7ddb14SDimitry Andric   unsigned getUnprocPredCount(const BasicBlock *Block) const {
1310b57cec5SDimitry Andric     unsigned Count = 0;
132*5f7ddb14SDimitry Andric     for (const_pred_iterator I = pred_begin(Block), E = pred_end(Block); I != E;
133*5f7ddb14SDimitry Andric          ++I)
1340b57cec5SDimitry Andric       if (!Blocks.count(*I)) Count++;
1350b57cec5SDimitry Andric     return Count;
1360b57cec5SDimitry Andric   }
1370b57cec5SDimitry Andric 
138*5f7ddb14SDimitry Andric   typedef std::pair<const BasicBlock *, const BasicBlock *> BlockPair;
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   /// A type which sorts a priority queue by the number of unprocessed
1410b57cec5SDimitry Andric   /// predecessor blocks it has remaining.
1420b57cec5SDimitry Andric   ///
1430b57cec5SDimitry Andric   /// This is actually really expensive to calculate.
1440b57cec5SDimitry Andric   struct QueueSorter {
1450b57cec5SDimitry Andric     const FunctionDifferenceEngine &fde;
QueueSorter__anon3906a3ef0111::FunctionDifferenceEngine::QueueSorter1460b57cec5SDimitry Andric     explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
1470b57cec5SDimitry Andric 
operator ()__anon3906a3ef0111::FunctionDifferenceEngine::QueueSorter148*5f7ddb14SDimitry Andric     bool operator()(BlockPair &Old, BlockPair &New) {
1490b57cec5SDimitry Andric       return fde.getUnprocPredCount(Old.first)
1500b57cec5SDimitry Andric            < fde.getUnprocPredCount(New.first);
1510b57cec5SDimitry Andric     }
1520b57cec5SDimitry Andric   };
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   /// A queue of unified blocks to process.
1550b57cec5SDimitry Andric   PriorityQueue<BlockPair, QueueSorter, 20> Queue;
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric   /// Try to unify the given two blocks.  Enqueues them for processing
1580b57cec5SDimitry Andric   /// if they haven't already been processed.
1590b57cec5SDimitry Andric   ///
1600b57cec5SDimitry Andric   /// Returns true if there was a problem unifying them.
tryUnify(const BasicBlock * L,const BasicBlock * R)161*5f7ddb14SDimitry Andric   bool tryUnify(const BasicBlock *L, const BasicBlock *R) {
162*5f7ddb14SDimitry Andric     const BasicBlock *&Ref = Blocks[L];
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric     if (Ref) {
1650b57cec5SDimitry Andric       if (Ref == R) return false;
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric       Engine.logf("successor %l cannot be equivalent to %r; "
1680b57cec5SDimitry Andric                   "it's already equivalent to %r")
1690b57cec5SDimitry Andric         << L << R << Ref;
1700b57cec5SDimitry Andric       return true;
1710b57cec5SDimitry Andric     }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric     Ref = R;
1740b57cec5SDimitry Andric     Queue.insert(BlockPair(L, R));
1750b57cec5SDimitry Andric     return false;
1760b57cec5SDimitry Andric   }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   /// Unifies two instructions, given that they're known not to have
1790b57cec5SDimitry Andric   /// structural differences.
unify(const Instruction * L,const Instruction * R)180*5f7ddb14SDimitry Andric   void unify(const Instruction *L, const Instruction *R) {
1810b57cec5SDimitry Andric     DifferenceEngine::Context C(Engine, L, R);
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric     bool Result = diff(L, R, true, true);
1840b57cec5SDimitry Andric     assert(!Result && "structural differences second time around?");
1850b57cec5SDimitry Andric     (void) Result;
1860b57cec5SDimitry Andric     if (!L->use_empty())
1870b57cec5SDimitry Andric       Values[L] = R;
1880b57cec5SDimitry Andric   }
1890b57cec5SDimitry Andric 
processQueue()1900b57cec5SDimitry Andric   void processQueue() {
1910b57cec5SDimitry Andric     while (!Queue.empty()) {
1920b57cec5SDimitry Andric       BlockPair Pair = Queue.remove_min();
1930b57cec5SDimitry Andric       diff(Pair.first, Pair.second);
1940b57cec5SDimitry Andric     }
1950b57cec5SDimitry Andric   }
1960b57cec5SDimitry Andric 
diff(const BasicBlock * L,const BasicBlock * R)197*5f7ddb14SDimitry Andric   void diff(const BasicBlock *L, const BasicBlock *R) {
1980b57cec5SDimitry Andric     DifferenceEngine::Context C(Engine, L, R);
1990b57cec5SDimitry Andric 
200*5f7ddb14SDimitry Andric     BasicBlock::const_iterator LI = L->begin(), LE = L->end();
201*5f7ddb14SDimitry Andric     BasicBlock::const_iterator RI = R->begin();
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric     do {
2040b57cec5SDimitry Andric       assert(LI != LE && RI != R->end());
205*5f7ddb14SDimitry Andric       const Instruction *LeftI = &*LI, *RightI = &*RI;
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric       // If the instructions differ, start the more sophisticated diff
2080b57cec5SDimitry Andric       // algorithm at the start of the block.
2090b57cec5SDimitry Andric       if (diff(LeftI, RightI, false, false)) {
2100b57cec5SDimitry Andric         TentativeValues.clear();
2110b57cec5SDimitry Andric         return runBlockDiff(L->begin(), R->begin());
2120b57cec5SDimitry Andric       }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric       // Otherwise, tentatively unify them.
2150b57cec5SDimitry Andric       if (!LeftI->use_empty())
2160b57cec5SDimitry Andric         TentativeValues.insert(std::make_pair(LeftI, RightI));
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric       ++LI;
2190b57cec5SDimitry Andric       ++RI;
2200b57cec5SDimitry Andric     } while (LI != LE); // This is sufficient: we can't get equality of
2210b57cec5SDimitry Andric                         // terminators if there are residual instructions.
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric     // Unify everything in the block, non-tentatively this time.
2240b57cec5SDimitry Andric     TentativeValues.clear();
2250b57cec5SDimitry Andric     for (LI = L->begin(), RI = R->begin(); LI != LE; ++LI, ++RI)
2260b57cec5SDimitry Andric       unify(&*LI, &*RI);
2270b57cec5SDimitry Andric   }
2280b57cec5SDimitry Andric 
229*5f7ddb14SDimitry Andric   bool matchForBlockDiff(const Instruction *L, const Instruction *R);
230*5f7ddb14SDimitry Andric   void runBlockDiff(BasicBlock::const_iterator LI,
231*5f7ddb14SDimitry Andric                     BasicBlock::const_iterator RI);
2320b57cec5SDimitry Andric 
diffCallSites(const CallBase & L,const CallBase & R,bool Complain)233*5f7ddb14SDimitry Andric   bool diffCallSites(const CallBase &L, const CallBase &R, bool Complain) {
2340b57cec5SDimitry Andric     // FIXME: call attributes
2355ffd83dbSDimitry Andric     if (!equivalentAsOperands(L.getCalledOperand(), R.getCalledOperand())) {
2360b57cec5SDimitry Andric       if (Complain) Engine.log("called functions differ");
2370b57cec5SDimitry Andric       return true;
2380b57cec5SDimitry Andric     }
2390b57cec5SDimitry Andric     if (L.arg_size() != R.arg_size()) {
2400b57cec5SDimitry Andric       if (Complain) Engine.log("argument counts differ");
2410b57cec5SDimitry Andric       return true;
2420b57cec5SDimitry Andric     }
2430b57cec5SDimitry Andric     for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
2445ffd83dbSDimitry Andric       if (!equivalentAsOperands(L.getArgOperand(I), R.getArgOperand(I))) {
2450b57cec5SDimitry Andric         if (Complain)
2460b57cec5SDimitry Andric           Engine.logf("arguments %l and %r differ")
2475ffd83dbSDimitry Andric               << L.getArgOperand(I) << R.getArgOperand(I);
2480b57cec5SDimitry Andric         return true;
2490b57cec5SDimitry Andric       }
2500b57cec5SDimitry Andric     return false;
2510b57cec5SDimitry Andric   }
2520b57cec5SDimitry Andric 
diff(const Instruction * L,const Instruction * R,bool Complain,bool TryUnify)253*5f7ddb14SDimitry Andric   bool diff(const Instruction *L, const Instruction *R, bool Complain,
254*5f7ddb14SDimitry Andric             bool TryUnify) {
2550b57cec5SDimitry Andric     // FIXME: metadata (if Complain is set)
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     // Different opcodes always imply different operations.
2580b57cec5SDimitry Andric     if (L->getOpcode() != R->getOpcode()) {
2590b57cec5SDimitry Andric       if (Complain) Engine.log("different instruction types");
2600b57cec5SDimitry Andric       return true;
2610b57cec5SDimitry Andric     }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     if (isa<CmpInst>(L)) {
2640b57cec5SDimitry Andric       if (cast<CmpInst>(L)->getPredicate()
2650b57cec5SDimitry Andric             != cast<CmpInst>(R)->getPredicate()) {
2660b57cec5SDimitry Andric         if (Complain) Engine.log("different predicates");
2670b57cec5SDimitry Andric         return true;
2680b57cec5SDimitry Andric       }
2690b57cec5SDimitry Andric     } else if (isa<CallInst>(L)) {
2705ffd83dbSDimitry Andric       return diffCallSites(cast<CallInst>(*L), cast<CallInst>(*R), Complain);
2710b57cec5SDimitry Andric     } else if (isa<PHINode>(L)) {
2720b57cec5SDimitry Andric       // FIXME: implement.
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric       // This is really weird;  type uniquing is broken?
2750b57cec5SDimitry Andric       if (L->getType() != R->getType()) {
2760b57cec5SDimitry Andric         if (!L->getType()->isPointerTy() || !R->getType()->isPointerTy()) {
2770b57cec5SDimitry Andric           if (Complain) Engine.log("different phi types");
2780b57cec5SDimitry Andric           return true;
2790b57cec5SDimitry Andric         }
2800b57cec5SDimitry Andric       }
2810b57cec5SDimitry Andric       return false;
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric     // Terminators.
2840b57cec5SDimitry Andric     } else if (isa<InvokeInst>(L)) {
285*5f7ddb14SDimitry Andric       const InvokeInst &LI = cast<InvokeInst>(*L);
286*5f7ddb14SDimitry Andric       const InvokeInst &RI = cast<InvokeInst>(*R);
2875ffd83dbSDimitry Andric       if (diffCallSites(LI, RI, Complain))
2880b57cec5SDimitry Andric         return true;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric       if (TryUnify) {
2915ffd83dbSDimitry Andric         tryUnify(LI.getNormalDest(), RI.getNormalDest());
2925ffd83dbSDimitry Andric         tryUnify(LI.getUnwindDest(), RI.getUnwindDest());
2930b57cec5SDimitry Andric       }
2940b57cec5SDimitry Andric       return false;
2950b57cec5SDimitry Andric 
296*5f7ddb14SDimitry Andric     } else if (isa<CallBrInst>(L)) {
297*5f7ddb14SDimitry Andric       const CallBrInst &LI = cast<CallBrInst>(*L);
298*5f7ddb14SDimitry Andric       const CallBrInst &RI = cast<CallBrInst>(*R);
299*5f7ddb14SDimitry Andric       if (LI.getNumIndirectDests() != RI.getNumIndirectDests()) {
300*5f7ddb14SDimitry Andric         if (Complain)
301*5f7ddb14SDimitry Andric           Engine.log("callbr # of indirect destinations differ");
302*5f7ddb14SDimitry Andric         return true;
303*5f7ddb14SDimitry Andric       }
304*5f7ddb14SDimitry Andric 
305*5f7ddb14SDimitry Andric       // Perform the "try unify" step so that we can equate the indirect
306*5f7ddb14SDimitry Andric       // destinations before checking the call site.
307*5f7ddb14SDimitry Andric       for (unsigned I = 0; I < LI.getNumIndirectDests(); I++)
308*5f7ddb14SDimitry Andric         tryUnify(LI.getIndirectDest(I), RI.getIndirectDest(I));
309*5f7ddb14SDimitry Andric 
310*5f7ddb14SDimitry Andric       if (diffCallSites(LI, RI, Complain))
311*5f7ddb14SDimitry Andric         return true;
312*5f7ddb14SDimitry Andric 
313*5f7ddb14SDimitry Andric       if (TryUnify)
314*5f7ddb14SDimitry Andric         tryUnify(LI.getDefaultDest(), RI.getDefaultDest());
315*5f7ddb14SDimitry Andric       return false;
316*5f7ddb14SDimitry Andric 
3170b57cec5SDimitry Andric     } else if (isa<BranchInst>(L)) {
318*5f7ddb14SDimitry Andric       const BranchInst *LI = cast<BranchInst>(L);
319*5f7ddb14SDimitry Andric       const BranchInst *RI = cast<BranchInst>(R);
3200b57cec5SDimitry Andric       if (LI->isConditional() != RI->isConditional()) {
3210b57cec5SDimitry Andric         if (Complain) Engine.log("branch conditionality differs");
3220b57cec5SDimitry Andric         return true;
3230b57cec5SDimitry Andric       }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric       if (LI->isConditional()) {
3260b57cec5SDimitry Andric         if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
3270b57cec5SDimitry Andric           if (Complain) Engine.log("branch conditions differ");
3280b57cec5SDimitry Andric           return true;
3290b57cec5SDimitry Andric         }
3300b57cec5SDimitry Andric         if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
3310b57cec5SDimitry Andric       }
3320b57cec5SDimitry Andric       if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
3330b57cec5SDimitry Andric       return false;
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric     } else if (isa<IndirectBrInst>(L)) {
336*5f7ddb14SDimitry Andric       const IndirectBrInst *LI = cast<IndirectBrInst>(L);
337*5f7ddb14SDimitry Andric       const IndirectBrInst *RI = cast<IndirectBrInst>(R);
3380b57cec5SDimitry Andric       if (LI->getNumDestinations() != RI->getNumDestinations()) {
3390b57cec5SDimitry Andric         if (Complain) Engine.log("indirectbr # of destinations differ");
3400b57cec5SDimitry Andric         return true;
3410b57cec5SDimitry Andric       }
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric       if (!equivalentAsOperands(LI->getAddress(), RI->getAddress())) {
3440b57cec5SDimitry Andric         if (Complain) Engine.log("indirectbr addresses differ");
3450b57cec5SDimitry Andric         return true;
3460b57cec5SDimitry Andric       }
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric       if (TryUnify) {
3490b57cec5SDimitry Andric         for (unsigned i = 0; i < LI->getNumDestinations(); i++) {
3500b57cec5SDimitry Andric           tryUnify(LI->getDestination(i), RI->getDestination(i));
3510b57cec5SDimitry Andric         }
3520b57cec5SDimitry Andric       }
3530b57cec5SDimitry Andric       return false;
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric     } else if (isa<SwitchInst>(L)) {
356*5f7ddb14SDimitry Andric       const SwitchInst *LI = cast<SwitchInst>(L);
357*5f7ddb14SDimitry Andric       const SwitchInst *RI = cast<SwitchInst>(R);
3580b57cec5SDimitry Andric       if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
3590b57cec5SDimitry Andric         if (Complain) Engine.log("switch conditions differ");
3600b57cec5SDimitry Andric         return true;
3610b57cec5SDimitry Andric       }
3620b57cec5SDimitry Andric       if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric       bool Difference = false;
3650b57cec5SDimitry Andric 
366*5f7ddb14SDimitry Andric       DenseMap<const ConstantInt *, const BasicBlock *> LCases;
3670b57cec5SDimitry Andric       for (auto Case : LI->cases())
3680b57cec5SDimitry Andric         LCases[Case.getCaseValue()] = Case.getCaseSuccessor();
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric       for (auto Case : RI->cases()) {
371*5f7ddb14SDimitry Andric         const ConstantInt *CaseValue = Case.getCaseValue();
372*5f7ddb14SDimitry Andric         const BasicBlock *LCase = LCases[CaseValue];
3730b57cec5SDimitry Andric         if (LCase) {
3740b57cec5SDimitry Andric           if (TryUnify)
3750b57cec5SDimitry Andric             tryUnify(LCase, Case.getCaseSuccessor());
3760b57cec5SDimitry Andric           LCases.erase(CaseValue);
3770b57cec5SDimitry Andric         } else if (Complain || !Difference) {
3780b57cec5SDimitry Andric           if (Complain)
3790b57cec5SDimitry Andric             Engine.logf("right switch has extra case %r") << CaseValue;
3800b57cec5SDimitry Andric           Difference = true;
3810b57cec5SDimitry Andric         }
3820b57cec5SDimitry Andric       }
3830b57cec5SDimitry Andric       if (!Difference)
384*5f7ddb14SDimitry Andric         for (DenseMap<const ConstantInt *, const BasicBlock *>::iterator
385*5f7ddb14SDimitry Andric                  I = LCases.begin(),
386*5f7ddb14SDimitry Andric                  E = LCases.end();
387*5f7ddb14SDimitry Andric              I != E; ++I) {
3880b57cec5SDimitry Andric           if (Complain)
3890b57cec5SDimitry Andric             Engine.logf("left switch has extra case %l") << I->first;
3900b57cec5SDimitry Andric           Difference = true;
3910b57cec5SDimitry Andric         }
3920b57cec5SDimitry Andric       return Difference;
3930b57cec5SDimitry Andric     } else if (isa<UnreachableInst>(L)) {
3940b57cec5SDimitry Andric       return false;
3950b57cec5SDimitry Andric     }
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric     if (L->getNumOperands() != R->getNumOperands()) {
3980b57cec5SDimitry Andric       if (Complain) Engine.log("instructions have different operand counts");
3990b57cec5SDimitry Andric       return true;
4000b57cec5SDimitry Andric     }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
4030b57cec5SDimitry Andric       Value *LO = L->getOperand(I), *RO = R->getOperand(I);
4040b57cec5SDimitry Andric       if (!equivalentAsOperands(LO, RO)) {
4050b57cec5SDimitry Andric         if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
4060b57cec5SDimitry Andric         return true;
4070b57cec5SDimitry Andric       }
4080b57cec5SDimitry Andric     }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric     return false;
4110b57cec5SDimitry Andric   }
4120b57cec5SDimitry Andric 
413*5f7ddb14SDimitry Andric public:
equivalentAsOperands(const Constant * L,const Constant * R)414*5f7ddb14SDimitry Andric   bool equivalentAsOperands(const Constant *L, const Constant *R) {
4150b57cec5SDimitry Andric     // Use equality as a preliminary filter.
4160b57cec5SDimitry Andric     if (L == R)
4170b57cec5SDimitry Andric       return true;
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric     if (L->getValueID() != R->getValueID())
4200b57cec5SDimitry Andric       return false;
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric     // Ask the engine about global values.
4230b57cec5SDimitry Andric     if (isa<GlobalValue>(L))
4240b57cec5SDimitry Andric       return Engine.equivalentAsOperands(cast<GlobalValue>(L),
4250b57cec5SDimitry Andric                                          cast<GlobalValue>(R));
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric     // Compare constant expressions structurally.
4280b57cec5SDimitry Andric     if (isa<ConstantExpr>(L))
4290b57cec5SDimitry Andric       return equivalentAsOperands(cast<ConstantExpr>(L),
4300b57cec5SDimitry Andric                                   cast<ConstantExpr>(R));
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric     // Constants of the "same type" don't always actually have the same
4330b57cec5SDimitry Andric     // type; I don't know why.  Just white-list them.
4340b57cec5SDimitry Andric     if (isa<ConstantPointerNull>(L) || isa<UndefValue>(L) || isa<ConstantAggregateZero>(L))
4350b57cec5SDimitry Andric       return true;
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric     // Block addresses only match if we've already encountered the
4380b57cec5SDimitry Andric     // block.  FIXME: tentative matches?
4390b57cec5SDimitry Andric     if (isa<BlockAddress>(L))
4400b57cec5SDimitry Andric       return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
4410b57cec5SDimitry Andric                  == cast<BlockAddress>(R)->getBasicBlock();
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric     // If L and R are ConstantVectors, compare each element
4440b57cec5SDimitry Andric     if (isa<ConstantVector>(L)) {
445*5f7ddb14SDimitry Andric       const ConstantVector *CVL = cast<ConstantVector>(L);
446*5f7ddb14SDimitry Andric       const ConstantVector *CVR = cast<ConstantVector>(R);
4470b57cec5SDimitry Andric       if (CVL->getType()->getNumElements() != CVR->getType()->getNumElements())
4480b57cec5SDimitry Andric         return false;
4490b57cec5SDimitry Andric       for (unsigned i = 0; i < CVL->getType()->getNumElements(); i++) {
4500b57cec5SDimitry Andric         if (!equivalentAsOperands(CVL->getOperand(i), CVR->getOperand(i)))
4510b57cec5SDimitry Andric           return false;
4520b57cec5SDimitry Andric       }
4530b57cec5SDimitry Andric       return true;
4540b57cec5SDimitry Andric     }
4550b57cec5SDimitry Andric 
456*5f7ddb14SDimitry Andric     // If L and R are ConstantArrays, compare the element count and types.
457*5f7ddb14SDimitry Andric     if (isa<ConstantArray>(L)) {
458*5f7ddb14SDimitry Andric       const ConstantArray *CAL = cast<ConstantArray>(L);
459*5f7ddb14SDimitry Andric       const ConstantArray *CAR = cast<ConstantArray>(R);
460*5f7ddb14SDimitry Andric       // Sometimes a type may be equivalent, but not uniquified---e.g. it may
461*5f7ddb14SDimitry Andric       // contain a GEP instruction. Do a deeper comparison of the types.
462*5f7ddb14SDimitry Andric       if (CAL->getType()->getNumElements() != CAR->getType()->getNumElements())
463*5f7ddb14SDimitry Andric         return false;
464*5f7ddb14SDimitry Andric 
465*5f7ddb14SDimitry Andric       for (unsigned I = 0; I < CAL->getType()->getNumElements(); ++I) {
466*5f7ddb14SDimitry Andric         if (!equivalentAsOperands(CAL->getAggregateElement(I),
467*5f7ddb14SDimitry Andric                                   CAR->getAggregateElement(I)))
4680b57cec5SDimitry Andric           return false;
4690b57cec5SDimitry Andric       }
4700b57cec5SDimitry Andric 
471*5f7ddb14SDimitry Andric       return true;
472*5f7ddb14SDimitry Andric     }
473*5f7ddb14SDimitry Andric 
474*5f7ddb14SDimitry Andric     // If L and R are ConstantStructs, compare each field and type.
475*5f7ddb14SDimitry Andric     if (isa<ConstantStruct>(L)) {
476*5f7ddb14SDimitry Andric       const ConstantStruct *CSL = cast<ConstantStruct>(L);
477*5f7ddb14SDimitry Andric       const ConstantStruct *CSR = cast<ConstantStruct>(R);
478*5f7ddb14SDimitry Andric 
479*5f7ddb14SDimitry Andric       const StructType *LTy = cast<StructType>(CSL->getType());
480*5f7ddb14SDimitry Andric       const StructType *RTy = cast<StructType>(CSR->getType());
481*5f7ddb14SDimitry Andric 
482*5f7ddb14SDimitry Andric       // The StructTypes should have the same attributes. Don't use
483*5f7ddb14SDimitry Andric       // isLayoutIdentical(), because that just checks the element pointers,
484*5f7ddb14SDimitry Andric       // which may not work here.
485*5f7ddb14SDimitry Andric       if (LTy->getNumElements() != RTy->getNumElements() ||
486*5f7ddb14SDimitry Andric           LTy->isPacked() != RTy->isPacked())
487*5f7ddb14SDimitry Andric         return false;
488*5f7ddb14SDimitry Andric 
489*5f7ddb14SDimitry Andric       for (unsigned I = 0; I < LTy->getNumElements(); I++) {
490*5f7ddb14SDimitry Andric         const Value *LAgg = CSL->getAggregateElement(I);
491*5f7ddb14SDimitry Andric         const Value *RAgg = CSR->getAggregateElement(I);
492*5f7ddb14SDimitry Andric 
493*5f7ddb14SDimitry Andric         if (LAgg == SavedLHS || RAgg == SavedRHS) {
494*5f7ddb14SDimitry Andric           if (LAgg != SavedLHS || RAgg != SavedRHS)
495*5f7ddb14SDimitry Andric             // If the left and right operands aren't both re-analyzing the
496*5f7ddb14SDimitry Andric             // variable, then the initialiers don't match, so report "false".
497*5f7ddb14SDimitry Andric             // Otherwise, we skip these operands..
498*5f7ddb14SDimitry Andric             return false;
499*5f7ddb14SDimitry Andric 
500*5f7ddb14SDimitry Andric           continue;
501*5f7ddb14SDimitry Andric         }
502*5f7ddb14SDimitry Andric 
503*5f7ddb14SDimitry Andric         if (!equivalentAsOperands(LAgg, RAgg)) {
504*5f7ddb14SDimitry Andric           return false;
505*5f7ddb14SDimitry Andric         }
506*5f7ddb14SDimitry Andric       }
507*5f7ddb14SDimitry Andric 
508*5f7ddb14SDimitry Andric       return true;
509*5f7ddb14SDimitry Andric     }
510*5f7ddb14SDimitry Andric 
511*5f7ddb14SDimitry Andric     return false;
512*5f7ddb14SDimitry Andric   }
513*5f7ddb14SDimitry Andric 
equivalentAsOperands(const ConstantExpr * L,const ConstantExpr * R)514*5f7ddb14SDimitry Andric   bool equivalentAsOperands(const ConstantExpr *L, const ConstantExpr *R) {
5150b57cec5SDimitry Andric     if (L == R)
5160b57cec5SDimitry Andric       return true;
517*5f7ddb14SDimitry Andric 
5180b57cec5SDimitry Andric     if (L->getOpcode() != R->getOpcode())
5190b57cec5SDimitry Andric       return false;
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric     switch (L->getOpcode()) {
5220b57cec5SDimitry Andric     case Instruction::ICmp:
5230b57cec5SDimitry Andric     case Instruction::FCmp:
5240b57cec5SDimitry Andric       if (L->getPredicate() != R->getPredicate())
5250b57cec5SDimitry Andric         return false;
5260b57cec5SDimitry Andric       break;
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric     case Instruction::GetElementPtr:
5290b57cec5SDimitry Andric       // FIXME: inbounds?
5300b57cec5SDimitry Andric       break;
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric     default:
5330b57cec5SDimitry Andric       break;
5340b57cec5SDimitry Andric     }
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric     if (L->getNumOperands() != R->getNumOperands())
5370b57cec5SDimitry Andric       return false;
5380b57cec5SDimitry Andric 
539*5f7ddb14SDimitry Andric     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
540*5f7ddb14SDimitry Andric       const auto *LOp = L->getOperand(I);
541*5f7ddb14SDimitry Andric       const auto *ROp = R->getOperand(I);
542*5f7ddb14SDimitry Andric 
543*5f7ddb14SDimitry Andric       if (LOp == SavedLHS || ROp == SavedRHS) {
544*5f7ddb14SDimitry Andric         if (LOp != SavedLHS || ROp != SavedRHS)
545*5f7ddb14SDimitry Andric           // If the left and right operands aren't both re-analyzing the
546*5f7ddb14SDimitry Andric           // variable, then the initialiers don't match, so report "false".
547*5f7ddb14SDimitry Andric           // Otherwise, we skip these operands..
5480b57cec5SDimitry Andric           return false;
5490b57cec5SDimitry Andric 
550*5f7ddb14SDimitry Andric         continue;
551*5f7ddb14SDimitry Andric       }
552*5f7ddb14SDimitry Andric 
553*5f7ddb14SDimitry Andric       if (!equivalentAsOperands(LOp, ROp))
554*5f7ddb14SDimitry Andric         return false;
555*5f7ddb14SDimitry Andric     }
556*5f7ddb14SDimitry Andric 
5570b57cec5SDimitry Andric     return true;
5580b57cec5SDimitry Andric   }
5590b57cec5SDimitry Andric 
equivalentAsOperands(const Value * L,const Value * R)560*5f7ddb14SDimitry Andric   bool equivalentAsOperands(const Value *L, const Value *R) {
5610b57cec5SDimitry Andric     // Fall out if the values have different kind.
5620b57cec5SDimitry Andric     // This possibly shouldn't take priority over oracles.
5630b57cec5SDimitry Andric     if (L->getValueID() != R->getValueID())
5640b57cec5SDimitry Andric       return false;
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric     // Value subtypes:  Argument, Constant, Instruction, BasicBlock,
5670b57cec5SDimitry Andric     //                  InlineAsm, MDNode, MDString, PseudoSourceValue
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric     if (isa<Constant>(L))
5700b57cec5SDimitry Andric       return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R));
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric     if (isa<Instruction>(L))
5730b57cec5SDimitry Andric       return Values[L] == R || TentativeValues.count(std::make_pair(L, R));
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric     if (isa<Argument>(L))
5760b57cec5SDimitry Andric       return Values[L] == R;
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric     if (isa<BasicBlock>(L))
5790b57cec5SDimitry Andric       return Blocks[cast<BasicBlock>(L)] != R;
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric     // Pretend everything else is identical.
5820b57cec5SDimitry Andric     return true;
5830b57cec5SDimitry Andric   }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   // Avoid a gcc warning about accessing 'this' in an initializer.
this_()5860b57cec5SDimitry Andric   FunctionDifferenceEngine *this_() { return this; }
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric public:
FunctionDifferenceEngine(DifferenceEngine & Engine,const Value * SavedLHS=nullptr,const Value * SavedRHS=nullptr)589*5f7ddb14SDimitry Andric   FunctionDifferenceEngine(DifferenceEngine &Engine,
590*5f7ddb14SDimitry Andric                            const Value *SavedLHS = nullptr,
591*5f7ddb14SDimitry Andric                            const Value *SavedRHS = nullptr)
592*5f7ddb14SDimitry Andric       : Engine(Engine), SavedLHS(SavedLHS), SavedRHS(SavedRHS),
593*5f7ddb14SDimitry Andric         Queue(QueueSorter(*this_())) {}
5940b57cec5SDimitry Andric 
diff(const Function * L,const Function * R)595*5f7ddb14SDimitry Andric   void diff(const Function *L, const Function *R) {
5960b57cec5SDimitry Andric     if (L->arg_size() != R->arg_size())
5970b57cec5SDimitry Andric       Engine.log("different argument counts");
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric     // Map the arguments.
600*5f7ddb14SDimitry Andric     for (Function::const_arg_iterator LI = L->arg_begin(), LE = L->arg_end(),
6010b57cec5SDimitry Andric                                       RI = R->arg_begin(), RE = R->arg_end();
6020b57cec5SDimitry Andric          LI != LE && RI != RE; ++LI, ++RI)
6030b57cec5SDimitry Andric       Values[&*LI] = &*RI;
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric     tryUnify(&*L->begin(), &*R->begin());
6060b57cec5SDimitry Andric     processQueue();
6070b57cec5SDimitry Andric   }
6080b57cec5SDimitry Andric };
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric struct DiffEntry {
DiffEntry__anon3906a3ef0111::DiffEntry6110b57cec5SDimitry Andric   DiffEntry() : Cost(0) {}
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   unsigned Cost;
6140b57cec5SDimitry Andric   llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
6150b57cec5SDimitry Andric };
6160b57cec5SDimitry Andric 
matchForBlockDiff(const Instruction * L,const Instruction * R)617*5f7ddb14SDimitry Andric bool FunctionDifferenceEngine::matchForBlockDiff(const Instruction *L,
618*5f7ddb14SDimitry Andric                                                  const Instruction *R) {
6190b57cec5SDimitry Andric   return !diff(L, R, false, false);
6200b57cec5SDimitry Andric }
6210b57cec5SDimitry Andric 
runBlockDiff(BasicBlock::const_iterator LStart,BasicBlock::const_iterator RStart)622*5f7ddb14SDimitry Andric void FunctionDifferenceEngine::runBlockDiff(BasicBlock::const_iterator LStart,
623*5f7ddb14SDimitry Andric                                             BasicBlock::const_iterator RStart) {
624*5f7ddb14SDimitry Andric   BasicBlock::const_iterator LE = LStart->getParent()->end();
625*5f7ddb14SDimitry Andric   BasicBlock::const_iterator RE = RStart->getParent()->end();
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   unsigned NL = std::distance(LStart, LE);
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   SmallVector<DiffEntry, 20> Paths1(NL+1);
6300b57cec5SDimitry Andric   SmallVector<DiffEntry, 20> Paths2(NL+1);
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   DiffEntry *Cur = Paths1.data();
6330b57cec5SDimitry Andric   DiffEntry *Next = Paths2.data();
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric   const unsigned LeftCost = 2;
6360b57cec5SDimitry Andric   const unsigned RightCost = 2;
6370b57cec5SDimitry Andric   const unsigned MatchCost = 0;
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric   assert(TentativeValues.empty());
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   // Initialize the first column.
6420b57cec5SDimitry Andric   for (unsigned I = 0; I != NL+1; ++I) {
6430b57cec5SDimitry Andric     Cur[I].Cost = I * LeftCost;
6440b57cec5SDimitry Andric     for (unsigned J = 0; J != I; ++J)
6450b57cec5SDimitry Andric       Cur[I].Path.push_back(DC_left);
6460b57cec5SDimitry Andric   }
6470b57cec5SDimitry Andric 
648*5f7ddb14SDimitry Andric   for (BasicBlock::const_iterator RI = RStart; RI != RE; ++RI) {
6490b57cec5SDimitry Andric     // Initialize the first row.
6500b57cec5SDimitry Andric     Next[0] = Cur[0];
6510b57cec5SDimitry Andric     Next[0].Cost += RightCost;
6520b57cec5SDimitry Andric     Next[0].Path.push_back(DC_right);
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric     unsigned Index = 1;
655*5f7ddb14SDimitry Andric     for (BasicBlock::const_iterator LI = LStart; LI != LE; ++LI, ++Index) {
6560b57cec5SDimitry Andric       if (matchForBlockDiff(&*LI, &*RI)) {
6570b57cec5SDimitry Andric         Next[Index] = Cur[Index-1];
6580b57cec5SDimitry Andric         Next[Index].Cost += MatchCost;
6590b57cec5SDimitry Andric         Next[Index].Path.push_back(DC_match);
6600b57cec5SDimitry Andric         TentativeValues.insert(std::make_pair(&*LI, &*RI));
6610b57cec5SDimitry Andric       } else if (Next[Index-1].Cost <= Cur[Index].Cost) {
6620b57cec5SDimitry Andric         Next[Index] = Next[Index-1];
6630b57cec5SDimitry Andric         Next[Index].Cost += LeftCost;
6640b57cec5SDimitry Andric         Next[Index].Path.push_back(DC_left);
6650b57cec5SDimitry Andric       } else {
6660b57cec5SDimitry Andric         Next[Index] = Cur[Index];
6670b57cec5SDimitry Andric         Next[Index].Cost += RightCost;
6680b57cec5SDimitry Andric         Next[Index].Path.push_back(DC_right);
6690b57cec5SDimitry Andric       }
6700b57cec5SDimitry Andric     }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric     std::swap(Cur, Next);
6730b57cec5SDimitry Andric   }
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric   // We don't need the tentative values anymore; everything from here
6760b57cec5SDimitry Andric   // on out should be non-tentative.
6770b57cec5SDimitry Andric   TentativeValues.clear();
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   SmallVectorImpl<char> &Path = Cur[NL].Path;
680*5f7ddb14SDimitry Andric   BasicBlock::const_iterator LI = LStart, RI = RStart;
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric   DiffLogBuilder Diff(Engine.getConsumer());
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric   // Drop trailing matches.
6855ffd83dbSDimitry Andric   while (Path.size() && Path.back() == DC_match)
6860b57cec5SDimitry Andric     Path.pop_back();
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric   // Skip leading matches.
6890b57cec5SDimitry Andric   SmallVectorImpl<char>::iterator
6900b57cec5SDimitry Andric     PI = Path.begin(), PE = Path.end();
6910b57cec5SDimitry Andric   while (PI != PE && *PI == DC_match) {
6920b57cec5SDimitry Andric     unify(&*LI, &*RI);
6930b57cec5SDimitry Andric     ++PI;
6940b57cec5SDimitry Andric     ++LI;
6950b57cec5SDimitry Andric     ++RI;
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   for (; PI != PE; ++PI) {
6990b57cec5SDimitry Andric     switch (static_cast<DiffChange>(*PI)) {
7000b57cec5SDimitry Andric     case DC_match:
7010b57cec5SDimitry Andric       assert(LI != LE && RI != RE);
7020b57cec5SDimitry Andric       {
703*5f7ddb14SDimitry Andric         const Instruction *L = &*LI, *R = &*RI;
7040b57cec5SDimitry Andric         unify(L, R);
7050b57cec5SDimitry Andric         Diff.addMatch(L, R);
7060b57cec5SDimitry Andric       }
7070b57cec5SDimitry Andric       ++LI; ++RI;
7080b57cec5SDimitry Andric       break;
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric     case DC_left:
7110b57cec5SDimitry Andric       assert(LI != LE);
7120b57cec5SDimitry Andric       Diff.addLeft(&*LI);
7130b57cec5SDimitry Andric       ++LI;
7140b57cec5SDimitry Andric       break;
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric     case DC_right:
7170b57cec5SDimitry Andric       assert(RI != RE);
7180b57cec5SDimitry Andric       Diff.addRight(&*RI);
7190b57cec5SDimitry Andric       ++RI;
7200b57cec5SDimitry Andric       break;
7210b57cec5SDimitry Andric     }
7220b57cec5SDimitry Andric   }
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric   // Finishing unifying and complaining about the tails of the block,
7250b57cec5SDimitry Andric   // which should be matches all the way through.
7260b57cec5SDimitry Andric   while (LI != LE) {
7270b57cec5SDimitry Andric     assert(RI != RE);
7280b57cec5SDimitry Andric     unify(&*LI, &*RI);
7290b57cec5SDimitry Andric     ++LI;
7300b57cec5SDimitry Andric     ++RI;
7310b57cec5SDimitry Andric   }
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric   // If the terminators have different kinds, but one is an invoke and the
7340b57cec5SDimitry Andric   // other is an unconditional branch immediately following a call, unify
7350b57cec5SDimitry Andric   // the results and the destinations.
736*5f7ddb14SDimitry Andric   const Instruction *LTerm = LStart->getParent()->getTerminator();
737*5f7ddb14SDimitry Andric   const Instruction *RTerm = RStart->getParent()->getTerminator();
7380b57cec5SDimitry Andric   if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
7390b57cec5SDimitry Andric     if (cast<BranchInst>(LTerm)->isConditional()) return;
740*5f7ddb14SDimitry Andric     BasicBlock::const_iterator I = LTerm->getIterator();
7410b57cec5SDimitry Andric     if (I == LStart->getParent()->begin()) return;
7420b57cec5SDimitry Andric     --I;
7430b57cec5SDimitry Andric     if (!isa<CallInst>(*I)) return;
744*5f7ddb14SDimitry Andric     const CallInst *LCall = cast<CallInst>(&*I);
745*5f7ddb14SDimitry Andric     const InvokeInst *RInvoke = cast<InvokeInst>(RTerm);
7465ffd83dbSDimitry Andric     if (!equivalentAsOperands(LCall->getCalledOperand(),
7475ffd83dbSDimitry Andric                               RInvoke->getCalledOperand()))
7480b57cec5SDimitry Andric       return;
7490b57cec5SDimitry Andric     if (!LCall->use_empty())
7500b57cec5SDimitry Andric       Values[LCall] = RInvoke;
7510b57cec5SDimitry Andric     tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
7520b57cec5SDimitry Andric   } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
7530b57cec5SDimitry Andric     if (cast<BranchInst>(RTerm)->isConditional()) return;
754*5f7ddb14SDimitry Andric     BasicBlock::const_iterator I = RTerm->getIterator();
7550b57cec5SDimitry Andric     if (I == RStart->getParent()->begin()) return;
7560b57cec5SDimitry Andric     --I;
7570b57cec5SDimitry Andric     if (!isa<CallInst>(*I)) return;
758*5f7ddb14SDimitry Andric     const CallInst *RCall = cast<CallInst>(I);
759*5f7ddb14SDimitry Andric     const InvokeInst *LInvoke = cast<InvokeInst>(LTerm);
7605ffd83dbSDimitry Andric     if (!equivalentAsOperands(LInvoke->getCalledOperand(),
7615ffd83dbSDimitry Andric                               RCall->getCalledOperand()))
7620b57cec5SDimitry Andric       return;
7630b57cec5SDimitry Andric     if (!LInvoke->use_empty())
7640b57cec5SDimitry Andric       Values[LInvoke] = RCall;
7650b57cec5SDimitry Andric     tryUnify(LInvoke->getNormalDest(), RTerm->getSuccessor(0));
7660b57cec5SDimitry Andric   }
7670b57cec5SDimitry Andric }
7680b57cec5SDimitry Andric }
7690b57cec5SDimitry Andric 
anchor()7700b57cec5SDimitry Andric void DifferenceEngine::Oracle::anchor() { }
7710b57cec5SDimitry Andric 
diff(const Function * L,const Function * R)772*5f7ddb14SDimitry Andric void DifferenceEngine::diff(const Function *L, const Function *R) {
7730b57cec5SDimitry Andric   Context C(*this, L, R);
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   // FIXME: types
7760b57cec5SDimitry Andric   // FIXME: attributes and CC
7770b57cec5SDimitry Andric   // FIXME: parameter attributes
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   // If both are declarations, we're done.
7800b57cec5SDimitry Andric   if (L->empty() && R->empty())
7810b57cec5SDimitry Andric     return;
7820b57cec5SDimitry Andric   else if (L->empty())
7830b57cec5SDimitry Andric     log("left function is declaration, right function is definition");
7840b57cec5SDimitry Andric   else if (R->empty())
7850b57cec5SDimitry Andric     log("right function is declaration, left function is definition");
7860b57cec5SDimitry Andric   else
7870b57cec5SDimitry Andric     FunctionDifferenceEngine(*this).diff(L, R);
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric 
diff(const Module * L,const Module * R)790*5f7ddb14SDimitry Andric void DifferenceEngine::diff(const Module *L, const Module *R) {
7910b57cec5SDimitry Andric   StringSet<> LNames;
792*5f7ddb14SDimitry Andric   SmallVector<std::pair<const Function *, const Function *>, 20> Queue;
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric   unsigned LeftAnonCount = 0;
7950b57cec5SDimitry Andric   unsigned RightAnonCount = 0;
7960b57cec5SDimitry Andric 
797*5f7ddb14SDimitry Andric   for (Module::const_iterator I = L->begin(), E = L->end(); I != E; ++I) {
798*5f7ddb14SDimitry Andric     const Function *LFn = &*I;
7990b57cec5SDimitry Andric     StringRef Name = LFn->getName();
8000b57cec5SDimitry Andric     if (Name.empty()) {
8010b57cec5SDimitry Andric       ++LeftAnonCount;
8020b57cec5SDimitry Andric       continue;
8030b57cec5SDimitry Andric     }
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric     LNames.insert(Name);
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric     if (Function *RFn = R->getFunction(LFn->getName()))
8080b57cec5SDimitry Andric       Queue.push_back(std::make_pair(LFn, RFn));
8090b57cec5SDimitry Andric     else
8100b57cec5SDimitry Andric       logf("function %l exists only in left module") << LFn;
8110b57cec5SDimitry Andric   }
8120b57cec5SDimitry Andric 
813*5f7ddb14SDimitry Andric   for (Module::const_iterator I = R->begin(), E = R->end(); I != E; ++I) {
814*5f7ddb14SDimitry Andric     const Function *RFn = &*I;
8150b57cec5SDimitry Andric     StringRef Name = RFn->getName();
8160b57cec5SDimitry Andric     if (Name.empty()) {
8170b57cec5SDimitry Andric       ++RightAnonCount;
8180b57cec5SDimitry Andric       continue;
8190b57cec5SDimitry Andric     }
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric     if (!LNames.count(Name))
8220b57cec5SDimitry Andric       logf("function %r exists only in right module") << RFn;
8230b57cec5SDimitry Andric   }
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   if (LeftAnonCount != 0 || RightAnonCount != 0) {
8260b57cec5SDimitry Andric     SmallString<32> Tmp;
8270b57cec5SDimitry Andric     logf(("not comparing " + Twine(LeftAnonCount) +
8280b57cec5SDimitry Andric           " anonymous functions in the left module and " +
8290b57cec5SDimitry Andric           Twine(RightAnonCount) + " in the right module")
8300b57cec5SDimitry Andric              .toStringRef(Tmp));
8310b57cec5SDimitry Andric   }
8320b57cec5SDimitry Andric 
833*5f7ddb14SDimitry Andric   for (SmallVectorImpl<std::pair<const Function *, const Function *>>::iterator
834*5f7ddb14SDimitry Andric            I = Queue.begin(),
835*5f7ddb14SDimitry Andric            E = Queue.end();
836*5f7ddb14SDimitry Andric        I != E; ++I)
8370b57cec5SDimitry Andric     diff(I->first, I->second);
8380b57cec5SDimitry Andric }
8390b57cec5SDimitry Andric 
equivalentAsOperands(const GlobalValue * L,const GlobalValue * R)840*5f7ddb14SDimitry Andric bool DifferenceEngine::equivalentAsOperands(const GlobalValue *L,
841*5f7ddb14SDimitry Andric                                             const GlobalValue *R) {
8420b57cec5SDimitry Andric   if (globalValueOracle) return (*globalValueOracle)(L, R);
843480093f4SDimitry Andric 
844480093f4SDimitry Andric   if (isa<GlobalVariable>(L) && isa<GlobalVariable>(R)) {
845*5f7ddb14SDimitry Andric     const GlobalVariable *GVL = cast<GlobalVariable>(L);
846*5f7ddb14SDimitry Andric     const GlobalVariable *GVR = cast<GlobalVariable>(R);
847480093f4SDimitry Andric     if (GVL->hasLocalLinkage() && GVL->hasUniqueInitializer() &&
848480093f4SDimitry Andric         GVR->hasLocalLinkage() && GVR->hasUniqueInitializer())
849*5f7ddb14SDimitry Andric       return FunctionDifferenceEngine(*this, GVL, GVR)
850*5f7ddb14SDimitry Andric           .equivalentAsOperands(GVL->getInitializer(), GVR->getInitializer());
851480093f4SDimitry Andric   }
852480093f4SDimitry Andric 
8530b57cec5SDimitry Andric   return L->getName() == R->getName();
8540b57cec5SDimitry Andric }
855