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