1 //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===// 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 // Pass to verify generated machine code. The following is checked: 11 // 12 // Operand counts: All explicit operands must be present. 13 // 14 // Register classes: All physical and virtual register operands must be 15 // compatible with the register class required by the instruction descriptor. 16 // 17 // Register live intervals: Registers must be defined only once, and must be 18 // defined before use. 19 // 20 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the 21 // command-line option -verify-machineinstrs, or by defining the environment 22 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive 23 // the verifier errors. 24 //===----------------------------------------------------------------------===// 25 26 #include "llvm/CodeGen/Passes.h" 27 #include "llvm/ADT/DenseSet.h" 28 #include "llvm/ADT/DepthFirstIterator.h" 29 #include "llvm/ADT/SetOperations.h" 30 #include "llvm/ADT/SmallVector.h" 31 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 32 #include "llvm/CodeGen/LiveStackAnalysis.h" 33 #include "llvm/CodeGen/LiveVariables.h" 34 #include "llvm/CodeGen/MachineFrameInfo.h" 35 #include "llvm/CodeGen/MachineFunctionPass.h" 36 #include "llvm/CodeGen/MachineMemOperand.h" 37 #include "llvm/CodeGen/MachineRegisterInfo.h" 38 #include "llvm/IR/BasicBlock.h" 39 #include "llvm/IR/InlineAsm.h" 40 #include "llvm/IR/Instructions.h" 41 #include "llvm/MC/MCAsmInfo.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/FileSystem.h" 45 #include "llvm/Support/Format.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Target/TargetInstrInfo.h" 48 #include "llvm/Target/TargetMachine.h" 49 #include "llvm/Target/TargetRegisterInfo.h" 50 #include "llvm/Target/TargetSubtargetInfo.h" 51 using namespace llvm; 52 53 namespace { 54 struct MachineVerifier { 55 56 MachineVerifier(Pass *pass, const char *b) : 57 PASS(pass), 58 Banner(b) 59 {} 60 61 bool runOnMachineFunction(MachineFunction &MF); 62 63 Pass *const PASS; 64 const char *Banner; 65 const MachineFunction *MF; 66 const TargetMachine *TM; 67 const TargetInstrInfo *TII; 68 const TargetRegisterInfo *TRI; 69 const MachineRegisterInfo *MRI; 70 71 unsigned foundErrors; 72 73 typedef SmallVector<unsigned, 16> RegVector; 74 typedef SmallVector<const uint32_t*, 4> RegMaskVector; 75 typedef DenseSet<unsigned> RegSet; 76 typedef DenseMap<unsigned, const MachineInstr*> RegMap; 77 typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet; 78 79 const MachineInstr *FirstTerminator; 80 BlockSet FunctionBlocks; 81 82 BitVector regsReserved; 83 RegSet regsLive; 84 RegVector regsDefined, regsDead, regsKilled; 85 RegMaskVector regMasks; 86 RegSet regsLiveInButUnused; 87 88 SlotIndex lastIndex; 89 90 // Add Reg and any sub-registers to RV 91 void addRegWithSubRegs(RegVector &RV, unsigned Reg) { 92 RV.push_back(Reg); 93 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 94 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) 95 RV.push_back(*SubRegs); 96 } 97 98 struct BBInfo { 99 // Is this MBB reachable from the MF entry point? 100 bool reachable; 101 102 // Vregs that must be live in because they are used without being 103 // defined. Map value is the user. 104 RegMap vregsLiveIn; 105 106 // Regs killed in MBB. They may be defined again, and will then be in both 107 // regsKilled and regsLiveOut. 108 RegSet regsKilled; 109 110 // Regs defined in MBB and live out. Note that vregs passing through may 111 // be live out without being mentioned here. 112 RegSet regsLiveOut; 113 114 // Vregs that pass through MBB untouched. This set is disjoint from 115 // regsKilled and regsLiveOut. 116 RegSet vregsPassed; 117 118 // Vregs that must pass through MBB because they are needed by a successor 119 // block. This set is disjoint from regsLiveOut. 120 RegSet vregsRequired; 121 122 // Set versions of block's predecessor and successor lists. 123 BlockSet Preds, Succs; 124 125 BBInfo() : reachable(false) {} 126 127 // Add register to vregsPassed if it belongs there. Return true if 128 // anything changed. 129 bool addPassed(unsigned Reg) { 130 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 131 return false; 132 if (regsKilled.count(Reg) || regsLiveOut.count(Reg)) 133 return false; 134 return vregsPassed.insert(Reg).second; 135 } 136 137 // Same for a full set. 138 bool addPassed(const RegSet &RS) { 139 bool changed = false; 140 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I) 141 if (addPassed(*I)) 142 changed = true; 143 return changed; 144 } 145 146 // Add register to vregsRequired if it belongs there. Return true if 147 // anything changed. 148 bool addRequired(unsigned Reg) { 149 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 150 return false; 151 if (regsLiveOut.count(Reg)) 152 return false; 153 return vregsRequired.insert(Reg).second; 154 } 155 156 // Same for a full set. 157 bool addRequired(const RegSet &RS) { 158 bool changed = false; 159 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I) 160 if (addRequired(*I)) 161 changed = true; 162 return changed; 163 } 164 165 // Same for a full map. 166 bool addRequired(const RegMap &RM) { 167 bool changed = false; 168 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I) 169 if (addRequired(I->first)) 170 changed = true; 171 return changed; 172 } 173 174 // Live-out registers are either in regsLiveOut or vregsPassed. 175 bool isLiveOut(unsigned Reg) const { 176 return regsLiveOut.count(Reg) || vregsPassed.count(Reg); 177 } 178 }; 179 180 // Extra register info per MBB. 181 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap; 182 183 bool isReserved(unsigned Reg) { 184 return Reg < regsReserved.size() && regsReserved.test(Reg); 185 } 186 187 bool isAllocatable(unsigned Reg) { 188 return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg); 189 } 190 191 // Analysis information if available 192 LiveVariables *LiveVars; 193 LiveIntervals *LiveInts; 194 LiveStacks *LiveStks; 195 SlotIndexes *Indexes; 196 197 void visitMachineFunctionBefore(); 198 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB); 199 void visitMachineBundleBefore(const MachineInstr *MI); 200 void visitMachineInstrBefore(const MachineInstr *MI); 201 void visitMachineOperand(const MachineOperand *MO, unsigned MONum); 202 void visitMachineInstrAfter(const MachineInstr *MI); 203 void visitMachineBundleAfter(const MachineInstr *MI); 204 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB); 205 void visitMachineFunctionAfter(); 206 207 void report(const char *msg, const MachineFunction *MF); 208 void report(const char *msg, const MachineBasicBlock *MBB); 209 void report(const char *msg, const MachineInstr *MI); 210 void report(const char *msg, const MachineOperand *MO, unsigned MONum); 211 void report(const char *msg, const MachineFunction *MF, 212 const LiveInterval &LI); 213 void report(const char *msg, const MachineBasicBlock *MBB, 214 const LiveInterval &LI); 215 void report(const char *msg, const MachineFunction *MF, 216 const LiveRange &LR, unsigned Reg, unsigned LaneMask); 217 void report(const char *msg, const MachineBasicBlock *MBB, 218 const LiveRange &LR, unsigned Reg, unsigned LaneMask); 219 220 void verifyInlineAsm(const MachineInstr *MI); 221 222 void checkLiveness(const MachineOperand *MO, unsigned MONum); 223 void markReachable(const MachineBasicBlock *MBB); 224 void calcRegsPassed(); 225 void checkPHIOps(const MachineBasicBlock *MBB); 226 227 void calcRegsRequired(); 228 void verifyLiveVariables(); 229 void verifyLiveIntervals(); 230 void verifyLiveInterval(const LiveInterval&); 231 void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned, 232 unsigned); 233 void verifyLiveRangeSegment(const LiveRange&, 234 const LiveRange::const_iterator I, unsigned, 235 unsigned); 236 void verifyLiveRange(const LiveRange&, unsigned, unsigned LaneMask = 0); 237 238 void verifyStackFrame(); 239 240 void verifySlotIndexes() const; 241 }; 242 243 struct MachineVerifierPass : public MachineFunctionPass { 244 static char ID; // Pass ID, replacement for typeid 245 const std::string Banner; 246 247 MachineVerifierPass(const std::string &banner = nullptr) 248 : MachineFunctionPass(ID), Banner(banner) { 249 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry()); 250 } 251 252 void getAnalysisUsage(AnalysisUsage &AU) const override { 253 AU.setPreservesAll(); 254 MachineFunctionPass::getAnalysisUsage(AU); 255 } 256 257 bool runOnMachineFunction(MachineFunction &MF) override { 258 MF.verify(this, Banner.c_str()); 259 return false; 260 } 261 }; 262 263 } 264 265 char MachineVerifierPass::ID = 0; 266 INITIALIZE_PASS(MachineVerifierPass, "machineverifier", 267 "Verify generated machine code", false, false) 268 269 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) { 270 return new MachineVerifierPass(Banner); 271 } 272 273 void MachineFunction::verify(Pass *p, const char *Banner) const { 274 MachineVerifier(p, Banner) 275 .runOnMachineFunction(const_cast<MachineFunction&>(*this)); 276 } 277 278 void MachineVerifier::verifySlotIndexes() const { 279 if (Indexes == nullptr) 280 return; 281 282 // Ensure the IdxMBB list is sorted by slot indexes. 283 SlotIndex Last; 284 for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(), 285 E = Indexes->MBBIndexEnd(); I != E; ++I) { 286 assert(!Last.isValid() || I->first > Last); 287 Last = I->first; 288 } 289 } 290 291 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) { 292 foundErrors = 0; 293 294 this->MF = &MF; 295 TM = &MF.getTarget(); 296 TII = MF.getSubtarget().getInstrInfo(); 297 TRI = MF.getSubtarget().getRegisterInfo(); 298 MRI = &MF.getRegInfo(); 299 300 LiveVars = nullptr; 301 LiveInts = nullptr; 302 LiveStks = nullptr; 303 Indexes = nullptr; 304 if (PASS) { 305 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>(); 306 // We don't want to verify LiveVariables if LiveIntervals is available. 307 if (!LiveInts) 308 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>(); 309 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>(); 310 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>(); 311 } 312 313 verifySlotIndexes(); 314 315 visitMachineFunctionBefore(); 316 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end(); 317 MFI!=MFE; ++MFI) { 318 visitMachineBasicBlockBefore(MFI); 319 // Keep track of the current bundle header. 320 const MachineInstr *CurBundle = nullptr; 321 // Do we expect the next instruction to be part of the same bundle? 322 bool InBundle = false; 323 324 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(), 325 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) { 326 if (MBBI->getParent() != MFI) { 327 report("Bad instruction parent pointer", MFI); 328 errs() << "Instruction: " << *MBBI; 329 continue; 330 } 331 332 // Check for consistent bundle flags. 333 if (InBundle && !MBBI->isBundledWithPred()) 334 report("Missing BundledPred flag, " 335 "BundledSucc was set on predecessor", MBBI); 336 if (!InBundle && MBBI->isBundledWithPred()) 337 report("BundledPred flag is set, " 338 "but BundledSucc not set on predecessor", MBBI); 339 340 // Is this a bundle header? 341 if (!MBBI->isInsideBundle()) { 342 if (CurBundle) 343 visitMachineBundleAfter(CurBundle); 344 CurBundle = MBBI; 345 visitMachineBundleBefore(CurBundle); 346 } else if (!CurBundle) 347 report("No bundle header", MBBI); 348 visitMachineInstrBefore(MBBI); 349 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) { 350 const MachineInstr &MI = *MBBI; 351 const MachineOperand &Op = MI.getOperand(I); 352 if (Op.getParent() != &MI) { 353 // Make sure to use correct addOperand / RemoveOperand / ChangeTo 354 // functions when replacing operands of a MachineInstr. 355 report("Instruction has operand with wrong parent set", &MI); 356 } 357 358 visitMachineOperand(&Op, I); 359 } 360 361 visitMachineInstrAfter(MBBI); 362 363 // Was this the last bundled instruction? 364 InBundle = MBBI->isBundledWithSucc(); 365 } 366 if (CurBundle) 367 visitMachineBundleAfter(CurBundle); 368 if (InBundle) 369 report("BundledSucc flag set on last instruction in block", &MFI->back()); 370 visitMachineBasicBlockAfter(MFI); 371 } 372 visitMachineFunctionAfter(); 373 374 if (foundErrors) 375 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors."); 376 377 // Clean up. 378 regsLive.clear(); 379 regsDefined.clear(); 380 regsDead.clear(); 381 regsKilled.clear(); 382 regMasks.clear(); 383 regsLiveInButUnused.clear(); 384 MBBInfoMap.clear(); 385 386 return false; // no changes 387 } 388 389 void MachineVerifier::report(const char *msg, const MachineFunction *MF) { 390 assert(MF); 391 errs() << '\n'; 392 if (!foundErrors++) { 393 if (Banner) 394 errs() << "# " << Banner << '\n'; 395 MF->print(errs(), Indexes); 396 } 397 errs() << "*** Bad machine code: " << msg << " ***\n" 398 << "- function: " << MF->getName() << "\n"; 399 } 400 401 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) { 402 assert(MBB); 403 report(msg, MBB->getParent()); 404 errs() << "- basic block: BB#" << MBB->getNumber() 405 << ' ' << MBB->getName() 406 << " (" << (const void*)MBB << ')'; 407 if (Indexes) 408 errs() << " [" << Indexes->getMBBStartIdx(MBB) 409 << ';' << Indexes->getMBBEndIdx(MBB) << ')'; 410 errs() << '\n'; 411 } 412 413 void MachineVerifier::report(const char *msg, const MachineInstr *MI) { 414 assert(MI); 415 report(msg, MI->getParent()); 416 errs() << "- instruction: "; 417 if (Indexes && Indexes->hasIndex(MI)) 418 errs() << Indexes->getInstructionIndex(MI) << '\t'; 419 MI->print(errs(), TM); 420 } 421 422 void MachineVerifier::report(const char *msg, 423 const MachineOperand *MO, unsigned MONum) { 424 assert(MO); 425 report(msg, MO->getParent()); 426 errs() << "- operand " << MONum << ": "; 427 MO->print(errs(), TRI); 428 errs() << "\n"; 429 } 430 431 void MachineVerifier::report(const char *msg, const MachineFunction *MF, 432 const LiveInterval &LI) { 433 report(msg, MF); 434 errs() << "- interval: " << LI << '\n'; 435 } 436 437 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB, 438 const LiveInterval &LI) { 439 report(msg, MBB); 440 errs() << "- interval: " << LI << '\n'; 441 } 442 443 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB, 444 const LiveRange &LR, unsigned Reg, 445 unsigned LaneMask) { 446 report(msg, MBB); 447 errs() << "- liverange: " << LR << '\n'; 448 errs() << "- register: " << PrintReg(Reg, TRI) << '\n'; 449 if (LaneMask != 0) 450 errs() << "- lanemask: " << format("%04X\n", LaneMask); 451 } 452 453 void MachineVerifier::report(const char *msg, const MachineFunction *MF, 454 const LiveRange &LR, unsigned Reg, 455 unsigned LaneMask) { 456 report(msg, MF); 457 errs() << "- liverange: " << LR << '\n'; 458 errs() << "- register: " << PrintReg(Reg, TRI) << '\n'; 459 if (LaneMask != 0) 460 errs() << "- lanemask: " << format("%04X\n", LaneMask); 461 } 462 463 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) { 464 BBInfo &MInfo = MBBInfoMap[MBB]; 465 if (!MInfo.reachable) { 466 MInfo.reachable = true; 467 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(), 468 SuE = MBB->succ_end(); SuI != SuE; ++SuI) 469 markReachable(*SuI); 470 } 471 } 472 473 void MachineVerifier::visitMachineFunctionBefore() { 474 lastIndex = SlotIndex(); 475 regsReserved = MRI->getReservedRegs(); 476 477 // A sub-register of a reserved register is also reserved 478 for (int Reg = regsReserved.find_first(); Reg>=0; 479 Reg = regsReserved.find_next(Reg)) { 480 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) { 481 // FIXME: This should probably be: 482 // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register"); 483 regsReserved.set(*SubRegs); 484 } 485 } 486 487 markReachable(&MF->front()); 488 489 // Build a set of the basic blocks in the function. 490 FunctionBlocks.clear(); 491 for (const auto &MBB : *MF) { 492 FunctionBlocks.insert(&MBB); 493 BBInfo &MInfo = MBBInfoMap[&MBB]; 494 495 MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end()); 496 if (MInfo.Preds.size() != MBB.pred_size()) 497 report("MBB has duplicate entries in its predecessor list.", &MBB); 498 499 MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end()); 500 if (MInfo.Succs.size() != MBB.succ_size()) 501 report("MBB has duplicate entries in its successor list.", &MBB); 502 } 503 504 // Check that the register use lists are sane. 505 MRI->verifyUseLists(); 506 507 verifyStackFrame(); 508 } 509 510 // Does iterator point to a and b as the first two elements? 511 static bool matchPair(MachineBasicBlock::const_succ_iterator i, 512 const MachineBasicBlock *a, const MachineBasicBlock *b) { 513 if (*i == a) 514 return *++i == b; 515 if (*i == b) 516 return *++i == a; 517 return false; 518 } 519 520 void 521 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) { 522 FirstTerminator = nullptr; 523 524 if (MRI->isSSA()) { 525 // If this block has allocatable physical registers live-in, check that 526 // it is an entry block or landing pad. 527 for (const auto &LI : MBB->liveins()) { 528 if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() && 529 MBB != MBB->getParent()->begin()) { 530 report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB); 531 } 532 } 533 } 534 535 // Count the number of landing pad successors. 536 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs; 537 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(), 538 E = MBB->succ_end(); I != E; ++I) { 539 if ((*I)->isEHPad()) 540 LandingPadSuccs.insert(*I); 541 if (!FunctionBlocks.count(*I)) 542 report("MBB has successor that isn't part of the function.", MBB); 543 if (!MBBInfoMap[*I].Preds.count(MBB)) { 544 report("Inconsistent CFG", MBB); 545 errs() << "MBB is not in the predecessor list of the successor BB#" 546 << (*I)->getNumber() << ".\n"; 547 } 548 } 549 550 // Check the predecessor list. 551 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(), 552 E = MBB->pred_end(); I != E; ++I) { 553 if (!FunctionBlocks.count(*I)) 554 report("MBB has predecessor that isn't part of the function.", MBB); 555 if (!MBBInfoMap[*I].Succs.count(MBB)) { 556 report("Inconsistent CFG", MBB); 557 errs() << "MBB is not in the successor list of the predecessor BB#" 558 << (*I)->getNumber() << ".\n"; 559 } 560 } 561 562 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo(); 563 const BasicBlock *BB = MBB->getBasicBlock(); 564 if (LandingPadSuccs.size() > 1 && 565 !(AsmInfo && 566 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj && 567 BB && isa<SwitchInst>(BB->getTerminator()))) 568 report("MBB has more than one landing pad successor", MBB); 569 570 // Call AnalyzeBranch. If it succeeds, there several more conditions to check. 571 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 572 SmallVector<MachineOperand, 4> Cond; 573 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB), 574 TBB, FBB, Cond)) { 575 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's 576 // check whether its answers match up with reality. 577 if (!TBB && !FBB) { 578 // Block falls through to its successor. 579 MachineFunction::const_iterator MBBI = MBB; 580 ++MBBI; 581 if (MBBI == MF->end()) { 582 // It's possible that the block legitimately ends with a noreturn 583 // call or an unreachable, in which case it won't actually fall 584 // out the bottom of the function. 585 } else if (MBB->succ_size() == LandingPadSuccs.size()) { 586 // It's possible that the block legitimately ends with a noreturn 587 // call or an unreachable, in which case it won't actuall fall 588 // out of the block. 589 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) { 590 report("MBB exits via unconditional fall-through but doesn't have " 591 "exactly one CFG successor!", MBB); 592 } else if (!MBB->isSuccessor(MBBI)) { 593 report("MBB exits via unconditional fall-through but its successor " 594 "differs from its CFG successor!", MBB); 595 } 596 if (!MBB->empty() && MBB->back().isBarrier() && 597 !TII->isPredicated(&MBB->back())) { 598 report("MBB exits via unconditional fall-through but ends with a " 599 "barrier instruction!", MBB); 600 } 601 if (!Cond.empty()) { 602 report("MBB exits via unconditional fall-through but has a condition!", 603 MBB); 604 } 605 } else if (TBB && !FBB && Cond.empty()) { 606 // Block unconditionally branches somewhere. 607 // If the block has exactly one successor, that happens to be a 608 // landingpad, accept it as valid control flow. 609 if (MBB->succ_size() != 1+LandingPadSuccs.size() && 610 (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 || 611 *MBB->succ_begin() != *LandingPadSuccs.begin())) { 612 report("MBB exits via unconditional branch but doesn't have " 613 "exactly one CFG successor!", MBB); 614 } else if (!MBB->isSuccessor(TBB)) { 615 report("MBB exits via unconditional branch but the CFG " 616 "successor doesn't match the actual successor!", MBB); 617 } 618 if (MBB->empty()) { 619 report("MBB exits via unconditional branch but doesn't contain " 620 "any instructions!", MBB); 621 } else if (!MBB->back().isBarrier()) { 622 report("MBB exits via unconditional branch but doesn't end with a " 623 "barrier instruction!", MBB); 624 } else if (!MBB->back().isTerminator()) { 625 report("MBB exits via unconditional branch but the branch isn't a " 626 "terminator instruction!", MBB); 627 } 628 } else if (TBB && !FBB && !Cond.empty()) { 629 // Block conditionally branches somewhere, otherwise falls through. 630 MachineFunction::const_iterator MBBI = MBB; 631 ++MBBI; 632 if (MBBI == MF->end()) { 633 report("MBB conditionally falls through out of function!", MBB); 634 } else if (MBB->succ_size() == 1) { 635 // A conditional branch with only one successor is weird, but allowed. 636 if (&*MBBI != TBB) 637 report("MBB exits via conditional branch/fall-through but only has " 638 "one CFG successor!", MBB); 639 else if (TBB != *MBB->succ_begin()) 640 report("MBB exits via conditional branch/fall-through but the CFG " 641 "successor don't match the actual successor!", MBB); 642 } else if (MBB->succ_size() != 2) { 643 report("MBB exits via conditional branch/fall-through but doesn't have " 644 "exactly two CFG successors!", MBB); 645 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) { 646 report("MBB exits via conditional branch/fall-through but the CFG " 647 "successors don't match the actual successors!", MBB); 648 } 649 if (MBB->empty()) { 650 report("MBB exits via conditional branch/fall-through but doesn't " 651 "contain any instructions!", MBB); 652 } else if (MBB->back().isBarrier()) { 653 report("MBB exits via conditional branch/fall-through but ends with a " 654 "barrier instruction!", MBB); 655 } else if (!MBB->back().isTerminator()) { 656 report("MBB exits via conditional branch/fall-through but the branch " 657 "isn't a terminator instruction!", MBB); 658 } 659 } else if (TBB && FBB) { 660 // Block conditionally branches somewhere, otherwise branches 661 // somewhere else. 662 if (MBB->succ_size() == 1) { 663 // A conditional branch with only one successor is weird, but allowed. 664 if (FBB != TBB) 665 report("MBB exits via conditional branch/branch through but only has " 666 "one CFG successor!", MBB); 667 else if (TBB != *MBB->succ_begin()) 668 report("MBB exits via conditional branch/branch through but the CFG " 669 "successor don't match the actual successor!", MBB); 670 } else if (MBB->succ_size() != 2) { 671 report("MBB exits via conditional branch/branch but doesn't have " 672 "exactly two CFG successors!", MBB); 673 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) { 674 report("MBB exits via conditional branch/branch but the CFG " 675 "successors don't match the actual successors!", MBB); 676 } 677 if (MBB->empty()) { 678 report("MBB exits via conditional branch/branch but doesn't " 679 "contain any instructions!", MBB); 680 } else if (!MBB->back().isBarrier()) { 681 report("MBB exits via conditional branch/branch but doesn't end with a " 682 "barrier instruction!", MBB); 683 } else if (!MBB->back().isTerminator()) { 684 report("MBB exits via conditional branch/branch but the branch " 685 "isn't a terminator instruction!", MBB); 686 } 687 if (Cond.empty()) { 688 report("MBB exits via conditinal branch/branch but there's no " 689 "condition!", MBB); 690 } 691 } else { 692 report("AnalyzeBranch returned invalid data!", MBB); 693 } 694 } 695 696 regsLive.clear(); 697 for (const auto &LI : MBB->liveins()) { 698 if (!TargetRegisterInfo::isPhysicalRegister(LI.PhysReg)) { 699 report("MBB live-in list contains non-physical register", MBB); 700 continue; 701 } 702 for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true); 703 SubRegs.isValid(); ++SubRegs) 704 regsLive.insert(*SubRegs); 705 } 706 regsLiveInButUnused = regsLive; 707 708 const MachineFrameInfo *MFI = MF->getFrameInfo(); 709 assert(MFI && "Function has no frame info"); 710 BitVector PR = MFI->getPristineRegs(*MF); 711 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) { 712 for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true); 713 SubRegs.isValid(); ++SubRegs) 714 regsLive.insert(*SubRegs); 715 } 716 717 regsKilled.clear(); 718 regsDefined.clear(); 719 720 if (Indexes) 721 lastIndex = Indexes->getMBBStartIdx(MBB); 722 } 723 724 // This function gets called for all bundle headers, including normal 725 // stand-alone unbundled instructions. 726 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) { 727 if (Indexes && Indexes->hasIndex(MI)) { 728 SlotIndex idx = Indexes->getInstructionIndex(MI); 729 if (!(idx > lastIndex)) { 730 report("Instruction index out of order", MI); 731 errs() << "Last instruction was at " << lastIndex << '\n'; 732 } 733 lastIndex = idx; 734 } 735 736 // Ensure non-terminators don't follow terminators. 737 // Ignore predicated terminators formed by if conversion. 738 // FIXME: If conversion shouldn't need to violate this rule. 739 if (MI->isTerminator() && !TII->isPredicated(MI)) { 740 if (!FirstTerminator) 741 FirstTerminator = MI; 742 } else if (FirstTerminator) { 743 report("Non-terminator instruction after the first terminator", MI); 744 errs() << "First terminator was:\t" << *FirstTerminator; 745 } 746 } 747 748 // The operands on an INLINEASM instruction must follow a template. 749 // Verify that the flag operands make sense. 750 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) { 751 // The first two operands on INLINEASM are the asm string and global flags. 752 if (MI->getNumOperands() < 2) { 753 report("Too few operands on inline asm", MI); 754 return; 755 } 756 if (!MI->getOperand(0).isSymbol()) 757 report("Asm string must be an external symbol", MI); 758 if (!MI->getOperand(1).isImm()) 759 report("Asm flags must be an immediate", MI); 760 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2, 761 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16. 762 if (!isUInt<5>(MI->getOperand(1).getImm())) 763 report("Unknown asm flags", &MI->getOperand(1), 1); 764 765 static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed"); 766 767 unsigned OpNo = InlineAsm::MIOp_FirstOperand; 768 unsigned NumOps; 769 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) { 770 const MachineOperand &MO = MI->getOperand(OpNo); 771 // There may be implicit ops after the fixed operands. 772 if (!MO.isImm()) 773 break; 774 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm()); 775 } 776 777 if (OpNo > MI->getNumOperands()) 778 report("Missing operands in last group", MI); 779 780 // An optional MDNode follows the groups. 781 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata()) 782 ++OpNo; 783 784 // All trailing operands must be implicit registers. 785 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) { 786 const MachineOperand &MO = MI->getOperand(OpNo); 787 if (!MO.isReg() || !MO.isImplicit()) 788 report("Expected implicit register after groups", &MO, OpNo); 789 } 790 } 791 792 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) { 793 const MCInstrDesc &MCID = MI->getDesc(); 794 if (MI->getNumOperands() < MCID.getNumOperands()) { 795 report("Too few operands", MI); 796 errs() << MCID.getNumOperands() << " operands expected, but " 797 << MI->getNumOperands() << " given.\n"; 798 } 799 800 // Check the tied operands. 801 if (MI->isInlineAsm()) 802 verifyInlineAsm(MI); 803 804 // Check the MachineMemOperands for basic consistency. 805 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(), 806 E = MI->memoperands_end(); I != E; ++I) { 807 if ((*I)->isLoad() && !MI->mayLoad()) 808 report("Missing mayLoad flag", MI); 809 if ((*I)->isStore() && !MI->mayStore()) 810 report("Missing mayStore flag", MI); 811 } 812 813 // Debug values must not have a slot index. 814 // Other instructions must have one, unless they are inside a bundle. 815 if (LiveInts) { 816 bool mapped = !LiveInts->isNotInMIMap(MI); 817 if (MI->isDebugValue()) { 818 if (mapped) 819 report("Debug instruction has a slot index", MI); 820 } else if (MI->isInsideBundle()) { 821 if (mapped) 822 report("Instruction inside bundle has a slot index", MI); 823 } else { 824 if (!mapped) 825 report("Missing slot index", MI); 826 } 827 } 828 829 StringRef ErrorInfo; 830 if (!TII->verifyInstruction(MI, ErrorInfo)) 831 report(ErrorInfo.data(), MI); 832 } 833 834 void 835 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) { 836 const MachineInstr *MI = MO->getParent(); 837 const MCInstrDesc &MCID = MI->getDesc(); 838 unsigned NumDefs = MCID.getNumDefs(); 839 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT) 840 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0; 841 842 // The first MCID.NumDefs operands must be explicit register defines 843 if (MONum < NumDefs) { 844 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 845 if (!MO->isReg()) 846 report("Explicit definition must be a register", MO, MONum); 847 else if (!MO->isDef() && !MCOI.isOptionalDef()) 848 report("Explicit definition marked as use", MO, MONum); 849 else if (MO->isImplicit()) 850 report("Explicit definition marked as implicit", MO, MONum); 851 } else if (MONum < MCID.getNumOperands()) { 852 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 853 // Don't check if it's the last operand in a variadic instruction. See, 854 // e.g., LDM_RET in the arm back end. 855 if (MO->isReg() && 856 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) { 857 if (MO->isDef() && !MCOI.isOptionalDef()) 858 report("Explicit operand marked as def", MO, MONum); 859 if (MO->isImplicit()) 860 report("Explicit operand marked as implicit", MO, MONum); 861 } 862 863 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO); 864 if (TiedTo != -1) { 865 if (!MO->isReg()) 866 report("Tied use must be a register", MO, MONum); 867 else if (!MO->isTied()) 868 report("Operand should be tied", MO, MONum); 869 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum)) 870 report("Tied def doesn't match MCInstrDesc", MO, MONum); 871 } else if (MO->isReg() && MO->isTied()) 872 report("Explicit operand should not be tied", MO, MONum); 873 } else { 874 // ARM adds %reg0 operands to indicate predicates. We'll allow that. 875 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg()) 876 report("Extra explicit operand on non-variadic instruction", MO, MONum); 877 } 878 879 switch (MO->getType()) { 880 case MachineOperand::MO_Register: { 881 const unsigned Reg = MO->getReg(); 882 if (!Reg) 883 return; 884 if (MRI->tracksLiveness() && !MI->isDebugValue()) 885 checkLiveness(MO, MONum); 886 887 // Verify the consistency of tied operands. 888 if (MO->isTied()) { 889 unsigned OtherIdx = MI->findTiedOperandIdx(MONum); 890 const MachineOperand &OtherMO = MI->getOperand(OtherIdx); 891 if (!OtherMO.isReg()) 892 report("Must be tied to a register", MO, MONum); 893 if (!OtherMO.isTied()) 894 report("Missing tie flags on tied operand", MO, MONum); 895 if (MI->findTiedOperandIdx(OtherIdx) != MONum) 896 report("Inconsistent tie links", MO, MONum); 897 if (MONum < MCID.getNumDefs()) { 898 if (OtherIdx < MCID.getNumOperands()) { 899 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO)) 900 report("Explicit def tied to explicit use without tie constraint", 901 MO, MONum); 902 } else { 903 if (!OtherMO.isImplicit()) 904 report("Explicit def should be tied to implicit use", MO, MONum); 905 } 906 } 907 } 908 909 // Verify two-address constraints after leaving SSA form. 910 unsigned DefIdx; 911 if (!MRI->isSSA() && MO->isUse() && 912 MI->isRegTiedToDefOperand(MONum, &DefIdx) && 913 Reg != MI->getOperand(DefIdx).getReg()) 914 report("Two-address instruction operands must be identical", MO, MONum); 915 916 // Check register classes. 917 if (MONum < MCID.getNumOperands() && !MO->isImplicit()) { 918 unsigned SubIdx = MO->getSubReg(); 919 920 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 921 if (SubIdx) { 922 report("Illegal subregister index for physical register", MO, MONum); 923 return; 924 } 925 if (const TargetRegisterClass *DRC = 926 TII->getRegClass(MCID, MONum, TRI, *MF)) { 927 if (!DRC->contains(Reg)) { 928 report("Illegal physical register for instruction", MO, MONum); 929 errs() << TRI->getName(Reg) << " is not a " 930 << TRI->getRegClassName(DRC) << " register.\n"; 931 } 932 } 933 } else { 934 // Virtual register. 935 const TargetRegisterClass *RC = MRI->getRegClass(Reg); 936 if (SubIdx) { 937 const TargetRegisterClass *SRC = 938 TRI->getSubClassWithSubReg(RC, SubIdx); 939 if (!SRC) { 940 report("Invalid subregister index for virtual register", MO, MONum); 941 errs() << "Register class " << TRI->getRegClassName(RC) 942 << " does not support subreg index " << SubIdx << "\n"; 943 return; 944 } 945 if (RC != SRC) { 946 report("Invalid register class for subregister index", MO, MONum); 947 errs() << "Register class " << TRI->getRegClassName(RC) 948 << " does not fully support subreg index " << SubIdx << "\n"; 949 return; 950 } 951 } 952 if (const TargetRegisterClass *DRC = 953 TII->getRegClass(MCID, MONum, TRI, *MF)) { 954 if (SubIdx) { 955 const TargetRegisterClass *SuperRC = 956 TRI->getLargestLegalSuperClass(RC, *MF); 957 if (!SuperRC) { 958 report("No largest legal super class exists.", MO, MONum); 959 return; 960 } 961 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx); 962 if (!DRC) { 963 report("No matching super-reg register class.", MO, MONum); 964 return; 965 } 966 } 967 if (!RC->hasSuperClassEq(DRC)) { 968 report("Illegal virtual register for instruction", MO, MONum); 969 errs() << "Expected a " << TRI->getRegClassName(DRC) 970 << " register, but got a " << TRI->getRegClassName(RC) 971 << " register\n"; 972 } 973 } 974 } 975 } 976 break; 977 } 978 979 case MachineOperand::MO_RegisterMask: 980 regMasks.push_back(MO->getRegMask()); 981 break; 982 983 case MachineOperand::MO_MachineBasicBlock: 984 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent())) 985 report("PHI operand is not in the CFG", MO, MONum); 986 break; 987 988 case MachineOperand::MO_FrameIndex: 989 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) && 990 LiveInts && !LiveInts->isNotInMIMap(MI)) { 991 LiveInterval &LI = LiveStks->getInterval(MO->getIndex()); 992 SlotIndex Idx = LiveInts->getInstructionIndex(MI); 993 if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) { 994 report("Instruction loads from dead spill slot", MO, MONum); 995 errs() << "Live stack: " << LI << '\n'; 996 } 997 if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) { 998 report("Instruction stores to dead spill slot", MO, MONum); 999 errs() << "Live stack: " << LI << '\n'; 1000 } 1001 } 1002 break; 1003 1004 default: 1005 break; 1006 } 1007 } 1008 1009 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) { 1010 const MachineInstr *MI = MO->getParent(); 1011 const unsigned Reg = MO->getReg(); 1012 1013 // Both use and def operands can read a register. 1014 if (MO->readsReg()) { 1015 regsLiveInButUnused.erase(Reg); 1016 1017 if (MO->isKill()) 1018 addRegWithSubRegs(regsKilled, Reg); 1019 1020 // Check that LiveVars knows this kill. 1021 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) && 1022 MO->isKill()) { 1023 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 1024 if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end()) 1025 report("Kill missing from LiveVariables", MO, MONum); 1026 } 1027 1028 // Check LiveInts liveness and kill. 1029 if (LiveInts && !LiveInts->isNotInMIMap(MI)) { 1030 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI); 1031 // Check the cached regunit intervals. 1032 if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) { 1033 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) { 1034 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) { 1035 LiveQueryResult LRQ = LR->Query(UseIdx); 1036 if (!LRQ.valueIn()) { 1037 report("No live segment at use", MO, MONum); 1038 errs() << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI) 1039 << ' ' << *LR << '\n'; 1040 } 1041 if (MO->isKill() && !LRQ.isKill()) { 1042 report("Live range continues after kill flag", MO, MONum); 1043 errs() << PrintRegUnit(*Units, TRI) << ' ' << *LR << '\n'; 1044 } 1045 } 1046 } 1047 } 1048 1049 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1050 if (LiveInts->hasInterval(Reg)) { 1051 // This is a virtual register interval. 1052 const LiveInterval &LI = LiveInts->getInterval(Reg); 1053 LiveQueryResult LRQ = LI.Query(UseIdx); 1054 if (!LRQ.valueIn()) { 1055 report("No live segment at use", MO, MONum); 1056 errs() << UseIdx << " is not live in " << LI << '\n'; 1057 } 1058 // Check for extra kill flags. 1059 // Note that we allow missing kill flags for now. 1060 if (MO->isKill() && !LRQ.isKill()) { 1061 report("Live range continues after kill flag", MO, MONum); 1062 errs() << "Live range: " << LI << '\n'; 1063 } 1064 } else { 1065 report("Virtual register has no live interval", MO, MONum); 1066 } 1067 } 1068 } 1069 1070 // Use of a dead register. 1071 if (!regsLive.count(Reg)) { 1072 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1073 // Reserved registers may be used even when 'dead'. 1074 bool Bad = !isReserved(Reg); 1075 // We are fine if just any subregister has a defined value. 1076 if (Bad) { 1077 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); 1078 ++SubRegs) { 1079 if (regsLive.count(*SubRegs)) { 1080 Bad = false; 1081 break; 1082 } 1083 } 1084 } 1085 // If there is an additional implicit-use of a super register we stop 1086 // here. By definition we are fine if the super register is not 1087 // (completely) dead, if the complete super register is dead we will 1088 // get a report for its operand. 1089 if (Bad) { 1090 for (const MachineOperand &MOP : MI->uses()) { 1091 if (!MOP.isReg()) 1092 continue; 1093 if (!MOP.isImplicit()) 1094 continue; 1095 for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid(); 1096 ++SubRegs) { 1097 if (*SubRegs == Reg) { 1098 Bad = false; 1099 break; 1100 } 1101 } 1102 } 1103 } 1104 if (Bad) 1105 report("Using an undefined physical register", MO, MONum); 1106 } else if (MRI->def_empty(Reg)) { 1107 report("Reading virtual register without a def", MO, MONum); 1108 } else { 1109 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 1110 // We don't know which virtual registers are live in, so only complain 1111 // if vreg was killed in this MBB. Otherwise keep track of vregs that 1112 // must be live in. PHI instructions are handled separately. 1113 if (MInfo.regsKilled.count(Reg)) 1114 report("Using a killed virtual register", MO, MONum); 1115 else if (!MI->isPHI()) 1116 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI)); 1117 } 1118 } 1119 } 1120 1121 if (MO->isDef()) { 1122 // Register defined. 1123 // TODO: verify that earlyclobber ops are not used. 1124 if (MO->isDead()) 1125 addRegWithSubRegs(regsDead, Reg); 1126 else 1127 addRegWithSubRegs(regsDefined, Reg); 1128 1129 // Verify SSA form. 1130 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) && 1131 std::next(MRI->def_begin(Reg)) != MRI->def_end()) 1132 report("Multiple virtual register defs in SSA form", MO, MONum); 1133 1134 // Check LiveInts for a live segment, but only for virtual registers. 1135 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) && 1136 !LiveInts->isNotInMIMap(MI)) { 1137 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI); 1138 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber()); 1139 if (LiveInts->hasInterval(Reg)) { 1140 const LiveInterval &LI = LiveInts->getInterval(Reg); 1141 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) { 1142 assert(VNI && "NULL valno is not allowed"); 1143 if (VNI->def != DefIdx) { 1144 report("Inconsistent valno->def", MO, MONum); 1145 errs() << "Valno " << VNI->id << " is not defined at " 1146 << DefIdx << " in " << LI << '\n'; 1147 } 1148 } else { 1149 report("No live segment at def", MO, MONum); 1150 errs() << DefIdx << " is not live in " << LI << '\n'; 1151 } 1152 // Check that, if the dead def flag is present, LiveInts agree. 1153 if (MO->isDead()) { 1154 LiveQueryResult LRQ = LI.Query(DefIdx); 1155 if (!LRQ.isDeadDef()) { 1156 report("Live range continues after dead def flag", MO, MONum); 1157 errs() << "Live range: " << LI << '\n'; 1158 } 1159 } 1160 } else { 1161 report("Virtual register has no Live interval", MO, MONum); 1162 } 1163 } 1164 } 1165 } 1166 1167 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) { 1168 } 1169 1170 // This function gets called after visiting all instructions in a bundle. The 1171 // argument points to the bundle header. 1172 // Normal stand-alone instructions are also considered 'bundles', and this 1173 // function is called for all of them. 1174 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) { 1175 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 1176 set_union(MInfo.regsKilled, regsKilled); 1177 set_subtract(regsLive, regsKilled); regsKilled.clear(); 1178 // Kill any masked registers. 1179 while (!regMasks.empty()) { 1180 const uint32_t *Mask = regMasks.pop_back_val(); 1181 for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I) 1182 if (TargetRegisterInfo::isPhysicalRegister(*I) && 1183 MachineOperand::clobbersPhysReg(Mask, *I)) 1184 regsDead.push_back(*I); 1185 } 1186 set_subtract(regsLive, regsDead); regsDead.clear(); 1187 set_union(regsLive, regsDefined); regsDefined.clear(); 1188 } 1189 1190 void 1191 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) { 1192 MBBInfoMap[MBB].regsLiveOut = regsLive; 1193 regsLive.clear(); 1194 1195 if (Indexes) { 1196 SlotIndex stop = Indexes->getMBBEndIdx(MBB); 1197 if (!(stop > lastIndex)) { 1198 report("Block ends before last instruction index", MBB); 1199 errs() << "Block ends at " << stop 1200 << " last instruction was at " << lastIndex << '\n'; 1201 } 1202 lastIndex = stop; 1203 } 1204 } 1205 1206 // Calculate the largest possible vregsPassed sets. These are the registers that 1207 // can pass through an MBB live, but may not be live every time. It is assumed 1208 // that all vregsPassed sets are empty before the call. 1209 void MachineVerifier::calcRegsPassed() { 1210 // First push live-out regs to successors' vregsPassed. Remember the MBBs that 1211 // have any vregsPassed. 1212 SmallPtrSet<const MachineBasicBlock*, 8> todo; 1213 for (const auto &MBB : *MF) { 1214 BBInfo &MInfo = MBBInfoMap[&MBB]; 1215 if (!MInfo.reachable) 1216 continue; 1217 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(), 1218 SuE = MBB.succ_end(); SuI != SuE; ++SuI) { 1219 BBInfo &SInfo = MBBInfoMap[*SuI]; 1220 if (SInfo.addPassed(MInfo.regsLiveOut)) 1221 todo.insert(*SuI); 1222 } 1223 } 1224 1225 // Iteratively push vregsPassed to successors. This will converge to the same 1226 // final state regardless of DenseSet iteration order. 1227 while (!todo.empty()) { 1228 const MachineBasicBlock *MBB = *todo.begin(); 1229 todo.erase(MBB); 1230 BBInfo &MInfo = MBBInfoMap[MBB]; 1231 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(), 1232 SuE = MBB->succ_end(); SuI != SuE; ++SuI) { 1233 if (*SuI == MBB) 1234 continue; 1235 BBInfo &SInfo = MBBInfoMap[*SuI]; 1236 if (SInfo.addPassed(MInfo.vregsPassed)) 1237 todo.insert(*SuI); 1238 } 1239 } 1240 } 1241 1242 // Calculate the set of virtual registers that must be passed through each basic 1243 // block in order to satisfy the requirements of successor blocks. This is very 1244 // similar to calcRegsPassed, only backwards. 1245 void MachineVerifier::calcRegsRequired() { 1246 // First push live-in regs to predecessors' vregsRequired. 1247 SmallPtrSet<const MachineBasicBlock*, 8> todo; 1248 for (const auto &MBB : *MF) { 1249 BBInfo &MInfo = MBBInfoMap[&MBB]; 1250 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(), 1251 PrE = MBB.pred_end(); PrI != PrE; ++PrI) { 1252 BBInfo &PInfo = MBBInfoMap[*PrI]; 1253 if (PInfo.addRequired(MInfo.vregsLiveIn)) 1254 todo.insert(*PrI); 1255 } 1256 } 1257 1258 // Iteratively push vregsRequired to predecessors. This will converge to the 1259 // same final state regardless of DenseSet iteration order. 1260 while (!todo.empty()) { 1261 const MachineBasicBlock *MBB = *todo.begin(); 1262 todo.erase(MBB); 1263 BBInfo &MInfo = MBBInfoMap[MBB]; 1264 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(), 1265 PrE = MBB->pred_end(); PrI != PrE; ++PrI) { 1266 if (*PrI == MBB) 1267 continue; 1268 BBInfo &SInfo = MBBInfoMap[*PrI]; 1269 if (SInfo.addRequired(MInfo.vregsRequired)) 1270 todo.insert(*PrI); 1271 } 1272 } 1273 } 1274 1275 // Check PHI instructions at the beginning of MBB. It is assumed that 1276 // calcRegsPassed has been run so BBInfo::isLiveOut is valid. 1277 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) { 1278 SmallPtrSet<const MachineBasicBlock*, 8> seen; 1279 for (const auto &BBI : *MBB) { 1280 if (!BBI.isPHI()) 1281 break; 1282 seen.clear(); 1283 1284 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) { 1285 unsigned Reg = BBI.getOperand(i).getReg(); 1286 const MachineBasicBlock *Pre = BBI.getOperand(i + 1).getMBB(); 1287 if (!Pre->isSuccessor(MBB)) 1288 continue; 1289 seen.insert(Pre); 1290 BBInfo &PrInfo = MBBInfoMap[Pre]; 1291 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg)) 1292 report("PHI operand is not live-out from predecessor", 1293 &BBI.getOperand(i), i); 1294 } 1295 1296 // Did we see all predecessors? 1297 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(), 1298 PrE = MBB->pred_end(); PrI != PrE; ++PrI) { 1299 if (!seen.count(*PrI)) { 1300 report("Missing PHI operand", &BBI); 1301 errs() << "BB#" << (*PrI)->getNumber() 1302 << " is a predecessor according to the CFG.\n"; 1303 } 1304 } 1305 } 1306 } 1307 1308 void MachineVerifier::visitMachineFunctionAfter() { 1309 calcRegsPassed(); 1310 1311 for (const auto &MBB : *MF) { 1312 BBInfo &MInfo = MBBInfoMap[&MBB]; 1313 1314 // Skip unreachable MBBs. 1315 if (!MInfo.reachable) 1316 continue; 1317 1318 checkPHIOps(&MBB); 1319 } 1320 1321 // Now check liveness info if available 1322 calcRegsRequired(); 1323 1324 // Check for killed virtual registers that should be live out. 1325 for (const auto &MBB : *MF) { 1326 BBInfo &MInfo = MBBInfoMap[&MBB]; 1327 for (RegSet::iterator 1328 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E; 1329 ++I) 1330 if (MInfo.regsKilled.count(*I)) { 1331 report("Virtual register killed in block, but needed live out.", &MBB); 1332 errs() << "Virtual register " << PrintReg(*I) 1333 << " is used after the block.\n"; 1334 } 1335 } 1336 1337 if (!MF->empty()) { 1338 BBInfo &MInfo = MBBInfoMap[&MF->front()]; 1339 for (RegSet::iterator 1340 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E; 1341 ++I) 1342 report("Virtual register def doesn't dominate all uses.", 1343 MRI->getVRegDef(*I)); 1344 } 1345 1346 if (LiveVars) 1347 verifyLiveVariables(); 1348 if (LiveInts) 1349 verifyLiveIntervals(); 1350 } 1351 1352 void MachineVerifier::verifyLiveVariables() { 1353 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars"); 1354 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 1355 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 1356 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 1357 for (const auto &MBB : *MF) { 1358 BBInfo &MInfo = MBBInfoMap[&MBB]; 1359 1360 // Our vregsRequired should be identical to LiveVariables' AliveBlocks 1361 if (MInfo.vregsRequired.count(Reg)) { 1362 if (!VI.AliveBlocks.test(MBB.getNumber())) { 1363 report("LiveVariables: Block missing from AliveBlocks", &MBB); 1364 errs() << "Virtual register " << PrintReg(Reg) 1365 << " must be live through the block.\n"; 1366 } 1367 } else { 1368 if (VI.AliveBlocks.test(MBB.getNumber())) { 1369 report("LiveVariables: Block should not be in AliveBlocks", &MBB); 1370 errs() << "Virtual register " << PrintReg(Reg) 1371 << " is not needed live through the block.\n"; 1372 } 1373 } 1374 } 1375 } 1376 } 1377 1378 void MachineVerifier::verifyLiveIntervals() { 1379 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts"); 1380 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 1381 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 1382 1383 // Spilling and splitting may leave unused registers around. Skip them. 1384 if (MRI->reg_nodbg_empty(Reg)) 1385 continue; 1386 1387 if (!LiveInts->hasInterval(Reg)) { 1388 report("Missing live interval for virtual register", MF); 1389 errs() << PrintReg(Reg, TRI) << " still has defs or uses\n"; 1390 continue; 1391 } 1392 1393 const LiveInterval &LI = LiveInts->getInterval(Reg); 1394 assert(Reg == LI.reg && "Invalid reg to interval mapping"); 1395 verifyLiveInterval(LI); 1396 } 1397 1398 // Verify all the cached regunit intervals. 1399 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i) 1400 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i)) 1401 verifyLiveRange(*LR, i); 1402 } 1403 1404 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR, 1405 const VNInfo *VNI, unsigned Reg, 1406 unsigned LaneMask) { 1407 if (VNI->isUnused()) 1408 return; 1409 1410 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def); 1411 1412 if (!DefVNI) { 1413 report("Valno not live at def and not marked unused", MF, LR, Reg, 1414 LaneMask); 1415 errs() << "Valno #" << VNI->id << '\n'; 1416 return; 1417 } 1418 1419 if (DefVNI != VNI) { 1420 report("Live segment at def has different valno", MF, LR, Reg, LaneMask); 1421 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def 1422 << " where valno #" << DefVNI->id << " is live\n"; 1423 return; 1424 } 1425 1426 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def); 1427 if (!MBB) { 1428 report("Invalid definition index", MF, LR, Reg, LaneMask); 1429 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def 1430 << " in " << LR << '\n'; 1431 return; 1432 } 1433 1434 if (VNI->isPHIDef()) { 1435 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) { 1436 report("PHIDef value is not defined at MBB start", MBB, LR, Reg, 1437 LaneMask); 1438 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def 1439 << ", not at the beginning of BB#" << MBB->getNumber() << '\n'; 1440 } 1441 return; 1442 } 1443 1444 // Non-PHI def. 1445 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def); 1446 if (!MI) { 1447 report("No instruction at def index", MBB, LR, Reg, LaneMask); 1448 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n'; 1449 return; 1450 } 1451 1452 if (Reg != 0) { 1453 bool hasDef = false; 1454 bool isEarlyClobber = false; 1455 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) { 1456 if (!MOI->isReg() || !MOI->isDef()) 1457 continue; 1458 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1459 if (MOI->getReg() != Reg) 1460 continue; 1461 } else { 1462 if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) || 1463 !TRI->hasRegUnit(MOI->getReg(), Reg)) 1464 continue; 1465 } 1466 if (LaneMask != 0 && 1467 (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask) == 0) 1468 continue; 1469 hasDef = true; 1470 if (MOI->isEarlyClobber()) 1471 isEarlyClobber = true; 1472 } 1473 1474 if (!hasDef) { 1475 report("Defining instruction does not modify register", MI); 1476 errs() << "Valno #" << VNI->id << " in " << LR << '\n'; 1477 } 1478 1479 // Early clobber defs begin at USE slots, but other defs must begin at 1480 // DEF slots. 1481 if (isEarlyClobber) { 1482 if (!VNI->def.isEarlyClobber()) { 1483 report("Early clobber def must be at an early-clobber slot", MBB, LR, 1484 Reg, LaneMask); 1485 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n'; 1486 } 1487 } else if (!VNI->def.isRegister()) { 1488 report("Non-PHI, non-early clobber def must be at a register slot", 1489 MBB, LR, Reg, LaneMask); 1490 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n'; 1491 } 1492 } 1493 } 1494 1495 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR, 1496 const LiveRange::const_iterator I, 1497 unsigned Reg, unsigned LaneMask) { 1498 const LiveRange::Segment &S = *I; 1499 const VNInfo *VNI = S.valno; 1500 assert(VNI && "Live segment has no valno"); 1501 1502 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) { 1503 report("Foreign valno in live segment", MF, LR, Reg, LaneMask); 1504 errs() << S << " has a bad valno\n"; 1505 } 1506 1507 if (VNI->isUnused()) { 1508 report("Live segment valno is marked unused", MF, LR, Reg, LaneMask); 1509 errs() << S << '\n'; 1510 } 1511 1512 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start); 1513 if (!MBB) { 1514 report("Bad start of live segment, no basic block", MF, LR, Reg, LaneMask); 1515 errs() << S << '\n'; 1516 return; 1517 } 1518 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB); 1519 if (S.start != MBBStartIdx && S.start != VNI->def) { 1520 report("Live segment must begin at MBB entry or valno def", MBB, LR, Reg, 1521 LaneMask); 1522 errs() << S << '\n'; 1523 } 1524 1525 const MachineBasicBlock *EndMBB = 1526 LiveInts->getMBBFromIndex(S.end.getPrevSlot()); 1527 if (!EndMBB) { 1528 report("Bad end of live segment, no basic block", MF, LR, Reg, LaneMask); 1529 errs() << S << '\n'; 1530 return; 1531 } 1532 1533 // No more checks for live-out segments. 1534 if (S.end == LiveInts->getMBBEndIdx(EndMBB)) 1535 return; 1536 1537 // RegUnit intervals are allowed dead phis. 1538 if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() && 1539 S.start == VNI->def && S.end == VNI->def.getDeadSlot()) 1540 return; 1541 1542 // The live segment is ending inside EndMBB 1543 const MachineInstr *MI = 1544 LiveInts->getInstructionFromIndex(S.end.getPrevSlot()); 1545 if (!MI) { 1546 report("Live segment doesn't end at a valid instruction", EndMBB, LR, Reg, 1547 LaneMask); 1548 errs() << S << '\n'; 1549 return; 1550 } 1551 1552 // The block slot must refer to a basic block boundary. 1553 if (S.end.isBlock()) { 1554 report("Live segment ends at B slot of an instruction", EndMBB, LR, Reg, 1555 LaneMask); 1556 errs() << S << '\n'; 1557 } 1558 1559 if (S.end.isDead()) { 1560 // Segment ends on the dead slot. 1561 // That means there must be a dead def. 1562 if (!SlotIndex::isSameInstr(S.start, S.end)) { 1563 report("Live segment ending at dead slot spans instructions", EndMBB, LR, 1564 Reg, LaneMask); 1565 errs() << S << '\n'; 1566 } 1567 } 1568 1569 // A live segment can only end at an early-clobber slot if it is being 1570 // redefined by an early-clobber def. 1571 if (S.end.isEarlyClobber()) { 1572 if (I+1 == LR.end() || (I+1)->start != S.end) { 1573 report("Live segment ending at early clobber slot must be " 1574 "redefined by an EC def in the same instruction", EndMBB, LR, Reg, 1575 LaneMask); 1576 errs() << S << '\n'; 1577 } 1578 } 1579 1580 // The following checks only apply to virtual registers. Physreg liveness 1581 // is too weird to check. 1582 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1583 // A live segment can end with either a redefinition, a kill flag on a 1584 // use, or a dead flag on a def. 1585 bool hasRead = false; 1586 bool hasSubRegDef = false; 1587 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) { 1588 if (!MOI->isReg() || MOI->getReg() != Reg) 1589 continue; 1590 if (LaneMask != 0 && 1591 (LaneMask & TRI->getSubRegIndexLaneMask(MOI->getSubReg())) == 0) 1592 continue; 1593 if (MOI->isDef() && MOI->getSubReg() != 0) 1594 hasSubRegDef = true; 1595 if (MOI->readsReg()) 1596 hasRead = true; 1597 } 1598 if (!S.end.isDead()) { 1599 if (!hasRead) { 1600 // When tracking subregister liveness, the main range must start new 1601 // values on partial register writes, even if there is no read. 1602 if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask != 0 || 1603 !hasSubRegDef) { 1604 report("Instruction ending live segment doesn't read the register", 1605 MI); 1606 errs() << S << " in " << LR << '\n'; 1607 } 1608 } 1609 } 1610 } 1611 1612 // Now check all the basic blocks in this live segment. 1613 MachineFunction::const_iterator MFI = MBB; 1614 // Is this live segment the beginning of a non-PHIDef VN? 1615 if (S.start == VNI->def && !VNI->isPHIDef()) { 1616 // Not live-in to any blocks. 1617 if (MBB == EndMBB) 1618 return; 1619 // Skip this block. 1620 ++MFI; 1621 } 1622 for (;;) { 1623 assert(LiveInts->isLiveInToMBB(LR, MFI)); 1624 // We don't know how to track physregs into a landing pad. 1625 if (!TargetRegisterInfo::isVirtualRegister(Reg) && 1626 MFI->isEHPad()) { 1627 if (&*MFI == EndMBB) 1628 break; 1629 ++MFI; 1630 continue; 1631 } 1632 1633 // Is VNI a PHI-def in the current block? 1634 bool IsPHI = VNI->isPHIDef() && 1635 VNI->def == LiveInts->getMBBStartIdx(MFI); 1636 1637 // Check that VNI is live-out of all predecessors. 1638 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(), 1639 PE = MFI->pred_end(); PI != PE; ++PI) { 1640 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI); 1641 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd); 1642 1643 // All predecessors must have a live-out value. 1644 if (!PVNI) { 1645 report("Register not marked live out of predecessor", *PI, LR, Reg, 1646 LaneMask); 1647 errs() << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber() 1648 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before " 1649 << PEnd << '\n'; 1650 continue; 1651 } 1652 1653 // Only PHI-defs can take different predecessor values. 1654 if (!IsPHI && PVNI != VNI) { 1655 report("Different value live out of predecessor", *PI, LR, Reg, 1656 LaneMask); 1657 errs() << "Valno #" << PVNI->id << " live out of BB#" 1658 << (*PI)->getNumber() << '@' << PEnd 1659 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber() 1660 << '@' << LiveInts->getMBBStartIdx(MFI) << '\n'; 1661 } 1662 } 1663 if (&*MFI == EndMBB) 1664 break; 1665 ++MFI; 1666 } 1667 } 1668 1669 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg, 1670 unsigned LaneMask) { 1671 for (const VNInfo *VNI : LR.valnos) 1672 verifyLiveRangeValue(LR, VNI, Reg, LaneMask); 1673 1674 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I) 1675 verifyLiveRangeSegment(LR, I, Reg, LaneMask); 1676 } 1677 1678 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) { 1679 unsigned Reg = LI.reg; 1680 assert(TargetRegisterInfo::isVirtualRegister(Reg)); 1681 verifyLiveRange(LI, Reg); 1682 1683 unsigned Mask = 0; 1684 unsigned MaxMask = MRI->getMaxLaneMaskForVReg(Reg); 1685 for (const LiveInterval::SubRange &SR : LI.subranges()) { 1686 if ((Mask & SR.LaneMask) != 0) 1687 report("Lane masks of sub ranges overlap in live interval", MF, LI); 1688 if ((SR.LaneMask & ~MaxMask) != 0) 1689 report("Subrange lanemask is invalid", MF, LI); 1690 if (SR.empty()) 1691 report("Subrange must not be empty", MF, SR, LI.reg, SR.LaneMask); 1692 Mask |= SR.LaneMask; 1693 verifyLiveRange(SR, LI.reg, SR.LaneMask); 1694 if (!LI.covers(SR)) 1695 report("A Subrange is not covered by the main range", MF, LI); 1696 } 1697 1698 // Check the LI only has one connected component. 1699 ConnectedVNInfoEqClasses ConEQ(*LiveInts); 1700 unsigned NumComp = ConEQ.Classify(&LI); 1701 if (NumComp > 1) { 1702 report("Multiple connected components in live interval", MF, LI); 1703 for (unsigned comp = 0; comp != NumComp; ++comp) { 1704 errs() << comp << ": valnos"; 1705 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), 1706 E = LI.vni_end(); I!=E; ++I) 1707 if (comp == ConEQ.getEqClass(*I)) 1708 errs() << ' ' << (*I)->id; 1709 errs() << '\n'; 1710 } 1711 } 1712 } 1713 1714 namespace { 1715 // FrameSetup and FrameDestroy can have zero adjustment, so using a single 1716 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the 1717 // value is zero. 1718 // We use a bool plus an integer to capture the stack state. 1719 struct StackStateOfBB { 1720 StackStateOfBB() : EntryValue(0), ExitValue(0), EntryIsSetup(false), 1721 ExitIsSetup(false) { } 1722 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) : 1723 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup), 1724 ExitIsSetup(ExitSetup) { } 1725 // Can be negative, which means we are setting up a frame. 1726 int EntryValue; 1727 int ExitValue; 1728 bool EntryIsSetup; 1729 bool ExitIsSetup; 1730 }; 1731 } 1732 1733 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed 1734 /// by a FrameDestroy <n>, stack adjustments are identical on all 1735 /// CFG edges to a merge point, and frame is destroyed at end of a return block. 1736 void MachineVerifier::verifyStackFrame() { 1737 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode(); 1738 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode(); 1739 1740 SmallVector<StackStateOfBB, 8> SPState; 1741 SPState.resize(MF->getNumBlockIDs()); 1742 SmallPtrSet<const MachineBasicBlock*, 8> Reachable; 1743 1744 // Visit the MBBs in DFS order. 1745 for (df_ext_iterator<const MachineFunction*, 1746 SmallPtrSet<const MachineBasicBlock*, 8> > 1747 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable); 1748 DFI != DFE; ++DFI) { 1749 const MachineBasicBlock *MBB = *DFI; 1750 1751 StackStateOfBB BBState; 1752 // Check the exit state of the DFS stack predecessor. 1753 if (DFI.getPathLength() >= 2) { 1754 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2); 1755 assert(Reachable.count(StackPred) && 1756 "DFS stack predecessor is already visited.\n"); 1757 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue; 1758 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup; 1759 BBState.ExitValue = BBState.EntryValue; 1760 BBState.ExitIsSetup = BBState.EntryIsSetup; 1761 } 1762 1763 // Update stack state by checking contents of MBB. 1764 for (const auto &I : *MBB) { 1765 if (I.getOpcode() == FrameSetupOpcode) { 1766 // The first operand of a FrameOpcode should be i32. 1767 int Size = I.getOperand(0).getImm(); 1768 assert(Size >= 0 && 1769 "Value should be non-negative in FrameSetup and FrameDestroy.\n"); 1770 1771 if (BBState.ExitIsSetup) 1772 report("FrameSetup is after another FrameSetup", &I); 1773 BBState.ExitValue -= Size; 1774 BBState.ExitIsSetup = true; 1775 } 1776 1777 if (I.getOpcode() == FrameDestroyOpcode) { 1778 // The first operand of a FrameOpcode should be i32. 1779 int Size = I.getOperand(0).getImm(); 1780 assert(Size >= 0 && 1781 "Value should be non-negative in FrameSetup and FrameDestroy.\n"); 1782 1783 if (!BBState.ExitIsSetup) 1784 report("FrameDestroy is not after a FrameSetup", &I); 1785 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue : 1786 BBState.ExitValue; 1787 if (BBState.ExitIsSetup && AbsSPAdj != Size) { 1788 report("FrameDestroy <n> is after FrameSetup <m>", &I); 1789 errs() << "FrameDestroy <" << Size << "> is after FrameSetup <" 1790 << AbsSPAdj << ">.\n"; 1791 } 1792 BBState.ExitValue += Size; 1793 BBState.ExitIsSetup = false; 1794 } 1795 } 1796 SPState[MBB->getNumber()] = BBState; 1797 1798 // Make sure the exit state of any predecessor is consistent with the entry 1799 // state. 1800 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(), 1801 E = MBB->pred_end(); I != E; ++I) { 1802 if (Reachable.count(*I) && 1803 (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue || 1804 SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) { 1805 report("The exit stack state of a predecessor is inconsistent.", MBB); 1806 errs() << "Predecessor BB#" << (*I)->getNumber() << " has exit state (" 1807 << SPState[(*I)->getNumber()].ExitValue << ", " 1808 << SPState[(*I)->getNumber()].ExitIsSetup 1809 << "), while BB#" << MBB->getNumber() << " has entry state (" 1810 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n"; 1811 } 1812 } 1813 1814 // Make sure the entry state of any successor is consistent with the exit 1815 // state. 1816 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(), 1817 E = MBB->succ_end(); I != E; ++I) { 1818 if (Reachable.count(*I) && 1819 (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue || 1820 SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) { 1821 report("The entry stack state of a successor is inconsistent.", MBB); 1822 errs() << "Successor BB#" << (*I)->getNumber() << " has entry state (" 1823 << SPState[(*I)->getNumber()].EntryValue << ", " 1824 << SPState[(*I)->getNumber()].EntryIsSetup 1825 << "), while BB#" << MBB->getNumber() << " has exit state (" 1826 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n"; 1827 } 1828 } 1829 1830 // Make sure a basic block with return ends with zero stack adjustment. 1831 if (!MBB->empty() && MBB->back().isReturn()) { 1832 if (BBState.ExitIsSetup) 1833 report("A return block ends with a FrameSetup.", MBB); 1834 if (BBState.ExitValue) 1835 report("A return block ends with a nonzero stack adjustment.", MBB); 1836 } 1837 } 1838 } 1839