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