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