Home | History | Annotate | Download | only in llvm-diff
      1 //===-- DifferenceEngine.cpp - Structural function/module comparison ------===//
      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 header defines the implementation of the LLVM difference
     11 // engine, which structurally compares global values within a module.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "DifferenceEngine.h"
     16 #include "llvm/ADT/DenseMap.h"
     17 #include "llvm/ADT/DenseSet.h"
     18 #include "llvm/ADT/SmallVector.h"
     19 #include "llvm/ADT/StringSet.h"
     20 #include "llvm/IR/CFG.h"
     21 #include "llvm/IR/CallSite.h"
     22 #include "llvm/IR/Constants.h"
     23 #include "llvm/IR/Function.h"
     24 #include "llvm/IR/Instructions.h"
     25 #include "llvm/IR/Module.h"
     26 #include "llvm/Support/ErrorHandling.h"
     27 #include "llvm/Support/raw_ostream.h"
     28 #include "llvm/Support/type_traits.h"
     29 #include <utility>
     30 
     31 using namespace llvm;
     32 
     33 namespace {
     34 
     35 /// A priority queue, implemented as a heap.
     36 template <class T, class Sorter, unsigned InlineCapacity>
     37 class PriorityQueue {
     38   Sorter Precedes;
     39   llvm::SmallVector<T, InlineCapacity> Storage;
     40 
     41 public:
     42   PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
     43 
     44   /// Checks whether the heap is empty.
     45   bool empty() const { return Storage.empty(); }
     46 
     47   /// Insert a new value on the heap.
     48   void insert(const T &V) {
     49     unsigned Index = Storage.size();
     50     Storage.push_back(V);
     51     if (Index == 0) return;
     52 
     53     T *data = Storage.data();
     54     while (true) {
     55       unsigned Target = (Index + 1) / 2 - 1;
     56       if (!Precedes(data[Index], data[Target])) return;
     57       std::swap(data[Index], data[Target]);
     58       if (Target == 0) return;
     59       Index = Target;
     60     }
     61   }
     62 
     63   /// Remove the minimum value in the heap.  Only valid on a non-empty heap.
     64   T remove_min() {
     65     assert(!empty());
     66     T tmp = Storage[0];
     67 
     68     unsigned NewSize = Storage.size() - 1;
     69     if (NewSize) {
     70       // Move the slot at the end to the beginning.
     71       if (isPodLike<T>::value)
     72         Storage[0] = Storage[NewSize];
     73       else
     74         std::swap(Storage[0], Storage[NewSize]);
     75 
     76       // Bubble the root up as necessary.
     77       unsigned Index = 0;
     78       while (true) {
     79         // With a 1-based index, the children would be Index*2 and Index*2+1.
     80         unsigned R = (Index + 1) * 2;
     81         unsigned L = R - 1;
     82 
     83         // If R is out of bounds, we're done after this in any case.
     84         if (R >= NewSize) {
     85           // If L is also out of bounds, we're done immediately.
     86           if (L >= NewSize) break;
     87 
     88           // Otherwise, test whether we should swap L and Index.
     89           if (Precedes(Storage[L], Storage[Index]))
     90             std::swap(Storage[L], Storage[Index]);
     91           break;
     92         }
     93 
     94         // Otherwise, we need to compare with the smaller of L and R.
     95         // Prefer R because it's closer to the end of the array.
     96         unsigned IndexToTest = (Precedes(Storage[L], Storage[R]) ? L : R);
     97 
     98         // If Index is >= the min of L and R, then heap ordering is restored.
     99         if (!Precedes(Storage[IndexToTest], Storage[Index]))
    100           break;
    101 
    102         // Otherwise, keep bubbling up.
    103         std::swap(Storage[IndexToTest], Storage[Index]);
    104         Index = IndexToTest;
    105       }
    106     }
    107     Storage.pop_back();
    108 
    109     return tmp;
    110   }
    111 };
    112 
    113 /// A function-scope difference engine.
    114 class FunctionDifferenceEngine {
    115   DifferenceEngine &Engine;
    116 
    117   /// The current mapping from old local values to new local values.
    118   DenseMap<Value*, Value*> Values;
    119 
    120   /// The current mapping from old blocks to new blocks.
    121   DenseMap<BasicBlock*, BasicBlock*> Blocks;
    122 
    123   DenseSet<std::pair<Value*, Value*> > TentativeValues;
    124 
    125   unsigned getUnprocPredCount(BasicBlock *Block) const {
    126     unsigned Count = 0;
    127     for (pred_iterator I = pred_begin(Block), E = pred_end(Block); I != E; ++I)
    128       if (!Blocks.count(*I)) Count++;
    129     return Count;
    130   }
    131 
    132   typedef std::pair<BasicBlock*, BasicBlock*> BlockPair;
    133 
    134   /// A type which sorts a priority queue by the number of unprocessed
    135   /// predecessor blocks it has remaining.
    136   ///
    137   /// This is actually really expensive to calculate.
    138   struct QueueSorter {
    139     const FunctionDifferenceEngine &fde;
    140     explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
    141 
    142     bool operator()(const BlockPair &Old, const BlockPair &New) {
    143       return fde.getUnprocPredCount(Old.first)
    144            < fde.getUnprocPredCount(New.first);
    145     }
    146   };
    147 
    148   /// A queue of unified blocks to process.
    149   PriorityQueue<BlockPair, QueueSorter, 20> Queue;
    150 
    151   /// Try to unify the given two blocks.  Enqueues them for processing
    152   /// if they haven't already been processed.
    153   ///
    154   /// Returns true if there was a problem unifying them.
    155   bool tryUnify(BasicBlock *L, BasicBlock *R) {
    156     BasicBlock *&Ref = Blocks[L];
    157 
    158     if (Ref) {
    159       if (Ref == R) return false;
    160 
    161       Engine.logf("successor %l cannot be equivalent to %r; "
    162                   "it's already equivalent to %r")
    163         << L << R << Ref;
    164       return true;
    165     }
    166 
    167     Ref = R;
    168     Queue.insert(BlockPair(L, R));
    169     return false;
    170   }
    171 
    172   /// Unifies two instructions, given that they're known not to have
    173   /// structural differences.
    174   void unify(Instruction *L, Instruction *R) {
    175     DifferenceEngine::Context C(Engine, L, R);
    176 
    177     bool Result = diff(L, R, true, true);
    178     assert(!Result && "structural differences second time around?");
    179     (void) Result;
    180     if (!L->use_empty())
    181       Values[L] = R;
    182   }
    183 
    184   void processQueue() {
    185     while (!Queue.empty()) {
    186       BlockPair Pair = Queue.remove_min();
    187       diff(Pair.first, Pair.second);
    188     }
    189   }
    190 
    191   void diff(BasicBlock *L, BasicBlock *R) {
    192     DifferenceEngine::Context C(Engine, L, R);
    193 
    194     BasicBlock::iterator LI = L->begin(), LE = L->end();
    195     BasicBlock::iterator RI = R->begin();
    196 
    197     do {
    198       assert(LI != LE && RI != R->end());
    199       Instruction *LeftI = &*LI, *RightI = &*RI;
    200 
    201       // If the instructions differ, start the more sophisticated diff
    202       // algorithm at the start of the block.
    203       if (diff(LeftI, RightI, false, false)) {
    204         TentativeValues.clear();
    205         return runBlockDiff(L->begin(), R->begin());
    206       }
    207 
    208       // Otherwise, tentatively unify them.
    209       if (!LeftI->use_empty())
    210         TentativeValues.insert(std::make_pair(LeftI, RightI));
    211 
    212       ++LI;
    213       ++RI;
    214     } while (LI != LE); // This is sufficient: we can't get equality of
    215                         // terminators if there are residual instructions.
    216 
    217     // Unify everything in the block, non-tentatively this time.
    218     TentativeValues.clear();
    219     for (LI = L->begin(), RI = R->begin(); LI != LE; ++LI, ++RI)
    220       unify(&*LI, &*RI);
    221   }
    222 
    223   bool matchForBlockDiff(Instruction *L, Instruction *R);
    224   void runBlockDiff(BasicBlock::iterator LI, BasicBlock::iterator RI);
    225 
    226   bool diffCallSites(CallSite L, CallSite R, bool Complain) {
    227     // FIXME: call attributes
    228     if (!equivalentAsOperands(L.getCalledValue(), R.getCalledValue())) {
    229       if (Complain) Engine.log("called functions differ");
    230       return true;
    231     }
    232     if (L.arg_size() != R.arg_size()) {
    233       if (Complain) Engine.log("argument counts differ");
    234       return true;
    235     }
    236     for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
    237       if (!equivalentAsOperands(L.getArgument(I), R.getArgument(I))) {
    238         if (Complain)
    239           Engine.logf("arguments %l and %r differ")
    240             << L.getArgument(I) << R.getArgument(I);
    241         return true;
    242       }
    243     return false;
    244   }
    245 
    246   bool diff(Instruction *L, Instruction *R, bool Complain, bool TryUnify) {
    247     // FIXME: metadata (if Complain is set)
    248 
    249     // Different opcodes always imply different operations.
    250     if (L->getOpcode() != R->getOpcode()) {
    251       if (Complain) Engine.log("different instruction types");
    252       return true;
    253     }
    254 
    255     if (isa<CmpInst>(L)) {
    256       if (cast<CmpInst>(L)->getPredicate()
    257             != cast<CmpInst>(R)->getPredicate()) {
    258         if (Complain) Engine.log("different predicates");
    259         return true;
    260       }
    261     } else if (isa<CallInst>(L)) {
    262       return diffCallSites(CallSite(L), CallSite(R), Complain);
    263     } else if (isa<PHINode>(L)) {
    264       // FIXME: implement.
    265 
    266       // This is really weird;  type uniquing is broken?
    267       if (L->getType() != R->getType()) {
    268         if (!L->getType()->isPointerTy() || !R->getType()->isPointerTy()) {
    269           if (Complain) Engine.log("different phi types");
    270           return true;
    271         }
    272       }
    273       return false;
    274 
    275     // Terminators.
    276     } else if (isa<InvokeInst>(L)) {
    277       InvokeInst *LI = cast<InvokeInst>(L);
    278       InvokeInst *RI = cast<InvokeInst>(R);
    279       if (diffCallSites(CallSite(LI), CallSite(RI), Complain))
    280         return true;
    281 
    282       if (TryUnify) {
    283         tryUnify(LI->getNormalDest(), RI->getNormalDest());
    284         tryUnify(LI->getUnwindDest(), RI->getUnwindDest());
    285       }
    286       return false;
    287 
    288     } else if (isa<BranchInst>(L)) {
    289       BranchInst *LI = cast<BranchInst>(L);
    290       BranchInst *RI = cast<BranchInst>(R);
    291       if (LI->isConditional() != RI->isConditional()) {
    292         if (Complain) Engine.log("branch conditionality differs");
    293         return true;
    294       }
    295 
    296       if (LI->isConditional()) {
    297         if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
    298           if (Complain) Engine.log("branch conditions differ");
    299           return true;
    300         }
    301         if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
    302       }
    303       if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
    304       return false;
    305 
    306     } else if (isa<SwitchInst>(L)) {
    307       SwitchInst *LI = cast<SwitchInst>(L);
    308       SwitchInst *RI = cast<SwitchInst>(R);
    309       if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
    310         if (Complain) Engine.log("switch conditions differ");
    311         return true;
    312       }
    313       if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
    314 
    315       bool Difference = false;
    316 
    317       DenseMap<ConstantInt*,BasicBlock*> LCases;
    318 
    319       for (SwitchInst::CaseIt I = LI->case_begin(), E = LI->case_end();
    320            I != E; ++I)
    321         LCases[I.getCaseValue()] = I.getCaseSuccessor();
    322 
    323       for (SwitchInst::CaseIt I = RI->case_begin(), E = RI->case_end();
    324            I != E; ++I) {
    325         ConstantInt *CaseValue = I.getCaseValue();
    326         BasicBlock *LCase = LCases[CaseValue];
    327         if (LCase) {
    328           if (TryUnify) tryUnify(LCase, I.getCaseSuccessor());
    329           LCases.erase(CaseValue);
    330         } else if (Complain || !Difference) {
    331           if (Complain)
    332             Engine.logf("right switch has extra case %r") << CaseValue;
    333           Difference = true;
    334         }
    335       }
    336       if (!Difference)
    337         for (DenseMap<ConstantInt*,BasicBlock*>::iterator
    338                I = LCases.begin(), E = LCases.end(); I != E; ++I) {
    339           if (Complain)
    340             Engine.logf("left switch has extra case %l") << I->first;
    341           Difference = true;
    342         }
    343       return Difference;
    344     } else if (isa<UnreachableInst>(L)) {
    345       return false;
    346     }
    347 
    348     if (L->getNumOperands() != R->getNumOperands()) {
    349       if (Complain) Engine.log("instructions have different operand counts");
    350       return true;
    351     }
    352 
    353     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
    354       Value *LO = L->getOperand(I), *RO = R->getOperand(I);
    355       if (!equivalentAsOperands(LO, RO)) {
    356         if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
    357         return true;
    358       }
    359     }
    360 
    361     return false;
    362   }
    363 
    364   bool equivalentAsOperands(Constant *L, Constant *R) {
    365     // Use equality as a preliminary filter.
    366     if (L == R)
    367       return true;
    368 
    369     if (L->getValueID() != R->getValueID())
    370       return false;
    371 
    372     // Ask the engine about global values.
    373     if (isa<GlobalValue>(L))
    374       return Engine.equivalentAsOperands(cast<GlobalValue>(L),
    375                                          cast<GlobalValue>(R));
    376 
    377     // Compare constant expressions structurally.
    378     if (isa<ConstantExpr>(L))
    379       return equivalentAsOperands(cast<ConstantExpr>(L),
    380                                   cast<ConstantExpr>(R));
    381 
    382     // Nulls of the "same type" don't always actually have the same
    383     // type; I don't know why.  Just white-list them.
    384     if (isa<ConstantPointerNull>(L))
    385       return true;
    386 
    387     // Block addresses only match if we've already encountered the
    388     // block.  FIXME: tentative matches?
    389     if (isa<BlockAddress>(L))
    390       return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
    391                  == cast<BlockAddress>(R)->getBasicBlock();
    392 
    393     return false;
    394   }
    395 
    396   bool equivalentAsOperands(ConstantExpr *L, ConstantExpr *R) {
    397     if (L == R)
    398       return true;
    399     if (L->getOpcode() != R->getOpcode())
    400       return false;
    401 
    402     switch (L->getOpcode()) {
    403     case Instruction::ICmp:
    404     case Instruction::FCmp:
    405       if (L->getPredicate() != R->getPredicate())
    406         return false;
    407       break;
    408 
    409     case Instruction::GetElementPtr:
    410       // FIXME: inbounds?
    411       break;
    412 
    413     default:
    414       break;
    415     }
    416 
    417     if (L->getNumOperands() != R->getNumOperands())
    418       return false;
    419 
    420     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I)
    421       if (!equivalentAsOperands(L->getOperand(I), R->getOperand(I)))
    422         return false;
    423 
    424     return true;
    425   }
    426 
    427   bool equivalentAsOperands(Value *L, Value *R) {
    428     // Fall out if the values have different kind.
    429     // This possibly shouldn't take priority over oracles.
    430     if (L->getValueID() != R->getValueID())
    431       return false;
    432 
    433     // Value subtypes:  Argument, Constant, Instruction, BasicBlock,
    434     //                  InlineAsm, MDNode, MDString, PseudoSourceValue
    435 
    436     if (isa<Constant>(L))
    437       return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R));
    438 
    439     if (isa<Instruction>(L))
    440       return Values[L] == R || TentativeValues.count(std::make_pair(L, R));
    441 
    442     if (isa<Argument>(L))
    443       return Values[L] == R;
    444 
    445     if (isa<BasicBlock>(L))
    446       return Blocks[cast<BasicBlock>(L)] != R;
    447 
    448     // Pretend everything else is identical.
    449     return true;
    450   }
    451 
    452   // Avoid a gcc warning about accessing 'this' in an initializer.
    453   FunctionDifferenceEngine *this_() { return this; }
    454 
    455 public:
    456   FunctionDifferenceEngine(DifferenceEngine &Engine) :
    457     Engine(Engine), Queue(QueueSorter(*this_())) {}
    458 
    459   void diff(Function *L, Function *R) {
    460     if (L->arg_size() != R->arg_size())
    461       Engine.log("different argument counts");
    462 
    463     // Map the arguments.
    464     for (Function::arg_iterator
    465            LI = L->arg_begin(), LE = L->arg_end(),
    466            RI = R->arg_begin(), RE = R->arg_end();
    467          LI != LE && RI != RE; ++LI, ++RI)
    468       Values[&*LI] = &*RI;
    469 
    470     tryUnify(&*L->begin(), &*R->begin());
    471     processQueue();
    472   }
    473 };
    474 
    475 struct DiffEntry {
    476   DiffEntry() : Cost(0) {}
    477 
    478   unsigned Cost;
    479   llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
    480 };
    481 
    482 bool FunctionDifferenceEngine::matchForBlockDiff(Instruction *L,
    483                                                  Instruction *R) {
    484   return !diff(L, R, false, false);
    485 }
    486 
    487 void FunctionDifferenceEngine::runBlockDiff(BasicBlock::iterator LStart,
    488                                             BasicBlock::iterator RStart) {
    489   BasicBlock::iterator LE = LStart->getParent()->end();
    490   BasicBlock::iterator RE = RStart->getParent()->end();
    491 
    492   unsigned NL = std::distance(LStart, LE);
    493 
    494   SmallVector<DiffEntry, 20> Paths1(NL+1);
    495   SmallVector<DiffEntry, 20> Paths2(NL+1);
    496 
    497   DiffEntry *Cur = Paths1.data();
    498   DiffEntry *Next = Paths2.data();
    499 
    500   const unsigned LeftCost = 2;
    501   const unsigned RightCost = 2;
    502   const unsigned MatchCost = 0;
    503 
    504   assert(TentativeValues.empty());
    505 
    506   // Initialize the first column.
    507   for (unsigned I = 0; I != NL+1; ++I) {
    508     Cur[I].Cost = I * LeftCost;
    509     for (unsigned J = 0; J != I; ++J)
    510       Cur[I].Path.push_back(DC_left);
    511   }
    512 
    513   for (BasicBlock::iterator RI = RStart; RI != RE; ++RI) {
    514     // Initialize the first row.
    515     Next[0] = Cur[0];
    516     Next[0].Cost += RightCost;
    517     Next[0].Path.push_back(DC_right);
    518 
    519     unsigned Index = 1;
    520     for (BasicBlock::iterator LI = LStart; LI != LE; ++LI, ++Index) {
    521       if (matchForBlockDiff(&*LI, &*RI)) {
    522         Next[Index] = Cur[Index-1];
    523         Next[Index].Cost += MatchCost;
    524         Next[Index].Path.push_back(DC_match);
    525         TentativeValues.insert(std::make_pair(&*LI, &*RI));
    526       } else if (Next[Index-1].Cost <= Cur[Index].Cost) {
    527         Next[Index] = Next[Index-1];
    528         Next[Index].Cost += LeftCost;
    529         Next[Index].Path.push_back(DC_left);
    530       } else {
    531         Next[Index] = Cur[Index];
    532         Next[Index].Cost += RightCost;
    533         Next[Index].Path.push_back(DC_right);
    534       }
    535     }
    536 
    537     std::swap(Cur, Next);
    538   }
    539 
    540   // We don't need the tentative values anymore; everything from here
    541   // on out should be non-tentative.
    542   TentativeValues.clear();
    543 
    544   SmallVectorImpl<char> &Path = Cur[NL].Path;
    545   BasicBlock::iterator LI = LStart, RI = RStart;
    546 
    547   DiffLogBuilder Diff(Engine.getConsumer());
    548 
    549   // Drop trailing matches.
    550   while (Path.back() == DC_match)
    551     Path.pop_back();
    552 
    553   // Skip leading matches.
    554   SmallVectorImpl<char>::iterator
    555     PI = Path.begin(), PE = Path.end();
    556   while (PI != PE && *PI == DC_match) {
    557     unify(&*LI, &*RI);
    558     ++PI;
    559     ++LI;
    560     ++RI;
    561   }
    562 
    563   for (; PI != PE; ++PI) {
    564     switch (static_cast<DiffChange>(*PI)) {
    565     case DC_match:
    566       assert(LI != LE && RI != RE);
    567       {
    568         Instruction *L = &*LI, *R = &*RI;
    569         unify(L, R);
    570         Diff.addMatch(L, R);
    571       }
    572       ++LI; ++RI;
    573       break;
    574 
    575     case DC_left:
    576       assert(LI != LE);
    577       Diff.addLeft(&*LI);
    578       ++LI;
    579       break;
    580 
    581     case DC_right:
    582       assert(RI != RE);
    583       Diff.addRight(&*RI);
    584       ++RI;
    585       break;
    586     }
    587   }
    588 
    589   // Finishing unifying and complaining about the tails of the block,
    590   // which should be matches all the way through.
    591   while (LI != LE) {
    592     assert(RI != RE);
    593     unify(&*LI, &*RI);
    594     ++LI;
    595     ++RI;
    596   }
    597 
    598   // If the terminators have different kinds, but one is an invoke and the
    599   // other is an unconditional branch immediately following a call, unify
    600   // the results and the destinations.
    601   TerminatorInst *LTerm = LStart->getParent()->getTerminator();
    602   TerminatorInst *RTerm = RStart->getParent()->getTerminator();
    603   if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
    604     if (cast<BranchInst>(LTerm)->isConditional()) return;
    605     BasicBlock::iterator I = LTerm->getIterator();
    606     if (I == LStart->getParent()->begin()) return;
    607     --I;
    608     if (!isa<CallInst>(*I)) return;
    609     CallInst *LCall = cast<CallInst>(&*I);
    610     InvokeInst *RInvoke = cast<InvokeInst>(RTerm);
    611     if (!equivalentAsOperands(LCall->getCalledValue(), RInvoke->getCalledValue()))
    612       return;
    613     if (!LCall->use_empty())
    614       Values[LCall] = RInvoke;
    615     tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
    616   } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
    617     if (cast<BranchInst>(RTerm)->isConditional()) return;
    618     BasicBlock::iterator I = RTerm->getIterator();
    619     if (I == RStart->getParent()->begin()) return;
    620     --I;
    621     if (!isa<CallInst>(*I)) return;
    622     CallInst *RCall = cast<CallInst>(I);
    623     InvokeInst *LInvoke = cast<InvokeInst>(LTerm);
    624     if (!equivalentAsOperands(LInvoke->getCalledValue(), RCall->getCalledValue()))
    625       return;
    626     if (!LInvoke->use_empty())
    627       Values[LInvoke] = RCall;
    628     tryUnify(LInvoke->getNormalDest(), RTerm->getSuccessor(0));
    629   }
    630 }
    631 
    632 }
    633 
    634 void DifferenceEngine::Oracle::anchor() { }
    635 
    636 void DifferenceEngine::diff(Function *L, Function *R) {
    637   Context C(*this, L, R);
    638 
    639   // FIXME: types
    640   // FIXME: attributes and CC
    641   // FIXME: parameter attributes
    642 
    643   // If both are declarations, we're done.
    644   if (L->empty() && R->empty())
    645     return;
    646   else if (L->empty())
    647     log("left function is declaration, right function is definition");
    648   else if (R->empty())
    649     log("right function is declaration, left function is definition");
    650   else
    651     FunctionDifferenceEngine(*this).diff(L, R);
    652 }
    653 
    654 void DifferenceEngine::diff(Module *L, Module *R) {
    655   StringSet<> LNames;
    656   SmallVector<std::pair<Function*,Function*>, 20> Queue;
    657 
    658   for (Module::iterator I = L->begin(), E = L->end(); I != E; ++I) {
    659     Function *LFn = &*I;
    660     LNames.insert(LFn->getName());
    661 
    662     if (Function *RFn = R->getFunction(LFn->getName()))
    663       Queue.push_back(std::make_pair(LFn, RFn));
    664     else
    665       logf("function %l exists only in left module") << LFn;
    666   }
    667 
    668   for (Module::iterator I = R->begin(), E = R->end(); I != E; ++I) {
    669     Function *RFn = &*I;
    670     if (!LNames.count(RFn->getName()))
    671       logf("function %r exists only in right module") << RFn;
    672   }
    673 
    674   for (SmallVectorImpl<std::pair<Function*,Function*> >::iterator
    675          I = Queue.begin(), E = Queue.end(); I != E; ++I)
    676     diff(I->first, I->second);
    677 }
    678 
    679 bool DifferenceEngine::equivalentAsOperands(GlobalValue *L, GlobalValue *R) {
    680   if (globalValueOracle) return (*globalValueOracle)(L, R);
    681   return L->getName() == R->getName();
    682 }
    683