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