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