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