1 //===-- DifferenceEngine.cpp - Structural function/module comparison ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the interface to the LLVM difference engine,
11 // which structurally compares functions within a module.
13 //===----------------------------------------------------------------------===//
17 #include <llvm/ADT/DenseMap.h>
18 #include <llvm/ADT/DenseSet.h>
19 #include <llvm/ADT/SmallVector.h>
20 #include <llvm/ADT/StringRef.h>
21 #include <llvm/ADT/StringSet.h>
23 #include <llvm/Module.h>
24 #include <llvm/Function.h>
25 #include <llvm/Instructions.h>
26 #include <llvm/Support/CFG.h>
28 #include <llvm/Support/raw_ostream.h>
29 #include <llvm/Support/type_traits.h>
30 #include <llvm/Support/ErrorHandling.h>
31 #include <llvm/Support/CallSite.h>
33 #include "DifferenceEngine.h"
39 /// A priority queue, implemented as a heap.
40 template <class T, class Sorter, unsigned InlineCapacity>
43 llvm::SmallVector<T, InlineCapacity> Storage;
46 PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
48 /// Checks whether the heap is empty.
49 bool empty() const { return Storage.empty(); }
51 /// Insert a new value on the heap.
52 void insert(const T &V) {
53 unsigned Index = Storage.size();
55 if (Index == 0) return;
57 T *data = Storage.data();
59 unsigned Target = (Index + 1) / 2 - 1;
60 if (!Precedes(data[Index], data[Target])) return;
61 std::swap(data[Index], data[Target]);
62 if (Target == 0) return;
67 /// Remove the minimum value in the heap. Only valid on a non-empty heap.
72 unsigned NewSize = Storage.size() - 1;
74 // Move the slot at the end to the beginning.
75 if (isPodLike<T>::value)
76 Storage[0] = Storage[NewSize];
78 std::swap(Storage[0], Storage[NewSize]);
80 // Bubble the root up as necessary.
83 // With a 1-based index, the children would be Index*2 and Index*2+1.
84 unsigned R = (Index + 1) * 2;
87 // If R is out of bounds, we're done after this in any case.
89 // If L is also out of bounds, we're done immediately.
90 if (L >= NewSize) break;
92 // Otherwise, test whether we should swap L and Index.
93 if (Precedes(Storage[L], Storage[Index]))
94 std::swap(Storage[L], Storage[Index]);
98 // Otherwise, we need to compare with the smaller of L and R.
99 // Prefer R because it's closer to the end of the array.
100 unsigned IndexToTest = (Precedes(Storage[L], Storage[R]) ? L : R);
102 // If Index is >= the min of L and R, then heap ordering is restored.
103 if (!Precedes(Storage[IndexToTest], Storage[Index]))
106 // Otherwise, keep bubbling up.
107 std::swap(Storage[IndexToTest], Storage[Index]);
117 /// A function-scope difference engine.
118 class FunctionDifferenceEngine {
119 DifferenceEngine &Engine;
121 /// The current mapping from old local values to new local values.
122 DenseMap<Value*, Value*> Values;
124 /// The current mapping from old blocks to new blocks.
125 DenseMap<BasicBlock*, BasicBlock*> Blocks;
127 DenseSet<std::pair<Value*, Value*> > TentativeValues;
129 unsigned getUnprocPredCount(BasicBlock *Block) const {
131 for (pred_iterator I = pred_begin(Block), E = pred_end(Block); I != E; ++I)
132 if (!Blocks.count(*I)) Count++;
136 typedef std::pair<BasicBlock*, BasicBlock*> BlockPair;
138 /// A type which sorts a priority queue by the number of unprocessed
139 /// predecessor blocks it has remaining.
141 /// This is actually really expensive to calculate.
143 const FunctionDifferenceEngine &fde;
144 explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
146 bool operator()(const BlockPair &Old, const BlockPair &New) {
147 return fde.getUnprocPredCount(Old.first)
148 < fde.getUnprocPredCount(New.first);
152 /// A queue of unified blocks to process.
153 PriorityQueue<BlockPair, QueueSorter, 20> Queue;
155 /// Try to unify the given two blocks. Enqueues them for processing
156 /// if they haven't already been processed.
158 /// Returns true if there was a problem unifying them.
159 bool tryUnify(BasicBlock *L, BasicBlock *R) {
160 BasicBlock *&Ref = Blocks[L];
163 if (Ref == R) return false;
165 Engine.logf("successor %l cannot be equivalent to %r; "
166 "it's already equivalent to %r")
172 Queue.insert(BlockPair(L, R));
176 void processQueue() {
177 while (!Queue.empty()) {
178 BlockPair Pair = Queue.remove_min();
179 diff(Pair.first, Pair.second);
183 void diff(BasicBlock *L, BasicBlock *R) {
184 DifferenceEngine::Context C(Engine, L, R);
186 BasicBlock::iterator LI = L->begin(), LE = L->end();
187 BasicBlock::iterator RI = R->begin(), RE = R->end();
189 llvm::SmallVector<std::pair<Instruction*,Instruction*>, 20> TentativePairs;
192 assert(LI != LE && RI != RE);
193 Instruction *LeftI = &*LI, *RightI = &*RI;
195 // If the instructions differ, start the more sophisticated diff
196 // algorithm at the start of the block.
197 if (diff(LeftI, RightI, false, true)) {
198 TentativeValues.clear();
199 return runBlockDiff(L->begin(), R->begin());
202 // Otherwise, tentatively unify them.
203 if (!LeftI->use_empty())
204 TentativeValues.insert(std::make_pair(LeftI, RightI));
207 } while (LI != LE); // This is sufficient: we can't get equality of
208 // terminators if there are residual instructions.
210 // Make all the tentative pairs solid.
211 for (llvm::DenseSet<std::pair<Value*,Value*> >::iterator
212 I = TentativeValues.begin(), E = TentativeValues.end(); I != E; ++I)
213 Values[I->first] = I->second;
214 TentativeValues.clear();
217 bool matchForBlockDiff(Instruction *L, Instruction *R);
218 void runBlockDiff(BasicBlock::iterator LI, BasicBlock::iterator RI);
220 bool diffCallSites(CallSite L, CallSite R, bool Complain) {
221 // FIXME: call attributes
222 if (!equivalentAsOperands(L.getCalledValue(), R.getCalledValue())) {
223 if (Complain) Engine.log("called functions differ");
226 if (L.arg_size() != R.arg_size()) {
227 if (Complain) Engine.log("argument counts differ");
230 for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
231 if (!equivalentAsOperands(L.getArgument(I), R.getArgument(I))) {
233 Engine.logf("arguments %l and %r differ")
234 << L.getArgument(I) << R.getArgument(I);
240 bool diff(Instruction *L, Instruction *R, bool Complain, bool TryUnify) {
241 // FIXME: metadata (if Complain is set)
243 // Different opcodes always imply different operations.
244 if (L->getOpcode() != R->getOpcode()) {
245 if (Complain) Engine.log("different instruction types");
249 if (isa<CmpInst>(L)) {
250 if (cast<CmpInst>(L)->getPredicate()
251 != cast<CmpInst>(R)->getPredicate()) {
252 if (Complain) Engine.log("different predicates");
255 } else if (isa<CallInst>(L)) {
256 return diffCallSites(CallSite(L), CallSite(R), Complain);
257 } else if (isa<PHINode>(L)) {
260 // This is really wierd; type uniquing is broken?
261 if (L->getType() != R->getType()) {
262 if (!L->getType()->isPointerTy() || !R->getType()->isPointerTy()) {
263 if (Complain) Engine.log("different phi types");
270 } else if (isa<InvokeInst>(L)) {
271 InvokeInst *LI = cast<InvokeInst>(L);
272 InvokeInst *RI = cast<InvokeInst>(R);
273 if (diffCallSites(CallSite(LI), CallSite(RI), Complain))
277 tryUnify(LI->getNormalDest(), RI->getNormalDest());
278 tryUnify(LI->getUnwindDest(), RI->getUnwindDest());
282 } else if (isa<BranchInst>(L)) {
283 BranchInst *LI = cast<BranchInst>(L);
284 BranchInst *RI = cast<BranchInst>(R);
285 if (LI->isConditional() != RI->isConditional()) {
286 if (Complain) Engine.log("branch conditionality differs");
290 if (LI->isConditional()) {
291 if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
292 if (Complain) Engine.log("branch conditions differ");
295 if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
297 if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
300 } else if (isa<SwitchInst>(L)) {
301 SwitchInst *LI = cast<SwitchInst>(L);
302 SwitchInst *RI = cast<SwitchInst>(R);
303 if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
304 if (Complain) Engine.log("switch conditions differ");
307 if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
309 bool Difference = false;
311 DenseMap<ConstantInt*,BasicBlock*> LCases;
312 for (unsigned I = 1, E = LI->getNumCases(); I != E; ++I)
313 LCases[LI->getCaseValue(I)] = LI->getSuccessor(I);
314 for (unsigned I = 1, E = RI->getNumCases(); I != E; ++I) {
315 ConstantInt *CaseValue = RI->getCaseValue(I);
316 BasicBlock *LCase = LCases[CaseValue];
318 if (TryUnify) tryUnify(LCase, RI->getSuccessor(I));
319 LCases.erase(CaseValue);
320 } else if (!Difference) {
322 Engine.logf("right switch has extra case %r") << CaseValue;
327 for (DenseMap<ConstantInt*,BasicBlock*>::iterator
328 I = LCases.begin(), E = LCases.end(); I != E; ++I) {
330 Engine.logf("left switch has extra case %l") << I->first;
334 } else if (isa<UnreachableInst>(L)) {
338 if (L->getNumOperands() != R->getNumOperands()) {
339 if (Complain) Engine.log("instructions have different operand counts");
343 for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
344 Value *LO = L->getOperand(I), *RO = R->getOperand(I);
345 if (!equivalentAsOperands(LO, RO)) {
346 if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
354 bool equivalentAsOperands(Constant *L, Constant *R) {
355 // Use equality as a preliminary filter.
359 if (L->getValueID() != R->getValueID())
362 // Ask the engine about global values.
363 if (isa<GlobalValue>(L))
364 return Engine.equivalentAsOperands(cast<GlobalValue>(L),
365 cast<GlobalValue>(R));
367 // Compare constant expressions structurally.
368 if (isa<ConstantExpr>(L))
369 return equivalentAsOperands(cast<ConstantExpr>(L),
370 cast<ConstantExpr>(R));
372 // Nulls of the "same type" don't always actually have the same
373 // type; I don't know why. Just white-list them.
374 if (isa<ConstantPointerNull>(L))
377 // Block addresses only match if we've already encountered the
378 // block. FIXME: tentative matches?
379 if (isa<BlockAddress>(L))
380 return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
381 == cast<BlockAddress>(R)->getBasicBlock();
386 bool equivalentAsOperands(ConstantExpr *L, ConstantExpr *R) {
389 if (L->getOpcode() != R->getOpcode())
392 switch (L->getOpcode()) {
393 case Instruction::ICmp:
394 case Instruction::FCmp:
395 if (L->getPredicate() != R->getPredicate())
399 case Instruction::GetElementPtr:
407 if (L->getNumOperands() != R->getNumOperands())
410 for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I)
411 if (!equivalentAsOperands(L->getOperand(I), R->getOperand(I)))
417 bool equivalentAsOperands(Value *L, Value *R) {
418 // Fall out if the values have different kind.
419 // This possibly shouldn't take priority over oracles.
420 if (L->getValueID() != R->getValueID())
423 // Value subtypes: Argument, Constant, Instruction, BasicBlock,
424 // InlineAsm, MDNode, MDString, PseudoSourceValue
426 if (isa<Constant>(L))
427 return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R));
429 if (isa<Instruction>(L))
430 return Values[L] == R || TentativeValues.count(std::make_pair(L, R));
432 if (isa<Argument>(L))
433 return Values[L] == R;
435 if (isa<BasicBlock>(L))
436 return Blocks[cast<BasicBlock>(L)] != R;
438 // Pretend everything else is identical.
442 // Avoid a gcc warning about accessing 'this' in an initializer.
443 FunctionDifferenceEngine *this_() { return this; }
446 FunctionDifferenceEngine(DifferenceEngine &Engine) :
447 Engine(Engine), Queue(QueueSorter(*this_())) {}
449 void diff(Function *L, Function *R) {
450 if (L->arg_size() != R->arg_size())
451 Engine.log("different argument counts");
453 // Map the arguments.
454 for (Function::arg_iterator
455 LI = L->arg_begin(), LE = L->arg_end(),
456 RI = R->arg_begin(), RE = R->arg_end();
457 LI != LE && RI != RE; ++LI, ++RI)
460 tryUnify(&*L->begin(), &*R->begin());
466 DiffEntry() : Cost(0) {}
469 llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
472 bool FunctionDifferenceEngine::matchForBlockDiff(Instruction *L,
474 return !diff(L, R, false, false);
477 void FunctionDifferenceEngine::runBlockDiff(BasicBlock::iterator LStart,
478 BasicBlock::iterator RStart) {
479 BasicBlock::iterator LE = LStart->getParent()->end();
480 BasicBlock::iterator RE = RStart->getParent()->end();
482 unsigned NL = std::distance(LStart, LE);
484 SmallVector<DiffEntry, 20> Paths1(NL+1);
485 SmallVector<DiffEntry, 20> Paths2(NL+1);
487 DiffEntry *Cur = Paths1.data();
488 DiffEntry *Next = Paths2.data();
490 const unsigned LeftCost = 2;
491 const unsigned RightCost = 2;
492 const unsigned MatchCost = 0;
494 assert(TentativeValues.empty());
496 // Initialize the first column.
497 for (unsigned I = 0; I != NL+1; ++I) {
498 Cur[I].Cost = I * LeftCost;
499 for (unsigned J = 0; J != I; ++J)
500 Cur[I].Path.push_back(DifferenceEngine::DC_left);
503 for (BasicBlock::iterator RI = RStart; RI != RE; ++RI) {
504 // Initialize the first row.
506 Next[0].Cost += RightCost;
507 Next[0].Path.push_back(DifferenceEngine::DC_right);
510 for (BasicBlock::iterator LI = LStart; LI != LE; ++LI, ++Index) {
511 if (matchForBlockDiff(&*LI, &*RI)) {
512 Next[Index] = Cur[Index-1];
513 Next[Index].Cost += MatchCost;
514 Next[Index].Path.push_back(DifferenceEngine::DC_match);
515 TentativeValues.insert(std::make_pair(&*LI, &*RI));
516 } else if (Next[Index-1].Cost <= Cur[Index].Cost) {
517 Next[Index] = Next[Index-1];
518 Next[Index].Cost += LeftCost;
519 Next[Index].Path.push_back(DifferenceEngine::DC_left);
521 Next[Index] = Cur[Index];
522 Next[Index].Cost += RightCost;
523 Next[Index].Path.push_back(DifferenceEngine::DC_right);
527 std::swap(Cur, Next);
530 SmallVectorImpl<char> &Path = Cur[NL].Path;
531 BasicBlock::iterator LI = LStart, RI = RStart;
533 DifferenceEngine::DiffLogBuilder Diff(Engine);
535 // Drop trailing matches.
536 while (Path.back() == DifferenceEngine::DC_match)
539 // Skip leading matches.
540 SmallVectorImpl<char>::iterator
541 PI = Path.begin(), PE = Path.end();
542 while (PI != PE && *PI == DifferenceEngine::DC_match)
545 for (; PI != PE; ++PI) {
546 switch (static_cast<DifferenceEngine::DiffChange>(*PI)) {
547 case DifferenceEngine::DC_match:
548 assert(LI != LE && RI != RE);
550 Instruction *L = &*LI, *R = &*RI;
551 DifferenceEngine::Context C(Engine, L, R);
552 diff(L, R, true, true); // complain and unify successors
553 Values[L] = R; // make non-tentative
559 case DifferenceEngine::DC_left:
565 case DifferenceEngine::DC_right:
573 TentativeValues.clear();
578 void DifferenceEngine::diff(Function *L, Function *R) {
579 Context C(*this, L, R);
582 // FIXME: attributes and CC
583 // FIXME: parameter attributes
585 // If both are declarations, we're done.
586 if (L->empty() && R->empty())
589 log("left function is declaration, right function is definition");
591 log("right function is declaration, left function is definition");
593 FunctionDifferenceEngine(*this).diff(L, R);
596 void DifferenceEngine::diff(Module *L, Module *R) {
598 SmallVector<std::pair<Function*,Function*>, 20> Queue;
600 for (Module::iterator I = L->begin(), E = L->end(); I != E; ++I) {
602 LNames.insert(LFn->getName());
604 if (Function *RFn = R->getFunction(LFn->getName()))
605 Queue.push_back(std::make_pair(LFn, RFn));
607 logf("function %l exists only in left module") << LFn;
610 for (Module::iterator I = R->begin(), E = R->end(); I != E; ++I) {
612 if (!LNames.count(RFn->getName()))
613 logf("function %r exists only in right module") << RFn;
616 for (SmallVectorImpl<std::pair<Function*,Function*> >::iterator
617 I = Queue.begin(), E = Queue.end(); I != E; ++I)
618 diff(I->first, I->second);
621 bool DifferenceEngine::equivalentAsOperands(GlobalValue *L, GlobalValue *R) {
622 if (globalValueOracle) return (*globalValueOracle)(L, R);
623 return L->getName() == R->getName();