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