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