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 for (auto Case : LI->cases()) 319 LCases[Case.getCaseValue()] = Case.getCaseSuccessor(); 320 321 for (auto Case : RI->cases()) { 322 ConstantInt *CaseValue = Case.getCaseValue(); 323 BasicBlock *LCase = LCases[CaseValue]; 324 if (LCase) { 325 if (TryUnify) 326 tryUnify(LCase, Case.getCaseSuccessor()); 327 LCases.erase(CaseValue); 328 } else if (Complain || !Difference) { 329 if (Complain) 330 Engine.logf("right switch has extra case %r") << CaseValue; 331 Difference = true; 332 } 333 } 334 if (!Difference) 335 for (DenseMap<ConstantInt*,BasicBlock*>::iterator 336 I = LCases.begin(), E = LCases.end(); I != E; ++I) { 337 if (Complain) 338 Engine.logf("left switch has extra case %l") << I->first; 339 Difference = true; 340 } 341 return Difference; 342 } else if (isa<UnreachableInst>(L)) { 343 return false; 344 } 345 346 if (L->getNumOperands() != R->getNumOperands()) { 347 if (Complain) Engine.log("instructions have different operand counts"); 348 return true; 349 } 350 351 for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) { 352 Value *LO = L->getOperand(I), *RO = R->getOperand(I); 353 if (!equivalentAsOperands(LO, RO)) { 354 if (Complain) Engine.logf("operands %l and %r differ") << LO << RO; 355 return true; 356 } 357 } 358 359 return false; 360 } 361 362 bool equivalentAsOperands(Constant *L, Constant *R) { 363 // Use equality as a preliminary filter. 364 if (L == R) 365 return true; 366 367 if (L->getValueID() != R->getValueID()) 368 return false; 369 370 // Ask the engine about global values. 371 if (isa<GlobalValue>(L)) 372 return Engine.equivalentAsOperands(cast<GlobalValue>(L), 373 cast<GlobalValue>(R)); 374 375 // Compare constant expressions structurally. 376 if (isa<ConstantExpr>(L)) 377 return equivalentAsOperands(cast<ConstantExpr>(L), 378 cast<ConstantExpr>(R)); 379 380 // Nulls of the "same type" don't always actually have the same 381 // type; I don't know why. Just white-list them. 382 if (isa<ConstantPointerNull>(L)) 383 return true; 384 385 // Block addresses only match if we've already encountered the 386 // block. FIXME: tentative matches? 387 if (isa<BlockAddress>(L)) 388 return Blocks[cast<BlockAddress>(L)->getBasicBlock()] 389 == cast<BlockAddress>(R)->getBasicBlock(); 390 391 return false; 392 } 393 394 bool equivalentAsOperands(ConstantExpr *L, ConstantExpr *R) { 395 if (L == R) 396 return true; 397 if (L->getOpcode() != R->getOpcode()) 398 return false; 399 400 switch (L->getOpcode()) { 401 case Instruction::ICmp: 402 case Instruction::FCmp: 403 if (L->getPredicate() != R->getPredicate()) 404 return false; 405 break; 406 407 case Instruction::GetElementPtr: 408 // FIXME: inbounds? 409 break; 410 411 default: 412 break; 413 } 414 415 if (L->getNumOperands() != R->getNumOperands()) 416 return false; 417 418 for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) 419 if (!equivalentAsOperands(L->getOperand(I), R->getOperand(I))) 420 return false; 421 422 return true; 423 } 424 425 bool equivalentAsOperands(Value *L, Value *R) { 426 // Fall out if the values have different kind. 427 // This possibly shouldn't take priority over oracles. 428 if (L->getValueID() != R->getValueID()) 429 return false; 430 431 // Value subtypes: Argument, Constant, Instruction, BasicBlock, 432 // InlineAsm, MDNode, MDString, PseudoSourceValue 433 434 if (isa<Constant>(L)) 435 return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R)); 436 437 if (isa<Instruction>(L)) 438 return Values[L] == R || TentativeValues.count(std::make_pair(L, R)); 439 440 if (isa<Argument>(L)) 441 return Values[L] == R; 442 443 if (isa<BasicBlock>(L)) 444 return Blocks[cast<BasicBlock>(L)] != R; 445 446 // Pretend everything else is identical. 447 return true; 448 } 449 450 // Avoid a gcc warning about accessing 'this' in an initializer. 451 FunctionDifferenceEngine *this_() { return this; } 452 453 public: 454 FunctionDifferenceEngine(DifferenceEngine &Engine) : 455 Engine(Engine), Queue(QueueSorter(*this_())) {} 456 457 void diff(Function *L, Function *R) { 458 if (L->arg_size() != R->arg_size()) 459 Engine.log("different argument counts"); 460 461 // Map the arguments. 462 for (Function::arg_iterator 463 LI = L->arg_begin(), LE = L->arg_end(), 464 RI = R->arg_begin(), RE = R->arg_end(); 465 LI != LE && RI != RE; ++LI, ++RI) 466 Values[&*LI] = &*RI; 467 468 tryUnify(&*L->begin(), &*R->begin()); 469 processQueue(); 470 } 471 }; 472 473 struct DiffEntry { 474 DiffEntry() : Cost(0) {} 475 476 unsigned Cost; 477 llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange 478 }; 479 480 bool FunctionDifferenceEngine::matchForBlockDiff(Instruction *L, 481 Instruction *R) { 482 return !diff(L, R, false, false); 483 } 484 485 void FunctionDifferenceEngine::runBlockDiff(BasicBlock::iterator LStart, 486 BasicBlock::iterator RStart) { 487 BasicBlock::iterator LE = LStart->getParent()->end(); 488 BasicBlock::iterator RE = RStart->getParent()->end(); 489 490 unsigned NL = std::distance(LStart, LE); 491 492 SmallVector<DiffEntry, 20> Paths1(NL+1); 493 SmallVector<DiffEntry, 20> Paths2(NL+1); 494 495 DiffEntry *Cur = Paths1.data(); 496 DiffEntry *Next = Paths2.data(); 497 498 const unsigned LeftCost = 2; 499 const unsigned RightCost = 2; 500 const unsigned MatchCost = 0; 501 502 assert(TentativeValues.empty()); 503 504 // Initialize the first column. 505 for (unsigned I = 0; I != NL+1; ++I) { 506 Cur[I].Cost = I * LeftCost; 507 for (unsigned J = 0; J != I; ++J) 508 Cur[I].Path.push_back(DC_left); 509 } 510 511 for (BasicBlock::iterator RI = RStart; RI != RE; ++RI) { 512 // Initialize the first row. 513 Next[0] = Cur[0]; 514 Next[0].Cost += RightCost; 515 Next[0].Path.push_back(DC_right); 516 517 unsigned Index = 1; 518 for (BasicBlock::iterator LI = LStart; LI != LE; ++LI, ++Index) { 519 if (matchForBlockDiff(&*LI, &*RI)) { 520 Next[Index] = Cur[Index-1]; 521 Next[Index].Cost += MatchCost; 522 Next[Index].Path.push_back(DC_match); 523 TentativeValues.insert(std::make_pair(&*LI, &*RI)); 524 } else if (Next[Index-1].Cost <= Cur[Index].Cost) { 525 Next[Index] = Next[Index-1]; 526 Next[Index].Cost += LeftCost; 527 Next[Index].Path.push_back(DC_left); 528 } else { 529 Next[Index] = Cur[Index]; 530 Next[Index].Cost += RightCost; 531 Next[Index].Path.push_back(DC_right); 532 } 533 } 534 535 std::swap(Cur, Next); 536 } 537 538 // We don't need the tentative values anymore; everything from here 539 // on out should be non-tentative. 540 TentativeValues.clear(); 541 542 SmallVectorImpl<char> &Path = Cur[NL].Path; 543 BasicBlock::iterator LI = LStart, RI = RStart; 544 545 DiffLogBuilder Diff(Engine.getConsumer()); 546 547 // Drop trailing matches. 548 while (Path.back() == DC_match) 549 Path.pop_back(); 550 551 // Skip leading matches. 552 SmallVectorImpl<char>::iterator 553 PI = Path.begin(), PE = Path.end(); 554 while (PI != PE && *PI == DC_match) { 555 unify(&*LI, &*RI); 556 ++PI; 557 ++LI; 558 ++RI; 559 } 560 561 for (; PI != PE; ++PI) { 562 switch (static_cast<DiffChange>(*PI)) { 563 case DC_match: 564 assert(LI != LE && RI != RE); 565 { 566 Instruction *L = &*LI, *R = &*RI; 567 unify(L, R); 568 Diff.addMatch(L, R); 569 } 570 ++LI; ++RI; 571 break; 572 573 case DC_left: 574 assert(LI != LE); 575 Diff.addLeft(&*LI); 576 ++LI; 577 break; 578 579 case DC_right: 580 assert(RI != RE); 581 Diff.addRight(&*RI); 582 ++RI; 583 break; 584 } 585 } 586 587 // Finishing unifying and complaining about the tails of the block, 588 // which should be matches all the way through. 589 while (LI != LE) { 590 assert(RI != RE); 591 unify(&*LI, &*RI); 592 ++LI; 593 ++RI; 594 } 595 596 // If the terminators have different kinds, but one is an invoke and the 597 // other is an unconditional branch immediately following a call, unify 598 // the results and the destinations. 599 TerminatorInst *LTerm = LStart->getParent()->getTerminator(); 600 TerminatorInst *RTerm = RStart->getParent()->getTerminator(); 601 if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) { 602 if (cast<BranchInst>(LTerm)->isConditional()) return; 603 BasicBlock::iterator I = LTerm->getIterator(); 604 if (I == LStart->getParent()->begin()) return; 605 --I; 606 if (!isa<CallInst>(*I)) return; 607 CallInst *LCall = cast<CallInst>(&*I); 608 InvokeInst *RInvoke = cast<InvokeInst>(RTerm); 609 if (!equivalentAsOperands(LCall->getCalledValue(), RInvoke->getCalledValue())) 610 return; 611 if (!LCall->use_empty()) 612 Values[LCall] = RInvoke; 613 tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest()); 614 } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) { 615 if (cast<BranchInst>(RTerm)->isConditional()) return; 616 BasicBlock::iterator I = RTerm->getIterator(); 617 if (I == RStart->getParent()->begin()) return; 618 --I; 619 if (!isa<CallInst>(*I)) return; 620 CallInst *RCall = cast<CallInst>(I); 621 InvokeInst *LInvoke = cast<InvokeInst>(LTerm); 622 if (!equivalentAsOperands(LInvoke->getCalledValue(), RCall->getCalledValue())) 623 return; 624 if (!LInvoke->use_empty()) 625 Values[LInvoke] = RCall; 626 tryUnify(LInvoke->getNormalDest(), RTerm->getSuccessor(0)); 627 } 628 } 629 630 } 631 632 void DifferenceEngine::Oracle::anchor() { } 633 634 void DifferenceEngine::diff(Function *L, Function *R) { 635 Context C(*this, L, R); 636 637 // FIXME: types 638 // FIXME: attributes and CC 639 // FIXME: parameter attributes 640 641 // If both are declarations, we're done. 642 if (L->empty() && R->empty()) 643 return; 644 else if (L->empty()) 645 log("left function is declaration, right function is definition"); 646 else if (R->empty()) 647 log("right function is declaration, left function is definition"); 648 else 649 FunctionDifferenceEngine(*this).diff(L, R); 650 } 651 652 void DifferenceEngine::diff(Module *L, Module *R) { 653 StringSet<> LNames; 654 SmallVector<std::pair<Function*,Function*>, 20> Queue; 655 656 for (Module::iterator I = L->begin(), E = L->end(); I != E; ++I) { 657 Function *LFn = &*I; 658 LNames.insert(LFn->getName()); 659 660 if (Function *RFn = R->getFunction(LFn->getName())) 661 Queue.push_back(std::make_pair(LFn, RFn)); 662 else 663 logf("function %l exists only in left module") << LFn; 664 } 665 666 for (Module::iterator I = R->begin(), E = R->end(); I != E; ++I) { 667 Function *RFn = &*I; 668 if (!LNames.count(RFn->getName())) 669 logf("function %r exists only in right module") << RFn; 670 } 671 672 for (SmallVectorImpl<std::pair<Function*,Function*> >::iterator 673 I = Queue.begin(), E = Queue.end(); I != E; ++I) 674 diff(I->first, I->second); 675 } 676 677 bool DifferenceEngine::equivalentAsOperands(GlobalValue *L, GlobalValue *R) { 678 if (globalValueOracle) return (*globalValueOracle)(L, R); 679 return L->getName() == R->getName(); 680 } 681