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