1 //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Pass to verify generated machine code. The following is checked: 10 // 11 // Operand counts: All explicit operands must be present. 12 // 13 // Register classes: All physical and virtual register operands must be 14 // compatible with the register class required by the instruction descriptor. 15 // 16 // Register live intervals: Registers must be defined only once, and must be 17 // defined before use. 18 // 19 // The machine code verifier is enabled with the command-line option 20 // -verify-machineinstrs. 21 //===----------------------------------------------------------------------===// 22 23 #include "llvm/ADT/BitVector.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/DenseSet.h" 26 #include "llvm/ADT/DepthFirstIterator.h" 27 #include "llvm/ADT/PostOrderIterator.h" 28 #include "llvm/ADT/STLExtras.h" 29 #include "llvm/ADT/SetOperations.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallVector.h" 32 #include "llvm/ADT/StringRef.h" 33 #include "llvm/ADT/Twine.h" 34 #include "llvm/Analysis/EHPersonalities.h" 35 #include "llvm/CodeGen/GlobalISel/RegisterBank.h" 36 #include "llvm/CodeGen/LiveInterval.h" 37 #include "llvm/CodeGen/LiveIntervalCalc.h" 38 #include "llvm/CodeGen/LiveIntervals.h" 39 #include "llvm/CodeGen/LiveStacks.h" 40 #include "llvm/CodeGen/LiveVariables.h" 41 #include "llvm/CodeGen/MachineBasicBlock.h" 42 #include "llvm/CodeGen/MachineFrameInfo.h" 43 #include "llvm/CodeGen/MachineFunction.h" 44 #include "llvm/CodeGen/MachineFunctionPass.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBundle.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/PseudoSourceValue.h" 51 #include "llvm/CodeGen/SlotIndexes.h" 52 #include "llvm/CodeGen/StackMaps.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetOpcodes.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/TargetSubtargetInfo.h" 57 #include "llvm/IR/BasicBlock.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/InlineAsm.h" 60 #include "llvm/IR/Instructions.h" 61 #include "llvm/InitializePasses.h" 62 #include "llvm/MC/LaneBitmask.h" 63 #include "llvm/MC/MCAsmInfo.h" 64 #include "llvm/MC/MCInstrDesc.h" 65 #include "llvm/MC/MCRegisterInfo.h" 66 #include "llvm/MC/MCTargetOptions.h" 67 #include "llvm/Pass.h" 68 #include "llvm/Support/Casting.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/LowLevelTypeImpl.h" 71 #include "llvm/Support/MathExtras.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include "llvm/Target/TargetMachine.h" 74 #include <algorithm> 75 #include <cassert> 76 #include <cstddef> 77 #include <cstdint> 78 #include <iterator> 79 #include <string> 80 #include <utility> 81 82 using namespace llvm; 83 84 namespace { 85 86 struct MachineVerifier { 87 MachineVerifier(Pass *pass, const char *b) : PASS(pass), Banner(b) {} 88 89 unsigned verify(const MachineFunction &MF); 90 91 Pass *const PASS; 92 const char *Banner; 93 const MachineFunction *MF; 94 const TargetMachine *TM; 95 const TargetInstrInfo *TII; 96 const TargetRegisterInfo *TRI; 97 const MachineRegisterInfo *MRI; 98 99 unsigned foundErrors; 100 101 // Avoid querying the MachineFunctionProperties for each operand. 102 bool isFunctionRegBankSelected; 103 bool isFunctionSelected; 104 105 using RegVector = SmallVector<unsigned, 16>; 106 using RegMaskVector = SmallVector<const uint32_t *, 4>; 107 using RegSet = DenseSet<unsigned>; 108 using RegMap = DenseMap<unsigned, const MachineInstr *>; 109 using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>; 110 111 const MachineInstr *FirstNonPHI; 112 const MachineInstr *FirstTerminator; 113 BlockSet FunctionBlocks; 114 115 BitVector regsReserved; 116 RegSet regsLive; 117 RegVector regsDefined, regsDead, regsKilled; 118 RegMaskVector regMasks; 119 120 SlotIndex lastIndex; 121 122 // Add Reg and any sub-registers to RV 123 void addRegWithSubRegs(RegVector &RV, unsigned Reg) { 124 RV.push_back(Reg); 125 if (Register::isPhysicalRegister(Reg)) 126 for (const MCPhysReg &SubReg : TRI->subregs(Reg)) 127 RV.push_back(SubReg); 128 } 129 130 struct BBInfo { 131 // Is this MBB reachable from the MF entry point? 132 bool reachable = false; 133 134 // Vregs that must be live in because they are used without being 135 // defined. Map value is the user. vregsLiveIn doesn't include regs 136 // that only are used by PHI nodes. 137 RegMap vregsLiveIn; 138 139 // Regs killed in MBB. They may be defined again, and will then be in both 140 // regsKilled and regsLiveOut. 141 RegSet regsKilled; 142 143 // Regs defined in MBB and live out. Note that vregs passing through may 144 // be live out without being mentioned here. 145 RegSet regsLiveOut; 146 147 // Vregs that pass through MBB untouched. This set is disjoint from 148 // regsKilled and regsLiveOut. 149 RegSet vregsPassed; 150 151 // Vregs that must pass through MBB because they are needed by a successor 152 // block. This set is disjoint from regsLiveOut. 153 RegSet vregsRequired; 154 155 // Set versions of block's predecessor and successor lists. 156 BlockSet Preds, Succs; 157 158 BBInfo() = default; 159 160 // Add register to vregsRequired if it belongs there. Return true if 161 // anything changed. 162 bool addRequired(unsigned Reg) { 163 if (!Register::isVirtualRegister(Reg)) 164 return false; 165 if (regsLiveOut.count(Reg)) 166 return false; 167 return vregsRequired.insert(Reg).second; 168 } 169 170 // Same for a full set. 171 bool addRequired(const RegSet &RS) { 172 bool Changed = false; 173 for (unsigned Reg : RS) 174 Changed |= addRequired(Reg); 175 return Changed; 176 } 177 178 // Same for a full map. 179 bool addRequired(const RegMap &RM) { 180 bool Changed = false; 181 for (const auto &I : RM) 182 Changed |= addRequired(I.first); 183 return Changed; 184 } 185 186 // Live-out registers are either in regsLiveOut or vregsPassed. 187 bool isLiveOut(unsigned Reg) const { 188 return regsLiveOut.count(Reg) || vregsPassed.count(Reg); 189 } 190 }; 191 192 // Extra register info per MBB. 193 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap; 194 195 bool isReserved(unsigned Reg) { 196 return Reg < regsReserved.size() && regsReserved.test(Reg); 197 } 198 199 bool isAllocatable(unsigned Reg) const { 200 return Reg < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) && 201 !regsReserved.test(Reg); 202 } 203 204 // Analysis information if available 205 LiveVariables *LiveVars; 206 LiveIntervals *LiveInts; 207 LiveStacks *LiveStks; 208 SlotIndexes *Indexes; 209 210 void visitMachineFunctionBefore(); 211 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB); 212 void visitMachineBundleBefore(const MachineInstr *MI); 213 214 bool verifyVectorElementMatch(LLT Ty0, LLT Ty1, const MachineInstr *MI); 215 void verifyPreISelGenericInstruction(const MachineInstr *MI); 216 void visitMachineInstrBefore(const MachineInstr *MI); 217 void visitMachineOperand(const MachineOperand *MO, unsigned MONum); 218 void visitMachineBundleAfter(const MachineInstr *MI); 219 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB); 220 void visitMachineFunctionAfter(); 221 222 void report(const char *msg, const MachineFunction *MF); 223 void report(const char *msg, const MachineBasicBlock *MBB); 224 void report(const char *msg, const MachineInstr *MI); 225 void report(const char *msg, const MachineOperand *MO, unsigned MONum, 226 LLT MOVRegType = LLT{}); 227 228 void report_context(const LiveInterval &LI) const; 229 void report_context(const LiveRange &LR, unsigned VRegUnit, 230 LaneBitmask LaneMask) const; 231 void report_context(const LiveRange::Segment &S) const; 232 void report_context(const VNInfo &VNI) const; 233 void report_context(SlotIndex Pos) const; 234 void report_context(MCPhysReg PhysReg) const; 235 void report_context_liverange(const LiveRange &LR) const; 236 void report_context_lanemask(LaneBitmask LaneMask) const; 237 void report_context_vreg(unsigned VReg) const; 238 void report_context_vreg_regunit(unsigned VRegOrUnit) const; 239 240 void verifyInlineAsm(const MachineInstr *MI); 241 242 void checkLiveness(const MachineOperand *MO, unsigned MONum); 243 void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum, 244 SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit, 245 LaneBitmask LaneMask = LaneBitmask::getNone()); 246 void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum, 247 SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit, 248 bool SubRangeCheck = false, 249 LaneBitmask LaneMask = LaneBitmask::getNone()); 250 251 void markReachable(const MachineBasicBlock *MBB); 252 void calcRegsPassed(); 253 void checkPHIOps(const MachineBasicBlock &MBB); 254 255 void calcRegsRequired(); 256 void verifyLiveVariables(); 257 void verifyLiveIntervals(); 258 void verifyLiveInterval(const LiveInterval&); 259 void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned, 260 LaneBitmask); 261 void verifyLiveRangeSegment(const LiveRange&, 262 const LiveRange::const_iterator I, unsigned, 263 LaneBitmask); 264 void verifyLiveRange(const LiveRange&, unsigned, 265 LaneBitmask LaneMask = LaneBitmask::getNone()); 266 267 void verifyStackFrame(); 268 269 void verifySlotIndexes() const; 270 void verifyProperties(const MachineFunction &MF); 271 }; 272 273 struct MachineVerifierPass : public MachineFunctionPass { 274 static char ID; // Pass ID, replacement for typeid 275 276 const std::string Banner; 277 278 MachineVerifierPass(std::string banner = std::string()) 279 : MachineFunctionPass(ID), Banner(std::move(banner)) { 280 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry()); 281 } 282 283 void getAnalysisUsage(AnalysisUsage &AU) const override { 284 AU.setPreservesAll(); 285 MachineFunctionPass::getAnalysisUsage(AU); 286 } 287 288 bool runOnMachineFunction(MachineFunction &MF) override { 289 unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF); 290 if (FoundErrors) 291 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors."); 292 return false; 293 } 294 }; 295 296 } // end anonymous namespace 297 298 char MachineVerifierPass::ID = 0; 299 300 INITIALIZE_PASS(MachineVerifierPass, "machineverifier", 301 "Verify generated machine code", false, false) 302 303 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) { 304 return new MachineVerifierPass(Banner); 305 } 306 307 bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors) 308 const { 309 MachineFunction &MF = const_cast<MachineFunction&>(*this); 310 unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF); 311 if (AbortOnErrors && FoundErrors) 312 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors."); 313 return FoundErrors == 0; 314 } 315 316 void MachineVerifier::verifySlotIndexes() const { 317 if (Indexes == nullptr) 318 return; 319 320 // Ensure the IdxMBB list is sorted by slot indexes. 321 SlotIndex Last; 322 for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(), 323 E = Indexes->MBBIndexEnd(); I != E; ++I) { 324 assert(!Last.isValid() || I->first > Last); 325 Last = I->first; 326 } 327 } 328 329 void MachineVerifier::verifyProperties(const MachineFunction &MF) { 330 // If a pass has introduced virtual registers without clearing the 331 // NoVRegs property (or set it without allocating the vregs) 332 // then report an error. 333 if (MF.getProperties().hasProperty( 334 MachineFunctionProperties::Property::NoVRegs) && 335 MRI->getNumVirtRegs()) 336 report("Function has NoVRegs property but there are VReg operands", &MF); 337 } 338 339 unsigned MachineVerifier::verify(const MachineFunction &MF) { 340 foundErrors = 0; 341 342 this->MF = &MF; 343 TM = &MF.getTarget(); 344 TII = MF.getSubtarget().getInstrInfo(); 345 TRI = MF.getSubtarget().getRegisterInfo(); 346 MRI = &MF.getRegInfo(); 347 348 const bool isFunctionFailedISel = MF.getProperties().hasProperty( 349 MachineFunctionProperties::Property::FailedISel); 350 351 // If we're mid-GlobalISel and we already triggered the fallback path then 352 // it's expected that the MIR is somewhat broken but that's ok since we'll 353 // reset it and clear the FailedISel attribute in ResetMachineFunctions. 354 if (isFunctionFailedISel) 355 return foundErrors; 356 357 isFunctionRegBankSelected = MF.getProperties().hasProperty( 358 MachineFunctionProperties::Property::RegBankSelected); 359 isFunctionSelected = MF.getProperties().hasProperty( 360 MachineFunctionProperties::Property::Selected); 361 362 LiveVars = nullptr; 363 LiveInts = nullptr; 364 LiveStks = nullptr; 365 Indexes = nullptr; 366 if (PASS) { 367 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>(); 368 // We don't want to verify LiveVariables if LiveIntervals is available. 369 if (!LiveInts) 370 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>(); 371 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>(); 372 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>(); 373 } 374 375 verifySlotIndexes(); 376 377 verifyProperties(MF); 378 379 visitMachineFunctionBefore(); 380 for (const MachineBasicBlock &MBB : MF) { 381 visitMachineBasicBlockBefore(&MBB); 382 // Keep track of the current bundle header. 383 const MachineInstr *CurBundle = nullptr; 384 // Do we expect the next instruction to be part of the same bundle? 385 bool InBundle = false; 386 387 for (const MachineInstr &MI : MBB.instrs()) { 388 if (MI.getParent() != &MBB) { 389 report("Bad instruction parent pointer", &MBB); 390 errs() << "Instruction: " << MI; 391 continue; 392 } 393 394 // Check for consistent bundle flags. 395 if (InBundle && !MI.isBundledWithPred()) 396 report("Missing BundledPred flag, " 397 "BundledSucc was set on predecessor", 398 &MI); 399 if (!InBundle && MI.isBundledWithPred()) 400 report("BundledPred flag is set, " 401 "but BundledSucc not set on predecessor", 402 &MI); 403 404 // Is this a bundle header? 405 if (!MI.isInsideBundle()) { 406 if (CurBundle) 407 visitMachineBundleAfter(CurBundle); 408 CurBundle = &MI; 409 visitMachineBundleBefore(CurBundle); 410 } else if (!CurBundle) 411 report("No bundle header", &MI); 412 visitMachineInstrBefore(&MI); 413 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { 414 const MachineOperand &Op = MI.getOperand(I); 415 if (Op.getParent() != &MI) { 416 // Make sure to use correct addOperand / RemoveOperand / ChangeTo 417 // functions when replacing operands of a MachineInstr. 418 report("Instruction has operand with wrong parent set", &MI); 419 } 420 421 visitMachineOperand(&Op, I); 422 } 423 424 // Was this the last bundled instruction? 425 InBundle = MI.isBundledWithSucc(); 426 } 427 if (CurBundle) 428 visitMachineBundleAfter(CurBundle); 429 if (InBundle) 430 report("BundledSucc flag set on last instruction in block", &MBB.back()); 431 visitMachineBasicBlockAfter(&MBB); 432 } 433 visitMachineFunctionAfter(); 434 435 // Clean up. 436 regsLive.clear(); 437 regsDefined.clear(); 438 regsDead.clear(); 439 regsKilled.clear(); 440 regMasks.clear(); 441 MBBInfoMap.clear(); 442 443 return foundErrors; 444 } 445 446 void MachineVerifier::report(const char *msg, const MachineFunction *MF) { 447 assert(MF); 448 errs() << '\n'; 449 if (!foundErrors++) { 450 if (Banner) 451 errs() << "# " << Banner << '\n'; 452 if (LiveInts != nullptr) 453 LiveInts->print(errs()); 454 else 455 MF->print(errs(), Indexes); 456 } 457 errs() << "*** Bad machine code: " << msg << " ***\n" 458 << "- function: " << MF->getName() << "\n"; 459 } 460 461 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) { 462 assert(MBB); 463 report(msg, MBB->getParent()); 464 errs() << "- basic block: " << printMBBReference(*MBB) << ' ' 465 << MBB->getName() << " (" << (const void *)MBB << ')'; 466 if (Indexes) 467 errs() << " [" << Indexes->getMBBStartIdx(MBB) 468 << ';' << Indexes->getMBBEndIdx(MBB) << ')'; 469 errs() << '\n'; 470 } 471 472 void MachineVerifier::report(const char *msg, const MachineInstr *MI) { 473 assert(MI); 474 report(msg, MI->getParent()); 475 errs() << "- instruction: "; 476 if (Indexes && Indexes->hasIndex(*MI)) 477 errs() << Indexes->getInstructionIndex(*MI) << '\t'; 478 MI->print(errs(), /*SkipOpers=*/true); 479 } 480 481 void MachineVerifier::report(const char *msg, const MachineOperand *MO, 482 unsigned MONum, LLT MOVRegType) { 483 assert(MO); 484 report(msg, MO->getParent()); 485 errs() << "- operand " << MONum << ": "; 486 MO->print(errs(), MOVRegType, TRI); 487 errs() << "\n"; 488 } 489 490 void MachineVerifier::report_context(SlotIndex Pos) const { 491 errs() << "- at: " << Pos << '\n'; 492 } 493 494 void MachineVerifier::report_context(const LiveInterval &LI) const { 495 errs() << "- interval: " << LI << '\n'; 496 } 497 498 void MachineVerifier::report_context(const LiveRange &LR, unsigned VRegUnit, 499 LaneBitmask LaneMask) const { 500 report_context_liverange(LR); 501 report_context_vreg_regunit(VRegUnit); 502 if (LaneMask.any()) 503 report_context_lanemask(LaneMask); 504 } 505 506 void MachineVerifier::report_context(const LiveRange::Segment &S) const { 507 errs() << "- segment: " << S << '\n'; 508 } 509 510 void MachineVerifier::report_context(const VNInfo &VNI) const { 511 errs() << "- ValNo: " << VNI.id << " (def " << VNI.def << ")\n"; 512 } 513 514 void MachineVerifier::report_context_liverange(const LiveRange &LR) const { 515 errs() << "- liverange: " << LR << '\n'; 516 } 517 518 void MachineVerifier::report_context(MCPhysReg PReg) const { 519 errs() << "- p. register: " << printReg(PReg, TRI) << '\n'; 520 } 521 522 void MachineVerifier::report_context_vreg(unsigned VReg) const { 523 errs() << "- v. register: " << printReg(VReg, TRI) << '\n'; 524 } 525 526 void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit) const { 527 if (Register::isVirtualRegister(VRegOrUnit)) { 528 report_context_vreg(VRegOrUnit); 529 } else { 530 errs() << "- regunit: " << printRegUnit(VRegOrUnit, TRI) << '\n'; 531 } 532 } 533 534 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const { 535 errs() << "- lanemask: " << PrintLaneMask(LaneMask) << '\n'; 536 } 537 538 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) { 539 BBInfo &MInfo = MBBInfoMap[MBB]; 540 if (!MInfo.reachable) { 541 MInfo.reachable = true; 542 for (const MachineBasicBlock *Succ : MBB->successors()) 543 markReachable(Succ); 544 } 545 } 546 547 void MachineVerifier::visitMachineFunctionBefore() { 548 lastIndex = SlotIndex(); 549 regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs() 550 : TRI->getReservedRegs(*MF); 551 552 if (!MF->empty()) 553 markReachable(&MF->front()); 554 555 // Build a set of the basic blocks in the function. 556 FunctionBlocks.clear(); 557 for (const auto &MBB : *MF) { 558 FunctionBlocks.insert(&MBB); 559 BBInfo &MInfo = MBBInfoMap[&MBB]; 560 561 MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end()); 562 if (MInfo.Preds.size() != MBB.pred_size()) 563 report("MBB has duplicate entries in its predecessor list.", &MBB); 564 565 MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end()); 566 if (MInfo.Succs.size() != MBB.succ_size()) 567 report("MBB has duplicate entries in its successor list.", &MBB); 568 } 569 570 // Check that the register use lists are sane. 571 MRI->verifyUseLists(); 572 573 if (!MF->empty()) 574 verifyStackFrame(); 575 } 576 577 void 578 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) { 579 FirstTerminator = nullptr; 580 FirstNonPHI = nullptr; 581 582 if (!MF->getProperties().hasProperty( 583 MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) { 584 // If this block has allocatable physical registers live-in, check that 585 // it is an entry block or landing pad. 586 for (const auto &LI : MBB->liveins()) { 587 if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() && 588 MBB->getIterator() != MBB->getParent()->begin()) { 589 report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB); 590 report_context(LI.PhysReg); 591 } 592 } 593 } 594 595 // Count the number of landing pad successors. 596 SmallPtrSet<const MachineBasicBlock*, 4> LandingPadSuccs; 597 for (const auto *succ : MBB->successors()) { 598 if (succ->isEHPad()) 599 LandingPadSuccs.insert(succ); 600 if (!FunctionBlocks.count(succ)) 601 report("MBB has successor that isn't part of the function.", MBB); 602 if (!MBBInfoMap[succ].Preds.count(MBB)) { 603 report("Inconsistent CFG", MBB); 604 errs() << "MBB is not in the predecessor list of the successor " 605 << printMBBReference(*succ) << ".\n"; 606 } 607 } 608 609 // Check the predecessor list. 610 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 611 if (!FunctionBlocks.count(Pred)) 612 report("MBB has predecessor that isn't part of the function.", MBB); 613 if (!MBBInfoMap[Pred].Succs.count(MBB)) { 614 report("Inconsistent CFG", MBB); 615 errs() << "MBB is not in the successor list of the predecessor " 616 << printMBBReference(*Pred) << ".\n"; 617 } 618 } 619 620 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo(); 621 const BasicBlock *BB = MBB->getBasicBlock(); 622 const Function &F = MF->getFunction(); 623 if (LandingPadSuccs.size() > 1 && 624 !(AsmInfo && 625 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj && 626 BB && isa<SwitchInst>(BB->getTerminator())) && 627 !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) 628 report("MBB has more than one landing pad successor", MBB); 629 630 // Call analyzeBranch. If it succeeds, there several more conditions to check. 631 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 632 SmallVector<MachineOperand, 4> Cond; 633 if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB, 634 Cond)) { 635 // Ok, analyzeBranch thinks it knows what's going on with this block. Let's 636 // check whether its answers match up with reality. 637 if (!TBB && !FBB) { 638 // Block falls through to its successor. 639 if (!MBB->empty() && MBB->back().isBarrier() && 640 !TII->isPredicated(MBB->back())) { 641 report("MBB exits via unconditional fall-through but ends with a " 642 "barrier instruction!", MBB); 643 } 644 if (!Cond.empty()) { 645 report("MBB exits via unconditional fall-through but has a condition!", 646 MBB); 647 } 648 } else if (TBB && !FBB && Cond.empty()) { 649 // Block unconditionally branches somewhere. 650 if (MBB->empty()) { 651 report("MBB exits via unconditional branch but doesn't contain " 652 "any instructions!", MBB); 653 } else if (!MBB->back().isBarrier()) { 654 report("MBB exits via unconditional branch but doesn't end with a " 655 "barrier instruction!", MBB); 656 } else if (!MBB->back().isTerminator()) { 657 report("MBB exits via unconditional branch but the branch isn't a " 658 "terminator instruction!", MBB); 659 } 660 } else if (TBB && !FBB && !Cond.empty()) { 661 // Block conditionally branches somewhere, otherwise falls through. 662 if (MBB->empty()) { 663 report("MBB exits via conditional branch/fall-through but doesn't " 664 "contain any instructions!", MBB); 665 } else if (MBB->back().isBarrier()) { 666 report("MBB exits via conditional branch/fall-through but ends with a " 667 "barrier instruction!", MBB); 668 } else if (!MBB->back().isTerminator()) { 669 report("MBB exits via conditional branch/fall-through but the branch " 670 "isn't a terminator instruction!", MBB); 671 } 672 } else if (TBB && FBB) { 673 // Block conditionally branches somewhere, otherwise branches 674 // somewhere else. 675 if (MBB->empty()) { 676 report("MBB exits via conditional branch/branch but doesn't " 677 "contain any instructions!", MBB); 678 } else if (!MBB->back().isBarrier()) { 679 report("MBB exits via conditional branch/branch but doesn't end with a " 680 "barrier instruction!", MBB); 681 } else if (!MBB->back().isTerminator()) { 682 report("MBB exits via conditional branch/branch but the branch " 683 "isn't a terminator instruction!", MBB); 684 } 685 if (Cond.empty()) { 686 report("MBB exits via conditional branch/branch but there's no " 687 "condition!", MBB); 688 } 689 } else { 690 report("analyzeBranch returned invalid data!", MBB); 691 } 692 693 // Now check that the successors match up with the answers reported by 694 // analyzeBranch. 695 if (TBB && !MBB->isSuccessor(TBB)) 696 report("MBB exits via jump or conditional branch, but its target isn't a " 697 "CFG successor!", 698 MBB); 699 if (FBB && !MBB->isSuccessor(FBB)) 700 report("MBB exits via conditional branch, but its target isn't a CFG " 701 "successor!", 702 MBB); 703 704 // There might be a fallthrough to the next block if there's either no 705 // unconditional true branch, or if there's a condition, and one of the 706 // branches is missing. 707 bool Fallthrough = !TBB || (!Cond.empty() && !FBB); 708 709 // A conditional fallthrough must be an actual CFG successor, not 710 // unreachable. (Conversely, an unconditional fallthrough might not really 711 // be a successor, because the block might end in unreachable.) 712 if (!Cond.empty() && !FBB) { 713 MachineFunction::const_iterator MBBI = std::next(MBB->getIterator()); 714 if (MBBI == MF->end()) { 715 report("MBB conditionally falls through out of function!", MBB); 716 } else if (!MBB->isSuccessor(&*MBBI)) 717 report("MBB exits via conditional branch/fall-through but the CFG " 718 "successors don't match the actual successors!", 719 MBB); 720 } 721 722 // Verify that there aren't any extra un-accounted-for successors. 723 for (const MachineBasicBlock *SuccMBB : MBB->successors()) { 724 // If this successor is one of the branch targets, it's okay. 725 if (SuccMBB == TBB || SuccMBB == FBB) 726 continue; 727 // If we might have a fallthrough, and the successor is the fallthrough 728 // block, that's also ok. 729 if (Fallthrough && SuccMBB == MBB->getNextNode()) 730 continue; 731 // Also accept successors which are for exception-handling or might be 732 // inlineasm_br targets. 733 if (SuccMBB->isEHPad() || SuccMBB->isInlineAsmBrIndirectTarget()) 734 continue; 735 report("MBB has unexpected successors which are not branch targets, " 736 "fallthrough, EHPads, or inlineasm_br targets.", 737 MBB); 738 } 739 } 740 741 regsLive.clear(); 742 if (MRI->tracksLiveness()) { 743 for (const auto &LI : MBB->liveins()) { 744 if (!Register::isPhysicalRegister(LI.PhysReg)) { 745 report("MBB live-in list contains non-physical register", MBB); 746 continue; 747 } 748 for (const MCPhysReg &SubReg : TRI->subregs_inclusive(LI.PhysReg)) 749 regsLive.insert(SubReg); 750 } 751 } 752 753 const MachineFrameInfo &MFI = MF->getFrameInfo(); 754 BitVector PR = MFI.getPristineRegs(*MF); 755 for (unsigned I : PR.set_bits()) { 756 for (const MCPhysReg &SubReg : TRI->subregs_inclusive(I)) 757 regsLive.insert(SubReg); 758 } 759 760 regsKilled.clear(); 761 regsDefined.clear(); 762 763 if (Indexes) 764 lastIndex = Indexes->getMBBStartIdx(MBB); 765 } 766 767 // This function gets called for all bundle headers, including normal 768 // stand-alone unbundled instructions. 769 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) { 770 if (Indexes && Indexes->hasIndex(*MI)) { 771 SlotIndex idx = Indexes->getInstructionIndex(*MI); 772 if (!(idx > lastIndex)) { 773 report("Instruction index out of order", MI); 774 errs() << "Last instruction was at " << lastIndex << '\n'; 775 } 776 lastIndex = idx; 777 } 778 779 // Ensure non-terminators don't follow terminators. 780 // Ignore predicated terminators formed by if conversion. 781 // FIXME: If conversion shouldn't need to violate this rule. 782 if (MI->isTerminator() && !TII->isPredicated(*MI)) { 783 if (!FirstTerminator) 784 FirstTerminator = MI; 785 } else if (FirstTerminator) { 786 report("Non-terminator instruction after the first terminator", MI); 787 errs() << "First terminator was:\t" << *FirstTerminator; 788 } 789 } 790 791 // The operands on an INLINEASM instruction must follow a template. 792 // Verify that the flag operands make sense. 793 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) { 794 // The first two operands on INLINEASM are the asm string and global flags. 795 if (MI->getNumOperands() < 2) { 796 report("Too few operands on inline asm", MI); 797 return; 798 } 799 if (!MI->getOperand(0).isSymbol()) 800 report("Asm string must be an external symbol", MI); 801 if (!MI->getOperand(1).isImm()) 802 report("Asm flags must be an immediate", MI); 803 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2, 804 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16, 805 // and Extra_IsConvergent = 32. 806 if (!isUInt<6>(MI->getOperand(1).getImm())) 807 report("Unknown asm flags", &MI->getOperand(1), 1); 808 809 static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed"); 810 811 unsigned OpNo = InlineAsm::MIOp_FirstOperand; 812 unsigned NumOps; 813 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) { 814 const MachineOperand &MO = MI->getOperand(OpNo); 815 // There may be implicit ops after the fixed operands. 816 if (!MO.isImm()) 817 break; 818 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm()); 819 } 820 821 if (OpNo > MI->getNumOperands()) 822 report("Missing operands in last group", MI); 823 824 // An optional MDNode follows the groups. 825 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata()) 826 ++OpNo; 827 828 // All trailing operands must be implicit registers. 829 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) { 830 const MachineOperand &MO = MI->getOperand(OpNo); 831 if (!MO.isReg() || !MO.isImplicit()) 832 report("Expected implicit register after groups", &MO, OpNo); 833 } 834 } 835 836 /// Check that types are consistent when two operands need to have the same 837 /// number of vector elements. 838 /// \return true if the types are valid. 839 bool MachineVerifier::verifyVectorElementMatch(LLT Ty0, LLT Ty1, 840 const MachineInstr *MI) { 841 if (Ty0.isVector() != Ty1.isVector()) { 842 report("operand types must be all-vector or all-scalar", MI); 843 // Generally we try to report as many issues as possible at once, but in 844 // this case it's not clear what should we be comparing the size of the 845 // scalar with: the size of the whole vector or its lane. Instead of 846 // making an arbitrary choice and emitting not so helpful message, let's 847 // avoid the extra noise and stop here. 848 return false; 849 } 850 851 if (Ty0.isVector() && Ty0.getNumElements() != Ty1.getNumElements()) { 852 report("operand types must preserve number of vector elements", MI); 853 return false; 854 } 855 856 return true; 857 } 858 859 void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr *MI) { 860 if (isFunctionSelected) 861 report("Unexpected generic instruction in a Selected function", MI); 862 863 const MCInstrDesc &MCID = MI->getDesc(); 864 unsigned NumOps = MI->getNumOperands(); 865 866 // Branches must reference a basic block if they are not indirect 867 if (MI->isBranch() && !MI->isIndirectBranch()) { 868 bool HasMBB = false; 869 for (const MachineOperand &Op : MI->operands()) { 870 if (Op.isMBB()) { 871 HasMBB = true; 872 break; 873 } 874 } 875 876 if (!HasMBB) { 877 report("Branch instruction is missing a basic block operand or " 878 "isIndirectBranch property", 879 MI); 880 } 881 } 882 883 // Check types. 884 SmallVector<LLT, 4> Types; 885 for (unsigned I = 0, E = std::min(MCID.getNumOperands(), NumOps); 886 I != E; ++I) { 887 if (!MCID.OpInfo[I].isGenericType()) 888 continue; 889 // Generic instructions specify type equality constraints between some of 890 // their operands. Make sure these are consistent. 891 size_t TypeIdx = MCID.OpInfo[I].getGenericTypeIndex(); 892 Types.resize(std::max(TypeIdx + 1, Types.size())); 893 894 const MachineOperand *MO = &MI->getOperand(I); 895 if (!MO->isReg()) { 896 report("generic instruction must use register operands", MI); 897 continue; 898 } 899 900 LLT OpTy = MRI->getType(MO->getReg()); 901 // Don't report a type mismatch if there is no actual mismatch, only a 902 // type missing, to reduce noise: 903 if (OpTy.isValid()) { 904 // Only the first valid type for a type index will be printed: don't 905 // overwrite it later so it's always clear which type was expected: 906 if (!Types[TypeIdx].isValid()) 907 Types[TypeIdx] = OpTy; 908 else if (Types[TypeIdx] != OpTy) 909 report("Type mismatch in generic instruction", MO, I, OpTy); 910 } else { 911 // Generic instructions must have types attached to their operands. 912 report("Generic instruction is missing a virtual register type", MO, I); 913 } 914 } 915 916 // Generic opcodes must not have physical register operands. 917 for (unsigned I = 0; I < MI->getNumOperands(); ++I) { 918 const MachineOperand *MO = &MI->getOperand(I); 919 if (MO->isReg() && Register::isPhysicalRegister(MO->getReg())) 920 report("Generic instruction cannot have physical register", MO, I); 921 } 922 923 // Avoid out of bounds in checks below. This was already reported earlier. 924 if (MI->getNumOperands() < MCID.getNumOperands()) 925 return; 926 927 StringRef ErrorInfo; 928 if (!TII->verifyInstruction(*MI, ErrorInfo)) 929 report(ErrorInfo.data(), MI); 930 931 // Verify properties of various specific instruction types 932 switch (MI->getOpcode()) { 933 case TargetOpcode::G_CONSTANT: 934 case TargetOpcode::G_FCONSTANT: { 935 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 936 if (DstTy.isVector()) 937 report("Instruction cannot use a vector result type", MI); 938 939 if (MI->getOpcode() == TargetOpcode::G_CONSTANT) { 940 if (!MI->getOperand(1).isCImm()) { 941 report("G_CONSTANT operand must be cimm", MI); 942 break; 943 } 944 945 const ConstantInt *CI = MI->getOperand(1).getCImm(); 946 if (CI->getBitWidth() != DstTy.getSizeInBits()) 947 report("inconsistent constant size", MI); 948 } else { 949 if (!MI->getOperand(1).isFPImm()) { 950 report("G_FCONSTANT operand must be fpimm", MI); 951 break; 952 } 953 const ConstantFP *CF = MI->getOperand(1).getFPImm(); 954 955 if (APFloat::getSizeInBits(CF->getValueAPF().getSemantics()) != 956 DstTy.getSizeInBits()) { 957 report("inconsistent constant size", MI); 958 } 959 } 960 961 break; 962 } 963 case TargetOpcode::G_LOAD: 964 case TargetOpcode::G_STORE: 965 case TargetOpcode::G_ZEXTLOAD: 966 case TargetOpcode::G_SEXTLOAD: { 967 LLT ValTy = MRI->getType(MI->getOperand(0).getReg()); 968 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg()); 969 if (!PtrTy.isPointer()) 970 report("Generic memory instruction must access a pointer", MI); 971 972 // Generic loads and stores must have a single MachineMemOperand 973 // describing that access. 974 if (!MI->hasOneMemOperand()) { 975 report("Generic instruction accessing memory must have one mem operand", 976 MI); 977 } else { 978 const MachineMemOperand &MMO = **MI->memoperands_begin(); 979 if (MI->getOpcode() == TargetOpcode::G_ZEXTLOAD || 980 MI->getOpcode() == TargetOpcode::G_SEXTLOAD) { 981 if (MMO.getSizeInBits() >= ValTy.getSizeInBits()) 982 report("Generic extload must have a narrower memory type", MI); 983 } else if (MI->getOpcode() == TargetOpcode::G_LOAD) { 984 if (MMO.getSize() > ValTy.getSizeInBytes()) 985 report("load memory size cannot exceed result size", MI); 986 } else if (MI->getOpcode() == TargetOpcode::G_STORE) { 987 if (ValTy.getSizeInBytes() < MMO.getSize()) 988 report("store memory size cannot exceed value size", MI); 989 } 990 } 991 992 break; 993 } 994 case TargetOpcode::G_PHI: { 995 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 996 if (!DstTy.isValid() || 997 !std::all_of(MI->operands_begin() + 1, MI->operands_end(), 998 [this, &DstTy](const MachineOperand &MO) { 999 if (!MO.isReg()) 1000 return true; 1001 LLT Ty = MRI->getType(MO.getReg()); 1002 if (!Ty.isValid() || (Ty != DstTy)) 1003 return false; 1004 return true; 1005 })) 1006 report("Generic Instruction G_PHI has operands with incompatible/missing " 1007 "types", 1008 MI); 1009 break; 1010 } 1011 case TargetOpcode::G_BITCAST: { 1012 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1013 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1014 if (!DstTy.isValid() || !SrcTy.isValid()) 1015 break; 1016 1017 if (SrcTy.isPointer() != DstTy.isPointer()) 1018 report("bitcast cannot convert between pointers and other types", MI); 1019 1020 if (SrcTy.getSizeInBits() != DstTy.getSizeInBits()) 1021 report("bitcast sizes must match", MI); 1022 1023 if (SrcTy == DstTy) 1024 report("bitcast must change the type", MI); 1025 1026 break; 1027 } 1028 case TargetOpcode::G_INTTOPTR: 1029 case TargetOpcode::G_PTRTOINT: 1030 case TargetOpcode::G_ADDRSPACE_CAST: { 1031 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1032 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1033 if (!DstTy.isValid() || !SrcTy.isValid()) 1034 break; 1035 1036 verifyVectorElementMatch(DstTy, SrcTy, MI); 1037 1038 DstTy = DstTy.getScalarType(); 1039 SrcTy = SrcTy.getScalarType(); 1040 1041 if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) { 1042 if (!DstTy.isPointer()) 1043 report("inttoptr result type must be a pointer", MI); 1044 if (SrcTy.isPointer()) 1045 report("inttoptr source type must not be a pointer", MI); 1046 } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) { 1047 if (!SrcTy.isPointer()) 1048 report("ptrtoint source type must be a pointer", MI); 1049 if (DstTy.isPointer()) 1050 report("ptrtoint result type must not be a pointer", MI); 1051 } else { 1052 assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST); 1053 if (!SrcTy.isPointer() || !DstTy.isPointer()) 1054 report("addrspacecast types must be pointers", MI); 1055 else { 1056 if (SrcTy.getAddressSpace() == DstTy.getAddressSpace()) 1057 report("addrspacecast must convert different address spaces", MI); 1058 } 1059 } 1060 1061 break; 1062 } 1063 case TargetOpcode::G_PTR_ADD: { 1064 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1065 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg()); 1066 LLT OffsetTy = MRI->getType(MI->getOperand(2).getReg()); 1067 if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid()) 1068 break; 1069 1070 if (!PtrTy.getScalarType().isPointer()) 1071 report("gep first operand must be a pointer", MI); 1072 1073 if (OffsetTy.getScalarType().isPointer()) 1074 report("gep offset operand must not be a pointer", MI); 1075 1076 // TODO: Is the offset allowed to be a scalar with a vector? 1077 break; 1078 } 1079 case TargetOpcode::G_PTRMASK: { 1080 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1081 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1082 LLT MaskTy = MRI->getType(MI->getOperand(2).getReg()); 1083 if (!DstTy.isValid() || !SrcTy.isValid() || !MaskTy.isValid()) 1084 break; 1085 1086 if (!DstTy.getScalarType().isPointer()) 1087 report("ptrmask result type must be a pointer", MI); 1088 1089 if (!MaskTy.getScalarType().isScalar()) 1090 report("ptrmask mask type must be an integer", MI); 1091 1092 verifyVectorElementMatch(DstTy, MaskTy, MI); 1093 break; 1094 } 1095 case TargetOpcode::G_SEXT: 1096 case TargetOpcode::G_ZEXT: 1097 case TargetOpcode::G_ANYEXT: 1098 case TargetOpcode::G_TRUNC: 1099 case TargetOpcode::G_FPEXT: 1100 case TargetOpcode::G_FPTRUNC: { 1101 // Number of operands and presense of types is already checked (and 1102 // reported in case of any issues), so no need to report them again. As 1103 // we're trying to report as many issues as possible at once, however, the 1104 // instructions aren't guaranteed to have the right number of operands or 1105 // types attached to them at this point 1106 assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}"); 1107 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1108 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1109 if (!DstTy.isValid() || !SrcTy.isValid()) 1110 break; 1111 1112 LLT DstElTy = DstTy.getScalarType(); 1113 LLT SrcElTy = SrcTy.getScalarType(); 1114 if (DstElTy.isPointer() || SrcElTy.isPointer()) 1115 report("Generic extend/truncate can not operate on pointers", MI); 1116 1117 verifyVectorElementMatch(DstTy, SrcTy, MI); 1118 1119 unsigned DstSize = DstElTy.getSizeInBits(); 1120 unsigned SrcSize = SrcElTy.getSizeInBits(); 1121 switch (MI->getOpcode()) { 1122 default: 1123 if (DstSize <= SrcSize) 1124 report("Generic extend has destination type no larger than source", MI); 1125 break; 1126 case TargetOpcode::G_TRUNC: 1127 case TargetOpcode::G_FPTRUNC: 1128 if (DstSize >= SrcSize) 1129 report("Generic truncate has destination type no smaller than source", 1130 MI); 1131 break; 1132 } 1133 break; 1134 } 1135 case TargetOpcode::G_SELECT: { 1136 LLT SelTy = MRI->getType(MI->getOperand(0).getReg()); 1137 LLT CondTy = MRI->getType(MI->getOperand(1).getReg()); 1138 if (!SelTy.isValid() || !CondTy.isValid()) 1139 break; 1140 1141 // Scalar condition select on a vector is valid. 1142 if (CondTy.isVector()) 1143 verifyVectorElementMatch(SelTy, CondTy, MI); 1144 break; 1145 } 1146 case TargetOpcode::G_MERGE_VALUES: { 1147 // G_MERGE_VALUES should only be used to merge scalars into a larger scalar, 1148 // e.g. s2N = MERGE sN, sN 1149 // Merging multiple scalars into a vector is not allowed, should use 1150 // G_BUILD_VECTOR for that. 1151 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1152 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1153 if (DstTy.isVector() || SrcTy.isVector()) 1154 report("G_MERGE_VALUES cannot operate on vectors", MI); 1155 1156 const unsigned NumOps = MI->getNumOperands(); 1157 if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1)) 1158 report("G_MERGE_VALUES result size is inconsistent", MI); 1159 1160 for (unsigned I = 2; I != NumOps; ++I) { 1161 if (MRI->getType(MI->getOperand(I).getReg()) != SrcTy) 1162 report("G_MERGE_VALUES source types do not match", MI); 1163 } 1164 1165 break; 1166 } 1167 case TargetOpcode::G_UNMERGE_VALUES: { 1168 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1169 LLT SrcTy = MRI->getType(MI->getOperand(MI->getNumOperands()-1).getReg()); 1170 // For now G_UNMERGE can split vectors. 1171 for (unsigned i = 0; i < MI->getNumOperands()-1; ++i) { 1172 if (MRI->getType(MI->getOperand(i).getReg()) != DstTy) 1173 report("G_UNMERGE_VALUES destination types do not match", MI); 1174 } 1175 if (SrcTy.getSizeInBits() != 1176 (DstTy.getSizeInBits() * (MI->getNumOperands() - 1))) { 1177 report("G_UNMERGE_VALUES source operand does not cover dest operands", 1178 MI); 1179 } 1180 break; 1181 } 1182 case TargetOpcode::G_BUILD_VECTOR: { 1183 // Source types must be scalars, dest type a vector. Total size of scalars 1184 // must match the dest vector size. 1185 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1186 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg()); 1187 if (!DstTy.isVector() || SrcEltTy.isVector()) { 1188 report("G_BUILD_VECTOR must produce a vector from scalar operands", MI); 1189 break; 1190 } 1191 1192 if (DstTy.getElementType() != SrcEltTy) 1193 report("G_BUILD_VECTOR result element type must match source type", MI); 1194 1195 if (DstTy.getNumElements() != MI->getNumOperands() - 1) 1196 report("G_BUILD_VECTOR must have an operand for each elemement", MI); 1197 1198 for (unsigned i = 2; i < MI->getNumOperands(); ++i) { 1199 if (MRI->getType(MI->getOperand(1).getReg()) != 1200 MRI->getType(MI->getOperand(i).getReg())) 1201 report("G_BUILD_VECTOR source operand types are not homogeneous", MI); 1202 } 1203 1204 break; 1205 } 1206 case TargetOpcode::G_BUILD_VECTOR_TRUNC: { 1207 // Source types must be scalars, dest type a vector. Scalar types must be 1208 // larger than the dest vector elt type, as this is a truncating operation. 1209 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1210 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg()); 1211 if (!DstTy.isVector() || SrcEltTy.isVector()) 1212 report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands", 1213 MI); 1214 for (unsigned i = 2; i < MI->getNumOperands(); ++i) { 1215 if (MRI->getType(MI->getOperand(1).getReg()) != 1216 MRI->getType(MI->getOperand(i).getReg())) 1217 report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous", 1218 MI); 1219 } 1220 if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits()) 1221 report("G_BUILD_VECTOR_TRUNC source operand types are not larger than " 1222 "dest elt type", 1223 MI); 1224 break; 1225 } 1226 case TargetOpcode::G_CONCAT_VECTORS: { 1227 // Source types should be vectors, and total size should match the dest 1228 // vector size. 1229 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1230 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1231 if (!DstTy.isVector() || !SrcTy.isVector()) 1232 report("G_CONCAT_VECTOR requires vector source and destination operands", 1233 MI); 1234 for (unsigned i = 2; i < MI->getNumOperands(); ++i) { 1235 if (MRI->getType(MI->getOperand(1).getReg()) != 1236 MRI->getType(MI->getOperand(i).getReg())) 1237 report("G_CONCAT_VECTOR source operand types are not homogeneous", MI); 1238 } 1239 if (DstTy.getNumElements() != 1240 SrcTy.getNumElements() * (MI->getNumOperands() - 1)) 1241 report("G_CONCAT_VECTOR num dest and source elements should match", MI); 1242 break; 1243 } 1244 case TargetOpcode::G_ICMP: 1245 case TargetOpcode::G_FCMP: { 1246 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1247 LLT SrcTy = MRI->getType(MI->getOperand(2).getReg()); 1248 1249 if ((DstTy.isVector() != SrcTy.isVector()) || 1250 (DstTy.isVector() && DstTy.getNumElements() != SrcTy.getNumElements())) 1251 report("Generic vector icmp/fcmp must preserve number of lanes", MI); 1252 1253 break; 1254 } 1255 case TargetOpcode::G_EXTRACT: { 1256 const MachineOperand &SrcOp = MI->getOperand(1); 1257 if (!SrcOp.isReg()) { 1258 report("extract source must be a register", MI); 1259 break; 1260 } 1261 1262 const MachineOperand &OffsetOp = MI->getOperand(2); 1263 if (!OffsetOp.isImm()) { 1264 report("extract offset must be a constant", MI); 1265 break; 1266 } 1267 1268 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits(); 1269 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits(); 1270 if (SrcSize == DstSize) 1271 report("extract source must be larger than result", MI); 1272 1273 if (DstSize + OffsetOp.getImm() > SrcSize) 1274 report("extract reads past end of register", MI); 1275 break; 1276 } 1277 case TargetOpcode::G_INSERT: { 1278 const MachineOperand &SrcOp = MI->getOperand(2); 1279 if (!SrcOp.isReg()) { 1280 report("insert source must be a register", MI); 1281 break; 1282 } 1283 1284 const MachineOperand &OffsetOp = MI->getOperand(3); 1285 if (!OffsetOp.isImm()) { 1286 report("insert offset must be a constant", MI); 1287 break; 1288 } 1289 1290 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits(); 1291 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits(); 1292 1293 if (DstSize <= SrcSize) 1294 report("inserted size must be smaller than total register", MI); 1295 1296 if (SrcSize + OffsetOp.getImm() > DstSize) 1297 report("insert writes past end of register", MI); 1298 1299 break; 1300 } 1301 case TargetOpcode::G_JUMP_TABLE: { 1302 if (!MI->getOperand(1).isJTI()) 1303 report("G_JUMP_TABLE source operand must be a jump table index", MI); 1304 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1305 if (!DstTy.isPointer()) 1306 report("G_JUMP_TABLE dest operand must have a pointer type", MI); 1307 break; 1308 } 1309 case TargetOpcode::G_BRJT: { 1310 if (!MRI->getType(MI->getOperand(0).getReg()).isPointer()) 1311 report("G_BRJT src operand 0 must be a pointer type", MI); 1312 1313 if (!MI->getOperand(1).isJTI()) 1314 report("G_BRJT src operand 1 must be a jump table index", MI); 1315 1316 const auto &IdxOp = MI->getOperand(2); 1317 if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer()) 1318 report("G_BRJT src operand 2 must be a scalar reg type", MI); 1319 break; 1320 } 1321 case TargetOpcode::G_INTRINSIC: 1322 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS: { 1323 // TODO: Should verify number of def and use operands, but the current 1324 // interface requires passing in IR types for mangling. 1325 const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs()); 1326 if (!IntrIDOp.isIntrinsicID()) { 1327 report("G_INTRINSIC first src operand must be an intrinsic ID", MI); 1328 break; 1329 } 1330 1331 bool NoSideEffects = MI->getOpcode() == TargetOpcode::G_INTRINSIC; 1332 unsigned IntrID = IntrIDOp.getIntrinsicID(); 1333 if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) { 1334 AttributeList Attrs 1335 = Intrinsic::getAttributes(MF->getFunction().getContext(), 1336 static_cast<Intrinsic::ID>(IntrID)); 1337 bool DeclHasSideEffects = !Attrs.hasFnAttribute(Attribute::ReadNone); 1338 if (NoSideEffects && DeclHasSideEffects) { 1339 report("G_INTRINSIC used with intrinsic that accesses memory", MI); 1340 break; 1341 } 1342 if (!NoSideEffects && !DeclHasSideEffects) { 1343 report("G_INTRINSIC_W_SIDE_EFFECTS used with readnone intrinsic", MI); 1344 break; 1345 } 1346 } 1347 switch (IntrID) { 1348 case Intrinsic::memcpy: 1349 if (MI->getNumOperands() != 5) 1350 report("Expected memcpy intrinsic to have 5 operands", MI); 1351 break; 1352 case Intrinsic::memmove: 1353 if (MI->getNumOperands() != 5) 1354 report("Expected memmove intrinsic to have 5 operands", MI); 1355 break; 1356 case Intrinsic::memset: 1357 if (MI->getNumOperands() != 5) 1358 report("Expected memset intrinsic to have 5 operands", MI); 1359 break; 1360 } 1361 break; 1362 } 1363 case TargetOpcode::G_SEXT_INREG: { 1364 if (!MI->getOperand(2).isImm()) { 1365 report("G_SEXT_INREG expects an immediate operand #2", MI); 1366 break; 1367 } 1368 1369 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1370 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1371 verifyVectorElementMatch(DstTy, SrcTy, MI); 1372 1373 int64_t Imm = MI->getOperand(2).getImm(); 1374 if (Imm <= 0) 1375 report("G_SEXT_INREG size must be >= 1", MI); 1376 if (Imm >= SrcTy.getScalarSizeInBits()) 1377 report("G_SEXT_INREG size must be less than source bit width", MI); 1378 break; 1379 } 1380 case TargetOpcode::G_SHUFFLE_VECTOR: { 1381 const MachineOperand &MaskOp = MI->getOperand(3); 1382 if (!MaskOp.isShuffleMask()) { 1383 report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI); 1384 break; 1385 } 1386 1387 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1388 LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg()); 1389 LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg()); 1390 1391 if (Src0Ty != Src1Ty) 1392 report("Source operands must be the same type", MI); 1393 1394 if (Src0Ty.getScalarType() != DstTy.getScalarType()) 1395 report("G_SHUFFLE_VECTOR cannot change element type", MI); 1396 1397 // Don't check that all operands are vector because scalars are used in 1398 // place of 1 element vectors. 1399 int SrcNumElts = Src0Ty.isVector() ? Src0Ty.getNumElements() : 1; 1400 int DstNumElts = DstTy.isVector() ? DstTy.getNumElements() : 1; 1401 1402 ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask(); 1403 1404 if (static_cast<int>(MaskIdxes.size()) != DstNumElts) 1405 report("Wrong result type for shufflemask", MI); 1406 1407 for (int Idx : MaskIdxes) { 1408 if (Idx < 0) 1409 continue; 1410 1411 if (Idx >= 2 * SrcNumElts) 1412 report("Out of bounds shuffle index", MI); 1413 } 1414 1415 break; 1416 } 1417 case TargetOpcode::G_DYN_STACKALLOC: { 1418 const MachineOperand &DstOp = MI->getOperand(0); 1419 const MachineOperand &AllocOp = MI->getOperand(1); 1420 const MachineOperand &AlignOp = MI->getOperand(2); 1421 1422 if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) { 1423 report("dst operand 0 must be a pointer type", MI); 1424 break; 1425 } 1426 1427 if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) { 1428 report("src operand 1 must be a scalar reg type", MI); 1429 break; 1430 } 1431 1432 if (!AlignOp.isImm()) { 1433 report("src operand 2 must be an immediate type", MI); 1434 break; 1435 } 1436 break; 1437 } 1438 default: 1439 break; 1440 } 1441 } 1442 1443 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) { 1444 const MCInstrDesc &MCID = MI->getDesc(); 1445 if (MI->getNumOperands() < MCID.getNumOperands()) { 1446 report("Too few operands", MI); 1447 errs() << MCID.getNumOperands() << " operands expected, but " 1448 << MI->getNumOperands() << " given.\n"; 1449 } 1450 1451 if (MI->isPHI()) { 1452 if (MF->getProperties().hasProperty( 1453 MachineFunctionProperties::Property::NoPHIs)) 1454 report("Found PHI instruction with NoPHIs property set", MI); 1455 1456 if (FirstNonPHI) 1457 report("Found PHI instruction after non-PHI", MI); 1458 } else if (FirstNonPHI == nullptr) 1459 FirstNonPHI = MI; 1460 1461 // Check the tied operands. 1462 if (MI->isInlineAsm()) 1463 verifyInlineAsm(MI); 1464 1465 // A fully-formed DBG_VALUE must have a location. Ignore partially formed 1466 // DBG_VALUEs: these are convenient to use in tests, but should never get 1467 // generated. 1468 if (MI->isDebugValue() && MI->getNumOperands() == 4) 1469 if (!MI->getDebugLoc()) 1470 report("Missing DebugLoc for debug instruction", MI); 1471 1472 // Check the MachineMemOperands for basic consistency. 1473 for (MachineMemOperand *Op : MI->memoperands()) { 1474 if (Op->isLoad() && !MI->mayLoad()) 1475 report("Missing mayLoad flag", MI); 1476 if (Op->isStore() && !MI->mayStore()) 1477 report("Missing mayStore flag", MI); 1478 } 1479 1480 // Debug values must not have a slot index. 1481 // Other instructions must have one, unless they are inside a bundle. 1482 if (LiveInts) { 1483 bool mapped = !LiveInts->isNotInMIMap(*MI); 1484 if (MI->isDebugInstr()) { 1485 if (mapped) 1486 report("Debug instruction has a slot index", MI); 1487 } else if (MI->isInsideBundle()) { 1488 if (mapped) 1489 report("Instruction inside bundle has a slot index", MI); 1490 } else { 1491 if (!mapped) 1492 report("Missing slot index", MI); 1493 } 1494 } 1495 1496 if (isPreISelGenericOpcode(MCID.getOpcode())) { 1497 verifyPreISelGenericInstruction(MI); 1498 return; 1499 } 1500 1501 StringRef ErrorInfo; 1502 if (!TII->verifyInstruction(*MI, ErrorInfo)) 1503 report(ErrorInfo.data(), MI); 1504 1505 // Verify properties of various specific instruction types 1506 switch (MI->getOpcode()) { 1507 case TargetOpcode::COPY: { 1508 if (foundErrors) 1509 break; 1510 const MachineOperand &DstOp = MI->getOperand(0); 1511 const MachineOperand &SrcOp = MI->getOperand(1); 1512 LLT DstTy = MRI->getType(DstOp.getReg()); 1513 LLT SrcTy = MRI->getType(SrcOp.getReg()); 1514 if (SrcTy.isValid() && DstTy.isValid()) { 1515 // If both types are valid, check that the types are the same. 1516 if (SrcTy != DstTy) { 1517 report("Copy Instruction is illegal with mismatching types", MI); 1518 errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n"; 1519 } 1520 } 1521 if (SrcTy.isValid() || DstTy.isValid()) { 1522 // If one of them have valid types, let's just check they have the same 1523 // size. 1524 unsigned SrcSize = TRI->getRegSizeInBits(SrcOp.getReg(), *MRI); 1525 unsigned DstSize = TRI->getRegSizeInBits(DstOp.getReg(), *MRI); 1526 assert(SrcSize && "Expecting size here"); 1527 assert(DstSize && "Expecting size here"); 1528 if (SrcSize != DstSize) 1529 if (!DstOp.getSubReg() && !SrcOp.getSubReg()) { 1530 report("Copy Instruction is illegal with mismatching sizes", MI); 1531 errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize 1532 << "\n"; 1533 } 1534 } 1535 break; 1536 } 1537 case TargetOpcode::STATEPOINT: { 1538 StatepointOpers SO(MI); 1539 if (!MI->getOperand(SO.getIDPos()).isImm() || 1540 !MI->getOperand(SO.getNBytesPos()).isImm() || 1541 !MI->getOperand(SO.getNCallArgsPos()).isImm()) { 1542 report("meta operands to STATEPOINT not constant!", MI); 1543 break; 1544 } 1545 1546 auto VerifyStackMapConstant = [&](unsigned Offset) { 1547 if (!MI->getOperand(Offset - 1).isImm() || 1548 MI->getOperand(Offset - 1).getImm() != StackMaps::ConstantOp || 1549 !MI->getOperand(Offset).isImm()) 1550 report("stack map constant to STATEPOINT not well formed!", MI); 1551 }; 1552 VerifyStackMapConstant(SO.getCCIdx()); 1553 VerifyStackMapConstant(SO.getFlagsIdx()); 1554 VerifyStackMapConstant(SO.getNumDeoptArgsIdx()); 1555 1556 // TODO: verify we have properly encoded deopt arguments 1557 } break; 1558 } 1559 } 1560 1561 void 1562 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) { 1563 const MachineInstr *MI = MO->getParent(); 1564 const MCInstrDesc &MCID = MI->getDesc(); 1565 unsigned NumDefs = MCID.getNumDefs(); 1566 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT) 1567 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0; 1568 1569 // The first MCID.NumDefs operands must be explicit register defines 1570 if (MONum < NumDefs) { 1571 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 1572 if (!MO->isReg()) 1573 report("Explicit definition must be a register", MO, MONum); 1574 else if (!MO->isDef() && !MCOI.isOptionalDef()) 1575 report("Explicit definition marked as use", MO, MONum); 1576 else if (MO->isImplicit()) 1577 report("Explicit definition marked as implicit", MO, MONum); 1578 } else if (MONum < MCID.getNumOperands()) { 1579 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 1580 // Don't check if it's the last operand in a variadic instruction. See, 1581 // e.g., LDM_RET in the arm back end. Check non-variadic operands only. 1582 bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1; 1583 if (!IsOptional) { 1584 if (MO->isReg()) { 1585 if (MO->isDef() && !MCOI.isOptionalDef() && !MCID.variadicOpsAreDefs()) 1586 report("Explicit operand marked as def", MO, MONum); 1587 if (MO->isImplicit()) 1588 report("Explicit operand marked as implicit", MO, MONum); 1589 } 1590 1591 // Check that an instruction has register operands only as expected. 1592 if (MCOI.OperandType == MCOI::OPERAND_REGISTER && 1593 !MO->isReg() && !MO->isFI()) 1594 report("Expected a register operand.", MO, MONum); 1595 if ((MCOI.OperandType == MCOI::OPERAND_IMMEDIATE || 1596 MCOI.OperandType == MCOI::OPERAND_PCREL) && MO->isReg()) 1597 report("Expected a non-register operand.", MO, MONum); 1598 } 1599 1600 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO); 1601 if (TiedTo != -1) { 1602 if (!MO->isReg()) 1603 report("Tied use must be a register", MO, MONum); 1604 else if (!MO->isTied()) 1605 report("Operand should be tied", MO, MONum); 1606 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum)) 1607 report("Tied def doesn't match MCInstrDesc", MO, MONum); 1608 else if (Register::isPhysicalRegister(MO->getReg())) { 1609 const MachineOperand &MOTied = MI->getOperand(TiedTo); 1610 if (!MOTied.isReg()) 1611 report("Tied counterpart must be a register", &MOTied, TiedTo); 1612 else if (Register::isPhysicalRegister(MOTied.getReg()) && 1613 MO->getReg() != MOTied.getReg()) 1614 report("Tied physical registers must match.", &MOTied, TiedTo); 1615 } 1616 } else if (MO->isReg() && MO->isTied()) 1617 report("Explicit operand should not be tied", MO, MONum); 1618 } else { 1619 // ARM adds %reg0 operands to indicate predicates. We'll allow that. 1620 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg()) 1621 report("Extra explicit operand on non-variadic instruction", MO, MONum); 1622 } 1623 1624 switch (MO->getType()) { 1625 case MachineOperand::MO_Register: { 1626 const Register Reg = MO->getReg(); 1627 if (!Reg) 1628 return; 1629 if (MRI->tracksLiveness() && !MI->isDebugValue()) 1630 checkLiveness(MO, MONum); 1631 1632 // Verify the consistency of tied operands. 1633 if (MO->isTied()) { 1634 unsigned OtherIdx = MI->findTiedOperandIdx(MONum); 1635 const MachineOperand &OtherMO = MI->getOperand(OtherIdx); 1636 if (!OtherMO.isReg()) 1637 report("Must be tied to a register", MO, MONum); 1638 if (!OtherMO.isTied()) 1639 report("Missing tie flags on tied operand", MO, MONum); 1640 if (MI->findTiedOperandIdx(OtherIdx) != MONum) 1641 report("Inconsistent tie links", MO, MONum); 1642 if (MONum < MCID.getNumDefs()) { 1643 if (OtherIdx < MCID.getNumOperands()) { 1644 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO)) 1645 report("Explicit def tied to explicit use without tie constraint", 1646 MO, MONum); 1647 } else { 1648 if (!OtherMO.isImplicit()) 1649 report("Explicit def should be tied to implicit use", MO, MONum); 1650 } 1651 } 1652 } 1653 1654 // Verify two-address constraints after the twoaddressinstruction pass. 1655 // Both twoaddressinstruction pass and phi-node-elimination pass call 1656 // MRI->leaveSSA() to set MF as NoSSA, we should do the verification after 1657 // twoaddressinstruction pass not after phi-node-elimination pass. So we 1658 // shouldn't use the NoSSA as the condition, we should based on 1659 // TiedOpsRewritten property to verify two-address constraints, this 1660 // property will be set in twoaddressinstruction pass. 1661 unsigned DefIdx; 1662 if (MF->getProperties().hasProperty( 1663 MachineFunctionProperties::Property::TiedOpsRewritten) && 1664 MO->isUse() && MI->isRegTiedToDefOperand(MONum, &DefIdx) && 1665 Reg != MI->getOperand(DefIdx).getReg()) 1666 report("Two-address instruction operands must be identical", MO, MONum); 1667 1668 // Check register classes. 1669 unsigned SubIdx = MO->getSubReg(); 1670 1671 if (Register::isPhysicalRegister(Reg)) { 1672 if (SubIdx) { 1673 report("Illegal subregister index for physical register", MO, MONum); 1674 return; 1675 } 1676 if (MONum < MCID.getNumOperands()) { 1677 if (const TargetRegisterClass *DRC = 1678 TII->getRegClass(MCID, MONum, TRI, *MF)) { 1679 if (!DRC->contains(Reg)) { 1680 report("Illegal physical register for instruction", MO, MONum); 1681 errs() << printReg(Reg, TRI) << " is not a " 1682 << TRI->getRegClassName(DRC) << " register.\n"; 1683 } 1684 } 1685 } 1686 if (MO->isRenamable()) { 1687 if (MRI->isReserved(Reg)) { 1688 report("isRenamable set on reserved register", MO, MONum); 1689 return; 1690 } 1691 } 1692 if (MI->isDebugValue() && MO->isUse() && !MO->isDebug()) { 1693 report("Use-reg is not IsDebug in a DBG_VALUE", MO, MONum); 1694 return; 1695 } 1696 } else { 1697 // Virtual register. 1698 const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg); 1699 if (!RC) { 1700 // This is a generic virtual register. 1701 1702 // Do not allow undef uses for generic virtual registers. This ensures 1703 // getVRegDef can never fail and return null on a generic register. 1704 // 1705 // FIXME: This restriction should probably be broadened to all SSA 1706 // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still 1707 // run on the SSA function just before phi elimination. 1708 if (MO->isUndef()) 1709 report("Generic virtual register use cannot be undef", MO, MONum); 1710 1711 // If we're post-Select, we can't have gvregs anymore. 1712 if (isFunctionSelected) { 1713 report("Generic virtual register invalid in a Selected function", 1714 MO, MONum); 1715 return; 1716 } 1717 1718 // The gvreg must have a type and it must not have a SubIdx. 1719 LLT Ty = MRI->getType(Reg); 1720 if (!Ty.isValid()) { 1721 report("Generic virtual register must have a valid type", MO, 1722 MONum); 1723 return; 1724 } 1725 1726 const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg); 1727 1728 // If we're post-RegBankSelect, the gvreg must have a bank. 1729 if (!RegBank && isFunctionRegBankSelected) { 1730 report("Generic virtual register must have a bank in a " 1731 "RegBankSelected function", 1732 MO, MONum); 1733 return; 1734 } 1735 1736 // Make sure the register fits into its register bank if any. 1737 if (RegBank && Ty.isValid() && 1738 RegBank->getSize() < Ty.getSizeInBits()) { 1739 report("Register bank is too small for virtual register", MO, 1740 MONum); 1741 errs() << "Register bank " << RegBank->getName() << " too small(" 1742 << RegBank->getSize() << ") to fit " << Ty.getSizeInBits() 1743 << "-bits\n"; 1744 return; 1745 } 1746 if (SubIdx) { 1747 report("Generic virtual register does not allow subregister index", MO, 1748 MONum); 1749 return; 1750 } 1751 1752 // If this is a target specific instruction and this operand 1753 // has register class constraint, the virtual register must 1754 // comply to it. 1755 if (!isPreISelGenericOpcode(MCID.getOpcode()) && 1756 MONum < MCID.getNumOperands() && 1757 TII->getRegClass(MCID, MONum, TRI, *MF)) { 1758 report("Virtual register does not match instruction constraint", MO, 1759 MONum); 1760 errs() << "Expect register class " 1761 << TRI->getRegClassName( 1762 TII->getRegClass(MCID, MONum, TRI, *MF)) 1763 << " but got nothing\n"; 1764 return; 1765 } 1766 1767 break; 1768 } 1769 if (SubIdx) { 1770 const TargetRegisterClass *SRC = 1771 TRI->getSubClassWithSubReg(RC, SubIdx); 1772 if (!SRC) { 1773 report("Invalid subregister index for virtual register", MO, MONum); 1774 errs() << "Register class " << TRI->getRegClassName(RC) 1775 << " does not support subreg index " << SubIdx << "\n"; 1776 return; 1777 } 1778 if (RC != SRC) { 1779 report("Invalid register class for subregister index", MO, MONum); 1780 errs() << "Register class " << TRI->getRegClassName(RC) 1781 << " does not fully support subreg index " << SubIdx << "\n"; 1782 return; 1783 } 1784 } 1785 if (MONum < MCID.getNumOperands()) { 1786 if (const TargetRegisterClass *DRC = 1787 TII->getRegClass(MCID, MONum, TRI, *MF)) { 1788 if (SubIdx) { 1789 const TargetRegisterClass *SuperRC = 1790 TRI->getLargestLegalSuperClass(RC, *MF); 1791 if (!SuperRC) { 1792 report("No largest legal super class exists.", MO, MONum); 1793 return; 1794 } 1795 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx); 1796 if (!DRC) { 1797 report("No matching super-reg register class.", MO, MONum); 1798 return; 1799 } 1800 } 1801 if (!RC->hasSuperClassEq(DRC)) { 1802 report("Illegal virtual register for instruction", MO, MONum); 1803 errs() << "Expected a " << TRI->getRegClassName(DRC) 1804 << " register, but got a " << TRI->getRegClassName(RC) 1805 << " register\n"; 1806 } 1807 } 1808 } 1809 } 1810 break; 1811 } 1812 1813 case MachineOperand::MO_RegisterMask: 1814 regMasks.push_back(MO->getRegMask()); 1815 break; 1816 1817 case MachineOperand::MO_MachineBasicBlock: 1818 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent())) 1819 report("PHI operand is not in the CFG", MO, MONum); 1820 break; 1821 1822 case MachineOperand::MO_FrameIndex: 1823 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) && 1824 LiveInts && !LiveInts->isNotInMIMap(*MI)) { 1825 int FI = MO->getIndex(); 1826 LiveInterval &LI = LiveStks->getInterval(FI); 1827 SlotIndex Idx = LiveInts->getInstructionIndex(*MI); 1828 1829 bool stores = MI->mayStore(); 1830 bool loads = MI->mayLoad(); 1831 // For a memory-to-memory move, we need to check if the frame 1832 // index is used for storing or loading, by inspecting the 1833 // memory operands. 1834 if (stores && loads) { 1835 for (auto *MMO : MI->memoperands()) { 1836 const PseudoSourceValue *PSV = MMO->getPseudoValue(); 1837 if (PSV == nullptr) continue; 1838 const FixedStackPseudoSourceValue *Value = 1839 dyn_cast<FixedStackPseudoSourceValue>(PSV); 1840 if (Value == nullptr) continue; 1841 if (Value->getFrameIndex() != FI) continue; 1842 1843 if (MMO->isStore()) 1844 loads = false; 1845 else 1846 stores = false; 1847 break; 1848 } 1849 if (loads == stores) 1850 report("Missing fixed stack memoperand.", MI); 1851 } 1852 if (loads && !LI.liveAt(Idx.getRegSlot(true))) { 1853 report("Instruction loads from dead spill slot", MO, MONum); 1854 errs() << "Live stack: " << LI << '\n'; 1855 } 1856 if (stores && !LI.liveAt(Idx.getRegSlot())) { 1857 report("Instruction stores to dead spill slot", MO, MONum); 1858 errs() << "Live stack: " << LI << '\n'; 1859 } 1860 } 1861 break; 1862 1863 default: 1864 break; 1865 } 1866 } 1867 1868 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO, 1869 unsigned MONum, SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit, 1870 LaneBitmask LaneMask) { 1871 LiveQueryResult LRQ = LR.Query(UseIdx); 1872 // Check if we have a segment at the use, note however that we only need one 1873 // live subregister range, the others may be dead. 1874 if (!LRQ.valueIn() && LaneMask.none()) { 1875 report("No live segment at use", MO, MONum); 1876 report_context_liverange(LR); 1877 report_context_vreg_regunit(VRegOrUnit); 1878 report_context(UseIdx); 1879 } 1880 if (MO->isKill() && !LRQ.isKill()) { 1881 report("Live range continues after kill flag", MO, MONum); 1882 report_context_liverange(LR); 1883 report_context_vreg_regunit(VRegOrUnit); 1884 if (LaneMask.any()) 1885 report_context_lanemask(LaneMask); 1886 report_context(UseIdx); 1887 } 1888 } 1889 1890 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO, 1891 unsigned MONum, SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit, 1892 bool SubRangeCheck, LaneBitmask LaneMask) { 1893 if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) { 1894 assert(VNI && "NULL valno is not allowed"); 1895 if (VNI->def != DefIdx) { 1896 report("Inconsistent valno->def", MO, MONum); 1897 report_context_liverange(LR); 1898 report_context_vreg_regunit(VRegOrUnit); 1899 if (LaneMask.any()) 1900 report_context_lanemask(LaneMask); 1901 report_context(*VNI); 1902 report_context(DefIdx); 1903 } 1904 } else { 1905 report("No live segment at def", MO, MONum); 1906 report_context_liverange(LR); 1907 report_context_vreg_regunit(VRegOrUnit); 1908 if (LaneMask.any()) 1909 report_context_lanemask(LaneMask); 1910 report_context(DefIdx); 1911 } 1912 // Check that, if the dead def flag is present, LiveInts agree. 1913 if (MO->isDead()) { 1914 LiveQueryResult LRQ = LR.Query(DefIdx); 1915 if (!LRQ.isDeadDef()) { 1916 assert(Register::isVirtualRegister(VRegOrUnit) && 1917 "Expecting a virtual register."); 1918 // A dead subreg def only tells us that the specific subreg is dead. There 1919 // could be other non-dead defs of other subregs, or we could have other 1920 // parts of the register being live through the instruction. So unless we 1921 // are checking liveness for a subrange it is ok for the live range to 1922 // continue, given that we have a dead def of a subregister. 1923 if (SubRangeCheck || MO->getSubReg() == 0) { 1924 report("Live range continues after dead def flag", MO, MONum); 1925 report_context_liverange(LR); 1926 report_context_vreg_regunit(VRegOrUnit); 1927 if (LaneMask.any()) 1928 report_context_lanemask(LaneMask); 1929 } 1930 } 1931 } 1932 } 1933 1934 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) { 1935 const MachineInstr *MI = MO->getParent(); 1936 const unsigned Reg = MO->getReg(); 1937 1938 // Both use and def operands can read a register. 1939 if (MO->readsReg()) { 1940 if (MO->isKill()) 1941 addRegWithSubRegs(regsKilled, Reg); 1942 1943 // Check that LiveVars knows this kill. 1944 if (LiveVars && Register::isVirtualRegister(Reg) && MO->isKill()) { 1945 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 1946 if (!is_contained(VI.Kills, MI)) 1947 report("Kill missing from LiveVariables", MO, MONum); 1948 } 1949 1950 // Check LiveInts liveness and kill. 1951 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) { 1952 SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI); 1953 // Check the cached regunit intervals. 1954 if (Register::isPhysicalRegister(Reg) && !isReserved(Reg)) { 1955 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) { 1956 if (MRI->isReservedRegUnit(*Units)) 1957 continue; 1958 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) 1959 checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units); 1960 } 1961 } 1962 1963 if (Register::isVirtualRegister(Reg)) { 1964 if (LiveInts->hasInterval(Reg)) { 1965 // This is a virtual register interval. 1966 const LiveInterval &LI = LiveInts->getInterval(Reg); 1967 checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg); 1968 1969 if (LI.hasSubRanges() && !MO->isDef()) { 1970 unsigned SubRegIdx = MO->getSubReg(); 1971 LaneBitmask MOMask = SubRegIdx != 0 1972 ? TRI->getSubRegIndexLaneMask(SubRegIdx) 1973 : MRI->getMaxLaneMaskForVReg(Reg); 1974 LaneBitmask LiveInMask; 1975 for (const LiveInterval::SubRange &SR : LI.subranges()) { 1976 if ((MOMask & SR.LaneMask).none()) 1977 continue; 1978 checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask); 1979 LiveQueryResult LRQ = SR.Query(UseIdx); 1980 if (LRQ.valueIn()) 1981 LiveInMask |= SR.LaneMask; 1982 } 1983 // At least parts of the register has to be live at the use. 1984 if ((LiveInMask & MOMask).none()) { 1985 report("No live subrange at use", MO, MONum); 1986 report_context(LI); 1987 report_context(UseIdx); 1988 } 1989 } 1990 } else { 1991 report("Virtual register has no live interval", MO, MONum); 1992 } 1993 } 1994 } 1995 1996 // Use of a dead register. 1997 if (!regsLive.count(Reg)) { 1998 if (Register::isPhysicalRegister(Reg)) { 1999 // Reserved registers may be used even when 'dead'. 2000 bool Bad = !isReserved(Reg); 2001 // We are fine if just any subregister has a defined value. 2002 if (Bad) { 2003 2004 for (const MCPhysReg &SubReg : TRI->subregs(Reg)) { 2005 if (regsLive.count(SubReg)) { 2006 Bad = false; 2007 break; 2008 } 2009 } 2010 } 2011 // If there is an additional implicit-use of a super register we stop 2012 // here. By definition we are fine if the super register is not 2013 // (completely) dead, if the complete super register is dead we will 2014 // get a report for its operand. 2015 if (Bad) { 2016 for (const MachineOperand &MOP : MI->uses()) { 2017 if (!MOP.isReg() || !MOP.isImplicit()) 2018 continue; 2019 2020 if (!Register::isPhysicalRegister(MOP.getReg())) 2021 continue; 2022 2023 for (const MCPhysReg &SubReg : TRI->subregs(MOP.getReg())) { 2024 if (SubReg == Reg) { 2025 Bad = false; 2026 break; 2027 } 2028 } 2029 } 2030 } 2031 if (Bad) 2032 report("Using an undefined physical register", MO, MONum); 2033 } else if (MRI->def_empty(Reg)) { 2034 report("Reading virtual register without a def", MO, MONum); 2035 } else { 2036 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 2037 // We don't know which virtual registers are live in, so only complain 2038 // if vreg was killed in this MBB. Otherwise keep track of vregs that 2039 // must be live in. PHI instructions are handled separately. 2040 if (MInfo.regsKilled.count(Reg)) 2041 report("Using a killed virtual register", MO, MONum); 2042 else if (!MI->isPHI()) 2043 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI)); 2044 } 2045 } 2046 } 2047 2048 if (MO->isDef()) { 2049 // Register defined. 2050 // TODO: verify that earlyclobber ops are not used. 2051 if (MO->isDead()) 2052 addRegWithSubRegs(regsDead, Reg); 2053 else 2054 addRegWithSubRegs(regsDefined, Reg); 2055 2056 // Verify SSA form. 2057 if (MRI->isSSA() && Register::isVirtualRegister(Reg) && 2058 std::next(MRI->def_begin(Reg)) != MRI->def_end()) 2059 report("Multiple virtual register defs in SSA form", MO, MONum); 2060 2061 // Check LiveInts for a live segment, but only for virtual registers. 2062 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) { 2063 SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI); 2064 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber()); 2065 2066 if (Register::isVirtualRegister(Reg)) { 2067 if (LiveInts->hasInterval(Reg)) { 2068 const LiveInterval &LI = LiveInts->getInterval(Reg); 2069 checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg); 2070 2071 if (LI.hasSubRanges()) { 2072 unsigned SubRegIdx = MO->getSubReg(); 2073 LaneBitmask MOMask = SubRegIdx != 0 2074 ? TRI->getSubRegIndexLaneMask(SubRegIdx) 2075 : MRI->getMaxLaneMaskForVReg(Reg); 2076 for (const LiveInterval::SubRange &SR : LI.subranges()) { 2077 if ((SR.LaneMask & MOMask).none()) 2078 continue; 2079 checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask); 2080 } 2081 } 2082 } else { 2083 report("Virtual register has no Live interval", MO, MONum); 2084 } 2085 } 2086 } 2087 } 2088 } 2089 2090 // This function gets called after visiting all instructions in a bundle. The 2091 // argument points to the bundle header. 2092 // Normal stand-alone instructions are also considered 'bundles', and this 2093 // function is called for all of them. 2094 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) { 2095 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 2096 set_union(MInfo.regsKilled, regsKilled); 2097 set_subtract(regsLive, regsKilled); regsKilled.clear(); 2098 // Kill any masked registers. 2099 while (!regMasks.empty()) { 2100 const uint32_t *Mask = regMasks.pop_back_val(); 2101 for (unsigned Reg : regsLive) 2102 if (Register::isPhysicalRegister(Reg) && 2103 MachineOperand::clobbersPhysReg(Mask, Reg)) 2104 regsDead.push_back(Reg); 2105 } 2106 set_subtract(regsLive, regsDead); regsDead.clear(); 2107 set_union(regsLive, regsDefined); regsDefined.clear(); 2108 } 2109 2110 void 2111 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) { 2112 MBBInfoMap[MBB].regsLiveOut = regsLive; 2113 regsLive.clear(); 2114 2115 if (Indexes) { 2116 SlotIndex stop = Indexes->getMBBEndIdx(MBB); 2117 if (!(stop > lastIndex)) { 2118 report("Block ends before last instruction index", MBB); 2119 errs() << "Block ends at " << stop 2120 << " last instruction was at " << lastIndex << '\n'; 2121 } 2122 lastIndex = stop; 2123 } 2124 } 2125 2126 namespace { 2127 // This implements a set of registers that serves as a filter: can filter other 2128 // sets by passing through elements not in the filter and blocking those that 2129 // are. Any filter implicitly includes the full set of physical registers upon 2130 // creation, thus filtering them all out. The filter itself as a set only grows, 2131 // and needs to be as efficient as possible. 2132 struct VRegFilter { 2133 // Add elements to the filter itself. \pre Input set \p FromRegSet must have 2134 // no duplicates. Both virtual and physical registers are fine. 2135 template <typename RegSetT> void add(const RegSetT &FromRegSet) { 2136 SmallVector<unsigned, 0> VRegsBuffer; 2137 filterAndAdd(FromRegSet, VRegsBuffer); 2138 } 2139 // Filter \p FromRegSet through the filter and append passed elements into \p 2140 // ToVRegs. All elements appended are then added to the filter itself. 2141 // \returns true if anything changed. 2142 template <typename RegSetT> 2143 bool filterAndAdd(const RegSetT &FromRegSet, 2144 SmallVectorImpl<unsigned> &ToVRegs) { 2145 unsigned SparseUniverse = Sparse.size(); 2146 unsigned NewSparseUniverse = SparseUniverse; 2147 unsigned NewDenseSize = Dense.size(); 2148 size_t Begin = ToVRegs.size(); 2149 for (unsigned Reg : FromRegSet) { 2150 if (!Register::isVirtualRegister(Reg)) 2151 continue; 2152 unsigned Index = Register::virtReg2Index(Reg); 2153 if (Index < SparseUniverseMax) { 2154 if (Index < SparseUniverse && Sparse.test(Index)) 2155 continue; 2156 NewSparseUniverse = std::max(NewSparseUniverse, Index + 1); 2157 } else { 2158 if (Dense.count(Reg)) 2159 continue; 2160 ++NewDenseSize; 2161 } 2162 ToVRegs.push_back(Reg); 2163 } 2164 size_t End = ToVRegs.size(); 2165 if (Begin == End) 2166 return false; 2167 // Reserving space in sets once performs better than doing so continuously 2168 // and pays easily for double look-ups (even in Dense with SparseUniverseMax 2169 // tuned all the way down) and double iteration (the second one is over a 2170 // SmallVector, which is a lot cheaper compared to DenseSet or BitVector). 2171 Sparse.resize(NewSparseUniverse); 2172 Dense.reserve(NewDenseSize); 2173 for (unsigned I = Begin; I < End; ++I) { 2174 unsigned Reg = ToVRegs[I]; 2175 unsigned Index = Register::virtReg2Index(Reg); 2176 if (Index < SparseUniverseMax) 2177 Sparse.set(Index); 2178 else 2179 Dense.insert(Reg); 2180 } 2181 return true; 2182 } 2183 2184 private: 2185 static constexpr unsigned SparseUniverseMax = 10 * 1024 * 8; 2186 // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyound 2187 // are tracked by Dense. The only purpose of the threashold and the Dense set 2188 // is to have a reasonably growing memory usage in pathological cases (large 2189 // number of very sparse VRegFilter instances live at the same time). In 2190 // practice even in the worst-by-execution time cases having all elements 2191 // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more 2192 // space efficient than if tracked by Dense. The threashold is set to keep the 2193 // worst-case memory usage within 2x of figures determined empirically for 2194 // "all Dense" scenario in such worst-by-execution-time cases. 2195 BitVector Sparse; 2196 DenseSet<unsigned> Dense; 2197 }; 2198 2199 // Implements both a transfer function and a (binary, in-place) join operator 2200 // for a dataflow over register sets with set union join and filtering transfer 2201 // (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time. 2202 // Maintains out_b as its state, allowing for O(n) iteration over it at any 2203 // time, where n is the size of the set (as opposed to O(U) where U is the 2204 // universe). filter_b implicitly contains all physical registers at all times. 2205 class FilteringVRegSet { 2206 VRegFilter Filter; 2207 SmallVector<unsigned, 0> VRegs; 2208 2209 public: 2210 // Set-up the filter_b. \pre Input register set \p RS must have no duplicates. 2211 // Both virtual and physical registers are fine. 2212 template <typename RegSetT> void addToFilter(const RegSetT &RS) { 2213 Filter.add(RS); 2214 } 2215 // Passes \p RS through the filter_b (transfer function) and adds what's left 2216 // to itself (out_b). 2217 template <typename RegSetT> bool add(const RegSetT &RS) { 2218 // Double-duty the Filter: to maintain VRegs a set (and the join operation 2219 // a set union) just add everything being added here to the Filter as well. 2220 return Filter.filterAndAdd(RS, VRegs); 2221 } 2222 using const_iterator = decltype(VRegs)::const_iterator; 2223 const_iterator begin() const { return VRegs.begin(); } 2224 const_iterator end() const { return VRegs.end(); } 2225 size_t size() const { return VRegs.size(); } 2226 }; 2227 } // namespace 2228 2229 // Calculate the largest possible vregsPassed sets. These are the registers that 2230 // can pass through an MBB live, but may not be live every time. It is assumed 2231 // that all vregsPassed sets are empty before the call. 2232 void MachineVerifier::calcRegsPassed() { 2233 if (MF->empty()) 2234 // ReversePostOrderTraversal doesn't handle empty functions. 2235 return; 2236 2237 for (const MachineBasicBlock *MB : 2238 ReversePostOrderTraversal<const MachineFunction *>(MF)) { 2239 FilteringVRegSet VRegs; 2240 BBInfo &Info = MBBInfoMap[MB]; 2241 assert(Info.reachable); 2242 2243 VRegs.addToFilter(Info.regsKilled); 2244 VRegs.addToFilter(Info.regsLiveOut); 2245 for (const MachineBasicBlock *Pred : MB->predecessors()) { 2246 const BBInfo &PredInfo = MBBInfoMap[Pred]; 2247 if (!PredInfo.reachable) 2248 continue; 2249 2250 VRegs.add(PredInfo.regsLiveOut); 2251 VRegs.add(PredInfo.vregsPassed); 2252 } 2253 Info.vregsPassed.reserve(VRegs.size()); 2254 Info.vregsPassed.insert(VRegs.begin(), VRegs.end()); 2255 } 2256 } 2257 2258 // Calculate the set of virtual registers that must be passed through each basic 2259 // block in order to satisfy the requirements of successor blocks. This is very 2260 // similar to calcRegsPassed, only backwards. 2261 void MachineVerifier::calcRegsRequired() { 2262 // First push live-in regs to predecessors' vregsRequired. 2263 SmallPtrSet<const MachineBasicBlock*, 8> todo; 2264 for (const auto &MBB : *MF) { 2265 BBInfo &MInfo = MBBInfoMap[&MBB]; 2266 for (const MachineBasicBlock *Pred : MBB.predecessors()) { 2267 BBInfo &PInfo = MBBInfoMap[Pred]; 2268 if (PInfo.addRequired(MInfo.vregsLiveIn)) 2269 todo.insert(Pred); 2270 } 2271 2272 // Handle the PHI node. 2273 for (const MachineInstr &MI : MBB.phis()) { 2274 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) { 2275 // Skip those Operands which are undef regs or not regs. 2276 if (!MI.getOperand(i).isReg() || !MI.getOperand(i).readsReg()) 2277 continue; 2278 2279 // Get register and predecessor for one PHI edge. 2280 Register Reg = MI.getOperand(i).getReg(); 2281 const MachineBasicBlock *Pred = MI.getOperand(i + 1).getMBB(); 2282 2283 BBInfo &PInfo = MBBInfoMap[Pred]; 2284 if (PInfo.addRequired(Reg)) 2285 todo.insert(Pred); 2286 } 2287 } 2288 } 2289 2290 // Iteratively push vregsRequired to predecessors. This will converge to the 2291 // same final state regardless of DenseSet iteration order. 2292 while (!todo.empty()) { 2293 const MachineBasicBlock *MBB = *todo.begin(); 2294 todo.erase(MBB); 2295 BBInfo &MInfo = MBBInfoMap[MBB]; 2296 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 2297 if (Pred == MBB) 2298 continue; 2299 BBInfo &SInfo = MBBInfoMap[Pred]; 2300 if (SInfo.addRequired(MInfo.vregsRequired)) 2301 todo.insert(Pred); 2302 } 2303 } 2304 } 2305 2306 // Check PHI instructions at the beginning of MBB. It is assumed that 2307 // calcRegsPassed has been run so BBInfo::isLiveOut is valid. 2308 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) { 2309 BBInfo &MInfo = MBBInfoMap[&MBB]; 2310 2311 SmallPtrSet<const MachineBasicBlock*, 8> seen; 2312 for (const MachineInstr &Phi : MBB) { 2313 if (!Phi.isPHI()) 2314 break; 2315 seen.clear(); 2316 2317 const MachineOperand &MODef = Phi.getOperand(0); 2318 if (!MODef.isReg() || !MODef.isDef()) { 2319 report("Expected first PHI operand to be a register def", &MODef, 0); 2320 continue; 2321 } 2322 if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() || 2323 MODef.isEarlyClobber() || MODef.isDebug()) 2324 report("Unexpected flag on PHI operand", &MODef, 0); 2325 Register DefReg = MODef.getReg(); 2326 if (!Register::isVirtualRegister(DefReg)) 2327 report("Expected first PHI operand to be a virtual register", &MODef, 0); 2328 2329 for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) { 2330 const MachineOperand &MO0 = Phi.getOperand(I); 2331 if (!MO0.isReg()) { 2332 report("Expected PHI operand to be a register", &MO0, I); 2333 continue; 2334 } 2335 if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() || 2336 MO0.isDebug() || MO0.isTied()) 2337 report("Unexpected flag on PHI operand", &MO0, I); 2338 2339 const MachineOperand &MO1 = Phi.getOperand(I + 1); 2340 if (!MO1.isMBB()) { 2341 report("Expected PHI operand to be a basic block", &MO1, I + 1); 2342 continue; 2343 } 2344 2345 const MachineBasicBlock &Pre = *MO1.getMBB(); 2346 if (!Pre.isSuccessor(&MBB)) { 2347 report("PHI input is not a predecessor block", &MO1, I + 1); 2348 continue; 2349 } 2350 2351 if (MInfo.reachable) { 2352 seen.insert(&Pre); 2353 BBInfo &PrInfo = MBBInfoMap[&Pre]; 2354 if (!MO0.isUndef() && PrInfo.reachable && 2355 !PrInfo.isLiveOut(MO0.getReg())) 2356 report("PHI operand is not live-out from predecessor", &MO0, I); 2357 } 2358 } 2359 2360 // Did we see all predecessors? 2361 if (MInfo.reachable) { 2362 for (MachineBasicBlock *Pred : MBB.predecessors()) { 2363 if (!seen.count(Pred)) { 2364 report("Missing PHI operand", &Phi); 2365 errs() << printMBBReference(*Pred) 2366 << " is a predecessor according to the CFG.\n"; 2367 } 2368 } 2369 } 2370 } 2371 } 2372 2373 void MachineVerifier::visitMachineFunctionAfter() { 2374 calcRegsPassed(); 2375 2376 for (const MachineBasicBlock &MBB : *MF) 2377 checkPHIOps(MBB); 2378 2379 // Now check liveness info if available 2380 calcRegsRequired(); 2381 2382 // Check for killed virtual registers that should be live out. 2383 for (const auto &MBB : *MF) { 2384 BBInfo &MInfo = MBBInfoMap[&MBB]; 2385 for (unsigned VReg : MInfo.vregsRequired) 2386 if (MInfo.regsKilled.count(VReg)) { 2387 report("Virtual register killed in block, but needed live out.", &MBB); 2388 errs() << "Virtual register " << printReg(VReg) 2389 << " is used after the block.\n"; 2390 } 2391 } 2392 2393 if (!MF->empty()) { 2394 BBInfo &MInfo = MBBInfoMap[&MF->front()]; 2395 for (unsigned VReg : MInfo.vregsRequired) { 2396 report("Virtual register defs don't dominate all uses.", MF); 2397 report_context_vreg(VReg); 2398 } 2399 } 2400 2401 if (LiveVars) 2402 verifyLiveVariables(); 2403 if (LiveInts) 2404 verifyLiveIntervals(); 2405 2406 // Check live-in list of each MBB. If a register is live into MBB, check 2407 // that the register is in regsLiveOut of each predecessor block. Since 2408 // this must come from a definition in the predecesssor or its live-in 2409 // list, this will catch a live-through case where the predecessor does not 2410 // have the register in its live-in list. This currently only checks 2411 // registers that have no aliases, are not allocatable and are not 2412 // reserved, which could mean a condition code register for instance. 2413 if (MRI->tracksLiveness()) 2414 for (const auto &MBB : *MF) 2415 for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) { 2416 MCPhysReg LiveInReg = P.PhysReg; 2417 bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid(); 2418 if (hasAliases || isAllocatable(LiveInReg) || isReserved(LiveInReg)) 2419 continue; 2420 for (const MachineBasicBlock *Pred : MBB.predecessors()) { 2421 BBInfo &PInfo = MBBInfoMap[Pred]; 2422 if (!PInfo.regsLiveOut.count(LiveInReg)) { 2423 report("Live in register not found to be live out from predecessor.", 2424 &MBB); 2425 errs() << TRI->getName(LiveInReg) 2426 << " not found to be live out from " 2427 << printMBBReference(*Pred) << "\n"; 2428 } 2429 } 2430 } 2431 2432 for (auto CSInfo : MF->getCallSitesInfo()) 2433 if (!CSInfo.first->isCall()) 2434 report("Call site info referencing instruction that is not call", MF); 2435 } 2436 2437 void MachineVerifier::verifyLiveVariables() { 2438 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars"); 2439 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 2440 unsigned Reg = Register::index2VirtReg(i); 2441 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 2442 for (const auto &MBB : *MF) { 2443 BBInfo &MInfo = MBBInfoMap[&MBB]; 2444 2445 // Our vregsRequired should be identical to LiveVariables' AliveBlocks 2446 if (MInfo.vregsRequired.count(Reg)) { 2447 if (!VI.AliveBlocks.test(MBB.getNumber())) { 2448 report("LiveVariables: Block missing from AliveBlocks", &MBB); 2449 errs() << "Virtual register " << printReg(Reg) 2450 << " must be live through the block.\n"; 2451 } 2452 } else { 2453 if (VI.AliveBlocks.test(MBB.getNumber())) { 2454 report("LiveVariables: Block should not be in AliveBlocks", &MBB); 2455 errs() << "Virtual register " << printReg(Reg) 2456 << " is not needed live through the block.\n"; 2457 } 2458 } 2459 } 2460 } 2461 } 2462 2463 void MachineVerifier::verifyLiveIntervals() { 2464 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts"); 2465 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 2466 unsigned Reg = Register::index2VirtReg(i); 2467 2468 // Spilling and splitting may leave unused registers around. Skip them. 2469 if (MRI->reg_nodbg_empty(Reg)) 2470 continue; 2471 2472 if (!LiveInts->hasInterval(Reg)) { 2473 report("Missing live interval for virtual register", MF); 2474 errs() << printReg(Reg, TRI) << " still has defs or uses\n"; 2475 continue; 2476 } 2477 2478 const LiveInterval &LI = LiveInts->getInterval(Reg); 2479 assert(Reg == LI.reg && "Invalid reg to interval mapping"); 2480 verifyLiveInterval(LI); 2481 } 2482 2483 // Verify all the cached regunit intervals. 2484 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i) 2485 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i)) 2486 verifyLiveRange(*LR, i); 2487 } 2488 2489 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR, 2490 const VNInfo *VNI, unsigned Reg, 2491 LaneBitmask LaneMask) { 2492 if (VNI->isUnused()) 2493 return; 2494 2495 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def); 2496 2497 if (!DefVNI) { 2498 report("Value not live at VNInfo def and not marked unused", MF); 2499 report_context(LR, Reg, LaneMask); 2500 report_context(*VNI); 2501 return; 2502 } 2503 2504 if (DefVNI != VNI) { 2505 report("Live segment at def has different VNInfo", MF); 2506 report_context(LR, Reg, LaneMask); 2507 report_context(*VNI); 2508 return; 2509 } 2510 2511 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def); 2512 if (!MBB) { 2513 report("Invalid VNInfo definition index", MF); 2514 report_context(LR, Reg, LaneMask); 2515 report_context(*VNI); 2516 return; 2517 } 2518 2519 if (VNI->isPHIDef()) { 2520 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) { 2521 report("PHIDef VNInfo is not defined at MBB start", MBB); 2522 report_context(LR, Reg, LaneMask); 2523 report_context(*VNI); 2524 } 2525 return; 2526 } 2527 2528 // Non-PHI def. 2529 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def); 2530 if (!MI) { 2531 report("No instruction at VNInfo def index", MBB); 2532 report_context(LR, Reg, LaneMask); 2533 report_context(*VNI); 2534 return; 2535 } 2536 2537 if (Reg != 0) { 2538 bool hasDef = false; 2539 bool isEarlyClobber = false; 2540 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) { 2541 if (!MOI->isReg() || !MOI->isDef()) 2542 continue; 2543 if (Register::isVirtualRegister(Reg)) { 2544 if (MOI->getReg() != Reg) 2545 continue; 2546 } else { 2547 if (!Register::isPhysicalRegister(MOI->getReg()) || 2548 !TRI->hasRegUnit(MOI->getReg(), Reg)) 2549 continue; 2550 } 2551 if (LaneMask.any() && 2552 (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none()) 2553 continue; 2554 hasDef = true; 2555 if (MOI->isEarlyClobber()) 2556 isEarlyClobber = true; 2557 } 2558 2559 if (!hasDef) { 2560 report("Defining instruction does not modify register", MI); 2561 report_context(LR, Reg, LaneMask); 2562 report_context(*VNI); 2563 } 2564 2565 // Early clobber defs begin at USE slots, but other defs must begin at 2566 // DEF slots. 2567 if (isEarlyClobber) { 2568 if (!VNI->def.isEarlyClobber()) { 2569 report("Early clobber def must be at an early-clobber slot", MBB); 2570 report_context(LR, Reg, LaneMask); 2571 report_context(*VNI); 2572 } 2573 } else if (!VNI->def.isRegister()) { 2574 report("Non-PHI, non-early clobber def must be at a register slot", MBB); 2575 report_context(LR, Reg, LaneMask); 2576 report_context(*VNI); 2577 } 2578 } 2579 } 2580 2581 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR, 2582 const LiveRange::const_iterator I, 2583 unsigned Reg, LaneBitmask LaneMask) 2584 { 2585 const LiveRange::Segment &S = *I; 2586 const VNInfo *VNI = S.valno; 2587 assert(VNI && "Live segment has no valno"); 2588 2589 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) { 2590 report("Foreign valno in live segment", MF); 2591 report_context(LR, Reg, LaneMask); 2592 report_context(S); 2593 report_context(*VNI); 2594 } 2595 2596 if (VNI->isUnused()) { 2597 report("Live segment valno is marked unused", MF); 2598 report_context(LR, Reg, LaneMask); 2599 report_context(S); 2600 } 2601 2602 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start); 2603 if (!MBB) { 2604 report("Bad start of live segment, no basic block", MF); 2605 report_context(LR, Reg, LaneMask); 2606 report_context(S); 2607 return; 2608 } 2609 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB); 2610 if (S.start != MBBStartIdx && S.start != VNI->def) { 2611 report("Live segment must begin at MBB entry or valno def", MBB); 2612 report_context(LR, Reg, LaneMask); 2613 report_context(S); 2614 } 2615 2616 const MachineBasicBlock *EndMBB = 2617 LiveInts->getMBBFromIndex(S.end.getPrevSlot()); 2618 if (!EndMBB) { 2619 report("Bad end of live segment, no basic block", MF); 2620 report_context(LR, Reg, LaneMask); 2621 report_context(S); 2622 return; 2623 } 2624 2625 // No more checks for live-out segments. 2626 if (S.end == LiveInts->getMBBEndIdx(EndMBB)) 2627 return; 2628 2629 // RegUnit intervals are allowed dead phis. 2630 if (!Register::isVirtualRegister(Reg) && VNI->isPHIDef() && 2631 S.start == VNI->def && S.end == VNI->def.getDeadSlot()) 2632 return; 2633 2634 // The live segment is ending inside EndMBB 2635 const MachineInstr *MI = 2636 LiveInts->getInstructionFromIndex(S.end.getPrevSlot()); 2637 if (!MI) { 2638 report("Live segment doesn't end at a valid instruction", EndMBB); 2639 report_context(LR, Reg, LaneMask); 2640 report_context(S); 2641 return; 2642 } 2643 2644 // The block slot must refer to a basic block boundary. 2645 if (S.end.isBlock()) { 2646 report("Live segment ends at B slot of an instruction", EndMBB); 2647 report_context(LR, Reg, LaneMask); 2648 report_context(S); 2649 } 2650 2651 if (S.end.isDead()) { 2652 // Segment ends on the dead slot. 2653 // That means there must be a dead def. 2654 if (!SlotIndex::isSameInstr(S.start, S.end)) { 2655 report("Live segment ending at dead slot spans instructions", EndMBB); 2656 report_context(LR, Reg, LaneMask); 2657 report_context(S); 2658 } 2659 } 2660 2661 // A live segment can only end at an early-clobber slot if it is being 2662 // redefined by an early-clobber def. 2663 if (S.end.isEarlyClobber()) { 2664 if (I+1 == LR.end() || (I+1)->start != S.end) { 2665 report("Live segment ending at early clobber slot must be " 2666 "redefined by an EC def in the same instruction", EndMBB); 2667 report_context(LR, Reg, LaneMask); 2668 report_context(S); 2669 } 2670 } 2671 2672 // The following checks only apply to virtual registers. Physreg liveness 2673 // is too weird to check. 2674 if (Register::isVirtualRegister(Reg)) { 2675 // A live segment can end with either a redefinition, a kill flag on a 2676 // use, or a dead flag on a def. 2677 bool hasRead = false; 2678 bool hasSubRegDef = false; 2679 bool hasDeadDef = false; 2680 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) { 2681 if (!MOI->isReg() || MOI->getReg() != Reg) 2682 continue; 2683 unsigned Sub = MOI->getSubReg(); 2684 LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub) 2685 : LaneBitmask::getAll(); 2686 if (MOI->isDef()) { 2687 if (Sub != 0) { 2688 hasSubRegDef = true; 2689 // An operand %0:sub0 reads %0:sub1..n. Invert the lane 2690 // mask for subregister defs. Read-undef defs will be handled by 2691 // readsReg below. 2692 SLM = ~SLM; 2693 } 2694 if (MOI->isDead()) 2695 hasDeadDef = true; 2696 } 2697 if (LaneMask.any() && (LaneMask & SLM).none()) 2698 continue; 2699 if (MOI->readsReg()) 2700 hasRead = true; 2701 } 2702 if (S.end.isDead()) { 2703 // Make sure that the corresponding machine operand for a "dead" live 2704 // range has the dead flag. We cannot perform this check for subregister 2705 // liveranges as partially dead values are allowed. 2706 if (LaneMask.none() && !hasDeadDef) { 2707 report("Instruction ending live segment on dead slot has no dead flag", 2708 MI); 2709 report_context(LR, Reg, LaneMask); 2710 report_context(S); 2711 } 2712 } else { 2713 if (!hasRead) { 2714 // When tracking subregister liveness, the main range must start new 2715 // values on partial register writes, even if there is no read. 2716 if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() || 2717 !hasSubRegDef) { 2718 report("Instruction ending live segment doesn't read the register", 2719 MI); 2720 report_context(LR, Reg, LaneMask); 2721 report_context(S); 2722 } 2723 } 2724 } 2725 } 2726 2727 // Now check all the basic blocks in this live segment. 2728 MachineFunction::const_iterator MFI = MBB->getIterator(); 2729 // Is this live segment the beginning of a non-PHIDef VN? 2730 if (S.start == VNI->def && !VNI->isPHIDef()) { 2731 // Not live-in to any blocks. 2732 if (MBB == EndMBB) 2733 return; 2734 // Skip this block. 2735 ++MFI; 2736 } 2737 2738 SmallVector<SlotIndex, 4> Undefs; 2739 if (LaneMask.any()) { 2740 LiveInterval &OwnerLI = LiveInts->getInterval(Reg); 2741 OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes); 2742 } 2743 2744 while (true) { 2745 assert(LiveInts->isLiveInToMBB(LR, &*MFI)); 2746 // We don't know how to track physregs into a landing pad. 2747 if (!Register::isVirtualRegister(Reg) && MFI->isEHPad()) { 2748 if (&*MFI == EndMBB) 2749 break; 2750 ++MFI; 2751 continue; 2752 } 2753 2754 // Is VNI a PHI-def in the current block? 2755 bool IsPHI = VNI->isPHIDef() && 2756 VNI->def == LiveInts->getMBBStartIdx(&*MFI); 2757 2758 // Check that VNI is live-out of all predecessors. 2759 for (const MachineBasicBlock *Pred : MFI->predecessors()) { 2760 SlotIndex PEnd = LiveInts->getMBBEndIdx(Pred); 2761 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd); 2762 2763 // All predecessors must have a live-out value. However for a phi 2764 // instruction with subregister intervals 2765 // only one of the subregisters (not necessarily the current one) needs to 2766 // be defined. 2767 if (!PVNI && (LaneMask.none() || !IsPHI)) { 2768 if (LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes)) 2769 continue; 2770 report("Register not marked live out of predecessor", Pred); 2771 report_context(LR, Reg, LaneMask); 2772 report_context(*VNI); 2773 errs() << " live into " << printMBBReference(*MFI) << '@' 2774 << LiveInts->getMBBStartIdx(&*MFI) << ", not live before " 2775 << PEnd << '\n'; 2776 continue; 2777 } 2778 2779 // Only PHI-defs can take different predecessor values. 2780 if (!IsPHI && PVNI != VNI) { 2781 report("Different value live out of predecessor", Pred); 2782 report_context(LR, Reg, LaneMask); 2783 errs() << "Valno #" << PVNI->id << " live out of " 2784 << printMBBReference(*Pred) << '@' << PEnd << "\nValno #" 2785 << VNI->id << " live into " << printMBBReference(*MFI) << '@' 2786 << LiveInts->getMBBStartIdx(&*MFI) << '\n'; 2787 } 2788 } 2789 if (&*MFI == EndMBB) 2790 break; 2791 ++MFI; 2792 } 2793 } 2794 2795 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg, 2796 LaneBitmask LaneMask) { 2797 for (const VNInfo *VNI : LR.valnos) 2798 verifyLiveRangeValue(LR, VNI, Reg, LaneMask); 2799 2800 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I) 2801 verifyLiveRangeSegment(LR, I, Reg, LaneMask); 2802 } 2803 2804 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) { 2805 unsigned Reg = LI.reg; 2806 assert(Register::isVirtualRegister(Reg)); 2807 verifyLiveRange(LI, Reg); 2808 2809 LaneBitmask Mask; 2810 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg); 2811 for (const LiveInterval::SubRange &SR : LI.subranges()) { 2812 if ((Mask & SR.LaneMask).any()) { 2813 report("Lane masks of sub ranges overlap in live interval", MF); 2814 report_context(LI); 2815 } 2816 if ((SR.LaneMask & ~MaxMask).any()) { 2817 report("Subrange lanemask is invalid", MF); 2818 report_context(LI); 2819 } 2820 if (SR.empty()) { 2821 report("Subrange must not be empty", MF); 2822 report_context(SR, LI.reg, SR.LaneMask); 2823 } 2824 Mask |= SR.LaneMask; 2825 verifyLiveRange(SR, LI.reg, SR.LaneMask); 2826 if (!LI.covers(SR)) { 2827 report("A Subrange is not covered by the main range", MF); 2828 report_context(LI); 2829 } 2830 } 2831 2832 // Check the LI only has one connected component. 2833 ConnectedVNInfoEqClasses ConEQ(*LiveInts); 2834 unsigned NumComp = ConEQ.Classify(LI); 2835 if (NumComp > 1) { 2836 report("Multiple connected components in live interval", MF); 2837 report_context(LI); 2838 for (unsigned comp = 0; comp != NumComp; ++comp) { 2839 errs() << comp << ": valnos"; 2840 for (const VNInfo *I : LI.valnos) 2841 if (comp == ConEQ.getEqClass(I)) 2842 errs() << ' ' << I->id; 2843 errs() << '\n'; 2844 } 2845 } 2846 } 2847 2848 namespace { 2849 2850 // FrameSetup and FrameDestroy can have zero adjustment, so using a single 2851 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the 2852 // value is zero. 2853 // We use a bool plus an integer to capture the stack state. 2854 struct StackStateOfBB { 2855 StackStateOfBB() = default; 2856 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) : 2857 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup), 2858 ExitIsSetup(ExitSetup) {} 2859 2860 // Can be negative, which means we are setting up a frame. 2861 int EntryValue = 0; 2862 int ExitValue = 0; 2863 bool EntryIsSetup = false; 2864 bool ExitIsSetup = false; 2865 }; 2866 2867 } // end anonymous namespace 2868 2869 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed 2870 /// by a FrameDestroy <n>, stack adjustments are identical on all 2871 /// CFG edges to a merge point, and frame is destroyed at end of a return block. 2872 void MachineVerifier::verifyStackFrame() { 2873 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode(); 2874 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode(); 2875 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u) 2876 return; 2877 2878 SmallVector<StackStateOfBB, 8> SPState; 2879 SPState.resize(MF->getNumBlockIDs()); 2880 df_iterator_default_set<const MachineBasicBlock*> Reachable; 2881 2882 // Visit the MBBs in DFS order. 2883 for (df_ext_iterator<const MachineFunction *, 2884 df_iterator_default_set<const MachineBasicBlock *>> 2885 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable); 2886 DFI != DFE; ++DFI) { 2887 const MachineBasicBlock *MBB = *DFI; 2888 2889 StackStateOfBB BBState; 2890 // Check the exit state of the DFS stack predecessor. 2891 if (DFI.getPathLength() >= 2) { 2892 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2); 2893 assert(Reachable.count(StackPred) && 2894 "DFS stack predecessor is already visited.\n"); 2895 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue; 2896 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup; 2897 BBState.ExitValue = BBState.EntryValue; 2898 BBState.ExitIsSetup = BBState.EntryIsSetup; 2899 } 2900 2901 // Update stack state by checking contents of MBB. 2902 for (const auto &I : *MBB) { 2903 if (I.getOpcode() == FrameSetupOpcode) { 2904 if (BBState.ExitIsSetup) 2905 report("FrameSetup is after another FrameSetup", &I); 2906 BBState.ExitValue -= TII->getFrameTotalSize(I); 2907 BBState.ExitIsSetup = true; 2908 } 2909 2910 if (I.getOpcode() == FrameDestroyOpcode) { 2911 int Size = TII->getFrameTotalSize(I); 2912 if (!BBState.ExitIsSetup) 2913 report("FrameDestroy is not after a FrameSetup", &I); 2914 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue : 2915 BBState.ExitValue; 2916 if (BBState.ExitIsSetup && AbsSPAdj != Size) { 2917 report("FrameDestroy <n> is after FrameSetup <m>", &I); 2918 errs() << "FrameDestroy <" << Size << "> is after FrameSetup <" 2919 << AbsSPAdj << ">.\n"; 2920 } 2921 BBState.ExitValue += Size; 2922 BBState.ExitIsSetup = false; 2923 } 2924 } 2925 SPState[MBB->getNumber()] = BBState; 2926 2927 // Make sure the exit state of any predecessor is consistent with the entry 2928 // state. 2929 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 2930 if (Reachable.count(Pred) && 2931 (SPState[Pred->getNumber()].ExitValue != BBState.EntryValue || 2932 SPState[Pred->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) { 2933 report("The exit stack state of a predecessor is inconsistent.", MBB); 2934 errs() << "Predecessor " << printMBBReference(*Pred) 2935 << " has exit state (" << SPState[Pred->getNumber()].ExitValue 2936 << ", " << SPState[Pred->getNumber()].ExitIsSetup << "), while " 2937 << printMBBReference(*MBB) << " has entry state (" 2938 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n"; 2939 } 2940 } 2941 2942 // Make sure the entry state of any successor is consistent with the exit 2943 // state. 2944 for (const MachineBasicBlock *Succ : MBB->successors()) { 2945 if (Reachable.count(Succ) && 2946 (SPState[Succ->getNumber()].EntryValue != BBState.ExitValue || 2947 SPState[Succ->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) { 2948 report("The entry stack state of a successor is inconsistent.", MBB); 2949 errs() << "Successor " << printMBBReference(*Succ) 2950 << " has entry state (" << SPState[Succ->getNumber()].EntryValue 2951 << ", " << SPState[Succ->getNumber()].EntryIsSetup << "), while " 2952 << printMBBReference(*MBB) << " has exit state (" 2953 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n"; 2954 } 2955 } 2956 2957 // Make sure a basic block with return ends with zero stack adjustment. 2958 if (!MBB->empty() && MBB->back().isReturn()) { 2959 if (BBState.ExitIsSetup) 2960 report("A return block ends with a FrameSetup.", MBB); 2961 if (BBState.ExitValue) 2962 report("A return block ends with a nonzero stack adjustment.", MBB); 2963 } 2964 } 2965 } 2966