1 //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Pass to verify generated machine code. The following is checked:
12 // Operand counts: All explicit operands must be present.
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
20 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
21 // command-line option -verify-machineinstrs, or by defining the environment
22 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
23 // the verifier errors.
24 //===----------------------------------------------------------------------===//
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/SetOperations.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
32 #include "llvm/CodeGen/LiveStackAnalysis.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/InlineAsm.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/MC/MCAsmInfo.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
53 struct MachineVerifier {
55 MachineVerifier(Pass *pass, const char *b) :
58 OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
61 bool runOnMachineFunction(MachineFunction &MF);
65 const char *const OutFileName;
67 const MachineFunction *MF;
68 const TargetMachine *TM;
69 const TargetInstrInfo *TII;
70 const TargetRegisterInfo *TRI;
71 const MachineRegisterInfo *MRI;
75 typedef SmallVector<unsigned, 16> RegVector;
76 typedef SmallVector<const uint32_t*, 4> RegMaskVector;
77 typedef DenseSet<unsigned> RegSet;
78 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
79 typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet;
81 const MachineInstr *FirstTerminator;
82 BlockSet FunctionBlocks;
84 BitVector regsReserved;
86 RegVector regsDefined, regsDead, regsKilled;
87 RegMaskVector regMasks;
88 RegSet regsLiveInButUnused;
92 // Add Reg and any sub-registers to RV
93 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
95 if (TargetRegisterInfo::isPhysicalRegister(Reg))
96 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
97 RV.push_back(*SubRegs);
101 // Is this MBB reachable from the MF entry point?
104 // Vregs that must be live in because they are used without being
105 // defined. Map value is the user.
108 // Regs killed in MBB. They may be defined again, and will then be in both
109 // regsKilled and regsLiveOut.
112 // Regs defined in MBB and live out. Note that vregs passing through may
113 // be live out without being mentioned here.
116 // Vregs that pass through MBB untouched. This set is disjoint from
117 // regsKilled and regsLiveOut.
120 // Vregs that must pass through MBB because they are needed by a successor
121 // block. This set is disjoint from regsLiveOut.
122 RegSet vregsRequired;
124 // Set versions of block's predecessor and successor lists.
125 BlockSet Preds, Succs;
127 BBInfo() : reachable(false) {}
129 // Add register to vregsPassed if it belongs there. Return true if
131 bool addPassed(unsigned Reg) {
132 if (!TargetRegisterInfo::isVirtualRegister(Reg))
134 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
136 return vregsPassed.insert(Reg).second;
139 // Same for a full set.
140 bool addPassed(const RegSet &RS) {
141 bool changed = false;
142 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
148 // Add register to vregsRequired if it belongs there. Return true if
150 bool addRequired(unsigned Reg) {
151 if (!TargetRegisterInfo::isVirtualRegister(Reg))
153 if (regsLiveOut.count(Reg))
155 return vregsRequired.insert(Reg).second;
158 // Same for a full set.
159 bool addRequired(const RegSet &RS) {
160 bool changed = false;
161 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
167 // Same for a full map.
168 bool addRequired(const RegMap &RM) {
169 bool changed = false;
170 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
171 if (addRequired(I->first))
176 // Live-out registers are either in regsLiveOut or vregsPassed.
177 bool isLiveOut(unsigned Reg) const {
178 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
182 // Extra register info per MBB.
183 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
185 bool isReserved(unsigned Reg) {
186 return Reg < regsReserved.size() && regsReserved.test(Reg);
189 bool isAllocatable(unsigned Reg) {
190 return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg);
193 // Analysis information if available
194 LiveVariables *LiveVars;
195 LiveIntervals *LiveInts;
196 LiveStacks *LiveStks;
197 SlotIndexes *Indexes;
199 void visitMachineFunctionBefore();
200 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
201 void visitMachineBundleBefore(const MachineInstr *MI);
202 void visitMachineInstrBefore(const MachineInstr *MI);
203 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
204 void visitMachineInstrAfter(const MachineInstr *MI);
205 void visitMachineBundleAfter(const MachineInstr *MI);
206 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
207 void visitMachineFunctionAfter();
209 void report(const char *msg, const MachineFunction *MF);
210 void report(const char *msg, const MachineBasicBlock *MBB);
211 void report(const char *msg, const MachineInstr *MI);
212 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
213 void report(const char *msg, const MachineFunction *MF,
214 const LiveInterval &LI);
215 void report(const char *msg, const MachineBasicBlock *MBB,
216 const LiveInterval &LI);
217 void report(const char *msg, const MachineFunction *MF,
218 const LiveRange &LR, unsigned Reg);
219 void report(const char *msg, const MachineBasicBlock *MBB,
220 const LiveRange &LR, unsigned Reg);
222 void verifyInlineAsm(const MachineInstr *MI);
224 void checkLiveness(const MachineOperand *MO, unsigned MONum);
225 void markReachable(const MachineBasicBlock *MBB);
226 void calcRegsPassed();
227 void checkPHIOps(const MachineBasicBlock *MBB);
229 void calcRegsRequired();
230 void verifyLiveVariables();
231 void verifyLiveIntervals();
232 void verifyLiveInterval(const LiveInterval&);
233 void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned);
234 void verifyLiveRangeSegment(const LiveRange&,
235 const LiveRange::const_iterator I, unsigned);
236 void verifyLiveRange(const LiveRange&, unsigned);
238 void verifyStackFrame();
241 struct MachineVerifierPass : public MachineFunctionPass {
242 static char ID; // Pass ID, replacement for typeid
243 const char *const Banner;
245 MachineVerifierPass(const char *b = nullptr)
246 : MachineFunctionPass(ID), Banner(b) {
247 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
250 void getAnalysisUsage(AnalysisUsage &AU) const override {
251 AU.setPreservesAll();
252 MachineFunctionPass::getAnalysisUsage(AU);
255 bool runOnMachineFunction(MachineFunction &MF) override {
256 MF.verify(this, Banner);
263 char MachineVerifierPass::ID = 0;
264 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
265 "Verify generated machine code", false, false)
267 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
268 return new MachineVerifierPass(Banner);
271 void MachineFunction::verify(Pass *p, const char *Banner) const {
272 MachineVerifier(p, Banner)
273 .runOnMachineFunction(const_cast<MachineFunction&>(*this));
276 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
277 raw_ostream *OutFile = nullptr;
280 OutFile = new raw_fd_ostream(OutFileName, EC,
281 sys::fs::F_Append | sys::fs::F_Text);
283 errs() << "Error opening '" << OutFileName << "': " << EC.message()
296 TM = &MF.getTarget();
297 TII = MF.getSubtarget().getInstrInfo();
298 TRI = MF.getSubtarget().getRegisterInfo();
299 MRI = &MF.getRegInfo();
306 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
307 // We don't want to verify LiveVariables if LiveIntervals is available.
309 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
310 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
311 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
314 visitMachineFunctionBefore();
315 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
317 visitMachineBasicBlockBefore(MFI);
318 // Keep track of the current bundle header.
319 const MachineInstr *CurBundle = nullptr;
320 // Do we expect the next instruction to be part of the same bundle?
321 bool InBundle = false;
323 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
324 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
325 if (MBBI->getParent() != MFI) {
326 report("Bad instruction parent pointer", MFI);
327 *OS << "Instruction: " << *MBBI;
331 // Check for consistent bundle flags.
332 if (InBundle && !MBBI->isBundledWithPred())
333 report("Missing BundledPred flag, "
334 "BundledSucc was set on predecessor", MBBI);
335 if (!InBundle && MBBI->isBundledWithPred())
336 report("BundledPred flag is set, "
337 "but BundledSucc not set on predecessor", MBBI);
339 // Is this a bundle header?
340 if (!MBBI->isInsideBundle()) {
342 visitMachineBundleAfter(CurBundle);
344 visitMachineBundleBefore(CurBundle);
345 } else if (!CurBundle)
346 report("No bundle header", MBBI);
347 visitMachineInstrBefore(MBBI);
348 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
349 visitMachineOperand(&MBBI->getOperand(I), I);
350 visitMachineInstrAfter(MBBI);
352 // Was this the last bundled instruction?
353 InBundle = MBBI->isBundledWithSucc();
356 visitMachineBundleAfter(CurBundle);
358 report("BundledSucc flag set on last instruction in block", &MFI->back());
359 visitMachineBasicBlockAfter(MFI);
361 visitMachineFunctionAfter();
365 else if (foundErrors)
366 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
374 regsLiveInButUnused.clear();
377 return false; // no changes
380 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
383 if (!foundErrors++) {
385 *OS << "# " << Banner << '\n';
386 MF->print(*OS, Indexes);
388 *OS << "*** Bad machine code: " << msg << " ***\n"
389 << "- function: " << MF->getName() << "\n";
392 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
394 report(msg, MBB->getParent());
395 *OS << "- basic block: BB#" << MBB->getNumber()
396 << ' ' << MBB->getName()
397 << " (" << (const void*)MBB << ')';
399 *OS << " [" << Indexes->getMBBStartIdx(MBB)
400 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
404 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
406 report(msg, MI->getParent());
407 *OS << "- instruction: ";
408 if (Indexes && Indexes->hasIndex(MI))
409 *OS << Indexes->getInstructionIndex(MI) << '\t';
413 void MachineVerifier::report(const char *msg,
414 const MachineOperand *MO, unsigned MONum) {
416 report(msg, MO->getParent());
417 *OS << "- operand " << MONum << ": ";
422 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
423 const LiveInterval &LI) {
425 *OS << "- interval: " << LI << '\n';
428 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
429 const LiveInterval &LI) {
431 *OS << "- interval: " << LI << '\n';
434 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
435 const LiveRange &LR, unsigned Reg) {
437 *OS << "- liverange: " << LR << '\n';
438 *OS << "- register: " << PrintReg(Reg, TRI) << '\n';
441 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
442 const LiveRange &LR, unsigned Reg) {
444 *OS << "- liverange: " << LR << '\n';
445 *OS << "- register: " << PrintReg(Reg, TRI) << '\n';
448 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
449 BBInfo &MInfo = MBBInfoMap[MBB];
450 if (!MInfo.reachable) {
451 MInfo.reachable = true;
452 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
453 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
458 void MachineVerifier::visitMachineFunctionBefore() {
459 lastIndex = SlotIndex();
460 regsReserved = MRI->getReservedRegs();
462 // A sub-register of a reserved register is also reserved
463 for (int Reg = regsReserved.find_first(); Reg>=0;
464 Reg = regsReserved.find_next(Reg)) {
465 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
466 // FIXME: This should probably be:
467 // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register");
468 regsReserved.set(*SubRegs);
472 markReachable(&MF->front());
474 // Build a set of the basic blocks in the function.
475 FunctionBlocks.clear();
476 for (const auto &MBB : *MF) {
477 FunctionBlocks.insert(&MBB);
478 BBInfo &MInfo = MBBInfoMap[&MBB];
480 MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
481 if (MInfo.Preds.size() != MBB.pred_size())
482 report("MBB has duplicate entries in its predecessor list.", &MBB);
484 MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
485 if (MInfo.Succs.size() != MBB.succ_size())
486 report("MBB has duplicate entries in its successor list.", &MBB);
489 // Check that the register use lists are sane.
490 MRI->verifyUseLists();
495 // Does iterator point to a and b as the first two elements?
496 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
497 const MachineBasicBlock *a, const MachineBasicBlock *b) {
506 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
507 FirstTerminator = nullptr;
510 // If this block has allocatable physical registers live-in, check that
511 // it is an entry block or landing pad.
512 for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
513 LE = MBB->livein_end();
516 if (isAllocatable(reg) && !MBB->isLandingPad() &&
517 MBB != MBB->getParent()->begin()) {
518 report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
523 // Count the number of landing pad successors.
524 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
525 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
526 E = MBB->succ_end(); I != E; ++I) {
527 if ((*I)->isLandingPad())
528 LandingPadSuccs.insert(*I);
529 if (!FunctionBlocks.count(*I))
530 report("MBB has successor that isn't part of the function.", MBB);
531 if (!MBBInfoMap[*I].Preds.count(MBB)) {
532 report("Inconsistent CFG", MBB);
533 *OS << "MBB is not in the predecessor list of the successor BB#"
534 << (*I)->getNumber() << ".\n";
538 // Check the predecessor list.
539 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
540 E = MBB->pred_end(); I != E; ++I) {
541 if (!FunctionBlocks.count(*I))
542 report("MBB has predecessor that isn't part of the function.", MBB);
543 if (!MBBInfoMap[*I].Succs.count(MBB)) {
544 report("Inconsistent CFG", MBB);
545 *OS << "MBB is not in the successor list of the predecessor BB#"
546 << (*I)->getNumber() << ".\n";
550 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
551 const BasicBlock *BB = MBB->getBasicBlock();
552 if (LandingPadSuccs.size() > 1 &&
554 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
555 BB && isa<SwitchInst>(BB->getTerminator())))
556 report("MBB has more than one landing pad successor", MBB);
558 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
559 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
560 SmallVector<MachineOperand, 4> Cond;
561 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
563 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
564 // check whether its answers match up with reality.
566 // Block falls through to its successor.
567 MachineFunction::const_iterator MBBI = MBB;
569 if (MBBI == MF->end()) {
570 // It's possible that the block legitimately ends with a noreturn
571 // call or an unreachable, in which case it won't actually fall
572 // out the bottom of the function.
573 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
574 // It's possible that the block legitimately ends with a noreturn
575 // call or an unreachable, in which case it won't actuall fall
577 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
578 report("MBB exits via unconditional fall-through but doesn't have "
579 "exactly one CFG successor!", MBB);
580 } else if (!MBB->isSuccessor(MBBI)) {
581 report("MBB exits via unconditional fall-through but its successor "
582 "differs from its CFG successor!", MBB);
584 if (!MBB->empty() && MBB->back().isBarrier() &&
585 !TII->isPredicated(&MBB->back())) {
586 report("MBB exits via unconditional fall-through but ends with a "
587 "barrier instruction!", MBB);
590 report("MBB exits via unconditional fall-through but has a condition!",
593 } else if (TBB && !FBB && Cond.empty()) {
594 // Block unconditionally branches somewhere.
595 if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
596 report("MBB exits via unconditional branch but doesn't have "
597 "exactly one CFG successor!", MBB);
598 } else if (!MBB->isSuccessor(TBB)) {
599 report("MBB exits via unconditional branch but the CFG "
600 "successor doesn't match the actual successor!", MBB);
603 report("MBB exits via unconditional branch but doesn't contain "
604 "any instructions!", MBB);
605 } else if (!MBB->back().isBarrier()) {
606 report("MBB exits via unconditional branch but doesn't end with a "
607 "barrier instruction!", MBB);
608 } else if (!MBB->back().isTerminator()) {
609 report("MBB exits via unconditional branch but the branch isn't a "
610 "terminator instruction!", MBB);
612 } else if (TBB && !FBB && !Cond.empty()) {
613 // Block conditionally branches somewhere, otherwise falls through.
614 MachineFunction::const_iterator MBBI = MBB;
616 if (MBBI == MF->end()) {
617 report("MBB conditionally falls through out of function!", MBB);
618 } else if (MBB->succ_size() == 1) {
619 // A conditional branch with only one successor is weird, but allowed.
621 report("MBB exits via conditional branch/fall-through but only has "
622 "one CFG successor!", MBB);
623 else if (TBB != *MBB->succ_begin())
624 report("MBB exits via conditional branch/fall-through but the CFG "
625 "successor don't match the actual successor!", MBB);
626 } else if (MBB->succ_size() != 2) {
627 report("MBB exits via conditional branch/fall-through but doesn't have "
628 "exactly two CFG successors!", MBB);
629 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
630 report("MBB exits via conditional branch/fall-through but the CFG "
631 "successors don't match the actual successors!", MBB);
634 report("MBB exits via conditional branch/fall-through but doesn't "
635 "contain any instructions!", MBB);
636 } else if (MBB->back().isBarrier()) {
637 report("MBB exits via conditional branch/fall-through but ends with a "
638 "barrier instruction!", MBB);
639 } else if (!MBB->back().isTerminator()) {
640 report("MBB exits via conditional branch/fall-through but the branch "
641 "isn't a terminator instruction!", MBB);
643 } else if (TBB && FBB) {
644 // Block conditionally branches somewhere, otherwise branches
646 if (MBB->succ_size() == 1) {
647 // A conditional branch with only one successor is weird, but allowed.
649 report("MBB exits via conditional branch/branch through but only has "
650 "one CFG successor!", MBB);
651 else if (TBB != *MBB->succ_begin())
652 report("MBB exits via conditional branch/branch through but the CFG "
653 "successor don't match the actual successor!", MBB);
654 } else if (MBB->succ_size() != 2) {
655 report("MBB exits via conditional branch/branch but doesn't have "
656 "exactly two CFG successors!", MBB);
657 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
658 report("MBB exits via conditional branch/branch but the CFG "
659 "successors don't match the actual successors!", MBB);
662 report("MBB exits via conditional branch/branch but doesn't "
663 "contain any instructions!", MBB);
664 } else if (!MBB->back().isBarrier()) {
665 report("MBB exits via conditional branch/branch but doesn't end with a "
666 "barrier instruction!", MBB);
667 } else if (!MBB->back().isTerminator()) {
668 report("MBB exits via conditional branch/branch but the branch "
669 "isn't a terminator instruction!", MBB);
672 report("MBB exits via conditinal branch/branch but there's no "
676 report("AnalyzeBranch returned invalid data!", MBB);
681 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
682 E = MBB->livein_end(); I != E; ++I) {
683 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
684 report("MBB live-in list contains non-physical register", MBB);
687 for (MCSubRegIterator SubRegs(*I, TRI, /*IncludeSelf=*/true);
688 SubRegs.isValid(); ++SubRegs)
689 regsLive.insert(*SubRegs);
691 regsLiveInButUnused = regsLive;
693 const MachineFrameInfo *MFI = MF->getFrameInfo();
694 assert(MFI && "Function has no frame info");
695 BitVector PR = MFI->getPristineRegs(MBB);
696 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
697 for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
698 SubRegs.isValid(); ++SubRegs)
699 regsLive.insert(*SubRegs);
706 lastIndex = Indexes->getMBBStartIdx(MBB);
709 // This function gets called for all bundle headers, including normal
710 // stand-alone unbundled instructions.
711 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
712 if (Indexes && Indexes->hasIndex(MI)) {
713 SlotIndex idx = Indexes->getInstructionIndex(MI);
714 if (!(idx > lastIndex)) {
715 report("Instruction index out of order", MI);
716 *OS << "Last instruction was at " << lastIndex << '\n';
721 // Ensure non-terminators don't follow terminators.
722 // Ignore predicated terminators formed by if conversion.
723 // FIXME: If conversion shouldn't need to violate this rule.
724 if (MI->isTerminator() && !TII->isPredicated(MI)) {
725 if (!FirstTerminator)
726 FirstTerminator = MI;
727 } else if (FirstTerminator) {
728 report("Non-terminator instruction after the first terminator", MI);
729 *OS << "First terminator was:\t" << *FirstTerminator;
733 // The operands on an INLINEASM instruction must follow a template.
734 // Verify that the flag operands make sense.
735 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
736 // The first two operands on INLINEASM are the asm string and global flags.
737 if (MI->getNumOperands() < 2) {
738 report("Too few operands on inline asm", MI);
741 if (!MI->getOperand(0).isSymbol())
742 report("Asm string must be an external symbol", MI);
743 if (!MI->getOperand(1).isImm())
744 report("Asm flags must be an immediate", MI);
745 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
746 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16.
747 if (!isUInt<5>(MI->getOperand(1).getImm()))
748 report("Unknown asm flags", &MI->getOperand(1), 1);
750 assert(InlineAsm::MIOp_FirstOperand == 2 && "Asm format changed");
752 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
754 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
755 const MachineOperand &MO = MI->getOperand(OpNo);
756 // There may be implicit ops after the fixed operands.
759 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
762 if (OpNo > MI->getNumOperands())
763 report("Missing operands in last group", MI);
765 // An optional MDNode follows the groups.
766 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
769 // All trailing operands must be implicit registers.
770 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
771 const MachineOperand &MO = MI->getOperand(OpNo);
772 if (!MO.isReg() || !MO.isImplicit())
773 report("Expected implicit register after groups", &MO, OpNo);
777 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
778 const MCInstrDesc &MCID = MI->getDesc();
779 if (MI->getNumOperands() < MCID.getNumOperands()) {
780 report("Too few operands", MI);
781 *OS << MCID.getNumOperands() << " operands expected, but "
782 << MI->getNumOperands() << " given.\n";
785 // Check the tied operands.
786 if (MI->isInlineAsm())
789 // Check the MachineMemOperands for basic consistency.
790 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
791 E = MI->memoperands_end(); I != E; ++I) {
792 if ((*I)->isLoad() && !MI->mayLoad())
793 report("Missing mayLoad flag", MI);
794 if ((*I)->isStore() && !MI->mayStore())
795 report("Missing mayStore flag", MI);
798 // Debug values must not have a slot index.
799 // Other instructions must have one, unless they are inside a bundle.
801 bool mapped = !LiveInts->isNotInMIMap(MI);
802 if (MI->isDebugValue()) {
804 report("Debug instruction has a slot index", MI);
805 } else if (MI->isInsideBundle()) {
807 report("Instruction inside bundle has a slot index", MI);
810 report("Missing slot index", MI);
815 if (!TII->verifyInstruction(MI, ErrorInfo))
816 report(ErrorInfo.data(), MI);
820 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
821 const MachineInstr *MI = MO->getParent();
822 const MCInstrDesc &MCID = MI->getDesc();
824 // The first MCID.NumDefs operands must be explicit register defines
825 if (MONum < MCID.getNumDefs()) {
826 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
828 report("Explicit definition must be a register", MO, MONum);
829 else if (!MO->isDef() && !MCOI.isOptionalDef())
830 report("Explicit definition marked as use", MO, MONum);
831 else if (MO->isImplicit())
832 report("Explicit definition marked as implicit", MO, MONum);
833 } else if (MONum < MCID.getNumOperands()) {
834 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
835 // Don't check if it's the last operand in a variadic instruction. See,
836 // e.g., LDM_RET in the arm back end.
838 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
839 if (MO->isDef() && !MCOI.isOptionalDef())
840 report("Explicit operand marked as def", MO, MONum);
841 if (MO->isImplicit())
842 report("Explicit operand marked as implicit", MO, MONum);
845 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
848 report("Tied use must be a register", MO, MONum);
849 else if (!MO->isTied())
850 report("Operand should be tied", MO, MONum);
851 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
852 report("Tied def doesn't match MCInstrDesc", MO, MONum);
853 } else if (MO->isReg() && MO->isTied())
854 report("Explicit operand should not be tied", MO, MONum);
856 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
857 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
858 report("Extra explicit operand on non-variadic instruction", MO, MONum);
861 switch (MO->getType()) {
862 case MachineOperand::MO_Register: {
863 const unsigned Reg = MO->getReg();
866 if (MRI->tracksLiveness() && !MI->isDebugValue())
867 checkLiveness(MO, MONum);
869 // Verify the consistency of tied operands.
871 unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
872 const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
873 if (!OtherMO.isReg())
874 report("Must be tied to a register", MO, MONum);
875 if (!OtherMO.isTied())
876 report("Missing tie flags on tied operand", MO, MONum);
877 if (MI->findTiedOperandIdx(OtherIdx) != MONum)
878 report("Inconsistent tie links", MO, MONum);
879 if (MONum < MCID.getNumDefs()) {
880 if (OtherIdx < MCID.getNumOperands()) {
881 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
882 report("Explicit def tied to explicit use without tie constraint",
885 if (!OtherMO.isImplicit())
886 report("Explicit def should be tied to implicit use", MO, MONum);
891 // Verify two-address constraints after leaving SSA form.
893 if (!MRI->isSSA() && MO->isUse() &&
894 MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
895 Reg != MI->getOperand(DefIdx).getReg())
896 report("Two-address instruction operands must be identical", MO, MONum);
898 // Check register classes.
899 if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
900 unsigned SubIdx = MO->getSubReg();
902 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
904 report("Illegal subregister index for physical register", MO, MONum);
907 if (const TargetRegisterClass *DRC =
908 TII->getRegClass(MCID, MONum, TRI, *MF)) {
909 if (!DRC->contains(Reg)) {
910 report("Illegal physical register for instruction", MO, MONum);
911 *OS << TRI->getName(Reg) << " is not a "
912 << TRI->getRegClassName(DRC) << " register.\n";
917 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
919 const TargetRegisterClass *SRC =
920 TRI->getSubClassWithSubReg(RC, SubIdx);
922 report("Invalid subregister index for virtual register", MO, MONum);
923 *OS << "Register class " << TRI->getRegClassName(RC)
924 << " does not support subreg index " << SubIdx << "\n";
928 report("Invalid register class for subregister index", MO, MONum);
929 *OS << "Register class " << TRI->getRegClassName(RC)
930 << " does not fully support subreg index " << SubIdx << "\n";
934 if (const TargetRegisterClass *DRC =
935 TII->getRegClass(MCID, MONum, TRI, *MF)) {
937 const TargetRegisterClass *SuperRC =
938 TRI->getLargestLegalSuperClass(RC);
940 report("No largest legal super class exists.", MO, MONum);
943 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
945 report("No matching super-reg register class.", MO, MONum);
949 if (!RC->hasSuperClassEq(DRC)) {
950 report("Illegal virtual register for instruction", MO, MONum);
951 *OS << "Expected a " << TRI->getRegClassName(DRC)
952 << " register, but got a " << TRI->getRegClassName(RC)
961 case MachineOperand::MO_RegisterMask:
962 regMasks.push_back(MO->getRegMask());
965 case MachineOperand::MO_MachineBasicBlock:
966 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
967 report("PHI operand is not in the CFG", MO, MONum);
970 case MachineOperand::MO_FrameIndex:
971 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
972 LiveInts && !LiveInts->isNotInMIMap(MI)) {
973 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
974 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
975 if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
976 report("Instruction loads from dead spill slot", MO, MONum);
977 *OS << "Live stack: " << LI << '\n';
979 if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
980 report("Instruction stores to dead spill slot", MO, MONum);
981 *OS << "Live stack: " << LI << '\n';
991 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
992 const MachineInstr *MI = MO->getParent();
993 const unsigned Reg = MO->getReg();
995 // Both use and def operands can read a register.
996 if (MO->readsReg()) {
997 regsLiveInButUnused.erase(Reg);
1000 addRegWithSubRegs(regsKilled, Reg);
1002 // Check that LiveVars knows this kill.
1003 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1005 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1006 if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end())
1007 report("Kill missing from LiveVariables", MO, MONum);
1010 // Check LiveInts liveness and kill.
1011 if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
1012 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI);
1013 // Check the cached regunit intervals.
1014 if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1015 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1016 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) {
1017 LiveQueryResult LRQ = LR->Query(UseIdx);
1018 if (!LRQ.valueIn()) {
1019 report("No live segment at use", MO, MONum);
1020 *OS << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI)
1021 << ' ' << *LR << '\n';
1023 if (MO->isKill() && !LRQ.isKill()) {
1024 report("Live range continues after kill flag", MO, MONum);
1025 *OS << PrintRegUnit(*Units, TRI) << ' ' << *LR << '\n';
1031 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1032 if (LiveInts->hasInterval(Reg)) {
1033 // This is a virtual register interval.
1034 const LiveInterval &LI = LiveInts->getInterval(Reg);
1035 LiveQueryResult LRQ = LI.Query(UseIdx);
1036 if (!LRQ.valueIn()) {
1037 report("No live segment at use", MO, MONum);
1038 *OS << UseIdx << " is not live in " << LI << '\n';
1040 // Check for extra kill flags.
1041 // Note that we allow missing kill flags for now.
1042 if (MO->isKill() && !LRQ.isKill()) {
1043 report("Live range continues after kill flag", MO, MONum);
1044 *OS << "Live range: " << LI << '\n';
1047 report("Virtual register has no live interval", MO, MONum);
1052 // Use of a dead register.
1053 if (!regsLive.count(Reg)) {
1054 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1055 // Reserved registers may be used even when 'dead'.
1056 if (!isReserved(Reg))
1057 report("Using an undefined physical register", MO, MONum);
1058 } else if (MRI->def_empty(Reg)) {
1059 report("Reading virtual register without a def", MO, MONum);
1061 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1062 // We don't know which virtual registers are live in, so only complain
1063 // if vreg was killed in this MBB. Otherwise keep track of vregs that
1064 // must be live in. PHI instructions are handled separately.
1065 if (MInfo.regsKilled.count(Reg))
1066 report("Using a killed virtual register", MO, MONum);
1067 else if (!MI->isPHI())
1068 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1074 // Register defined.
1075 // TODO: verify that earlyclobber ops are not used.
1077 addRegWithSubRegs(regsDead, Reg);
1079 addRegWithSubRegs(regsDefined, Reg);
1082 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1083 std::next(MRI->def_begin(Reg)) != MRI->def_end())
1084 report("Multiple virtual register defs in SSA form", MO, MONum);
1086 // Check LiveInts for a live segment, but only for virtual registers.
1087 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
1088 !LiveInts->isNotInMIMap(MI)) {
1089 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI);
1090 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1091 if (LiveInts->hasInterval(Reg)) {
1092 const LiveInterval &LI = LiveInts->getInterval(Reg);
1093 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
1094 assert(VNI && "NULL valno is not allowed");
1095 if (VNI->def != DefIdx) {
1096 report("Inconsistent valno->def", MO, MONum);
1097 *OS << "Valno " << VNI->id << " is not defined at "
1098 << DefIdx << " in " << LI << '\n';
1101 report("No live segment at def", MO, MONum);
1102 *OS << DefIdx << " is not live in " << LI << '\n';
1104 // Check that, if the dead def flag is present, LiveInts agree.
1106 LiveQueryResult LRQ = LI.Query(DefIdx);
1107 if (!LRQ.isDeadDef()) {
1108 report("Live range continues after dead def flag", MO, MONum);
1109 *OS << "Live range: " << LI << '\n';
1113 report("Virtual register has no Live interval", MO, MONum);
1119 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
1122 // This function gets called after visiting all instructions in a bundle. The
1123 // argument points to the bundle header.
1124 // Normal stand-alone instructions are also considered 'bundles', and this
1125 // function is called for all of them.
1126 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1127 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1128 set_union(MInfo.regsKilled, regsKilled);
1129 set_subtract(regsLive, regsKilled); regsKilled.clear();
1130 // Kill any masked registers.
1131 while (!regMasks.empty()) {
1132 const uint32_t *Mask = regMasks.pop_back_val();
1133 for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1134 if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1135 MachineOperand::clobbersPhysReg(Mask, *I))
1136 regsDead.push_back(*I);
1138 set_subtract(regsLive, regsDead); regsDead.clear();
1139 set_union(regsLive, regsDefined); regsDefined.clear();
1143 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1144 MBBInfoMap[MBB].regsLiveOut = regsLive;
1148 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1149 if (!(stop > lastIndex)) {
1150 report("Block ends before last instruction index", MBB);
1151 *OS << "Block ends at " << stop
1152 << " last instruction was at " << lastIndex << '\n';
1158 // Calculate the largest possible vregsPassed sets. These are the registers that
1159 // can pass through an MBB live, but may not be live every time. It is assumed
1160 // that all vregsPassed sets are empty before the call.
1161 void MachineVerifier::calcRegsPassed() {
1162 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1163 // have any vregsPassed.
1164 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1165 for (const auto &MBB : *MF) {
1166 BBInfo &MInfo = MBBInfoMap[&MBB];
1167 if (!MInfo.reachable)
1169 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1170 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1171 BBInfo &SInfo = MBBInfoMap[*SuI];
1172 if (SInfo.addPassed(MInfo.regsLiveOut))
1177 // Iteratively push vregsPassed to successors. This will converge to the same
1178 // final state regardless of DenseSet iteration order.
1179 while (!todo.empty()) {
1180 const MachineBasicBlock *MBB = *todo.begin();
1182 BBInfo &MInfo = MBBInfoMap[MBB];
1183 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1184 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1187 BBInfo &SInfo = MBBInfoMap[*SuI];
1188 if (SInfo.addPassed(MInfo.vregsPassed))
1194 // Calculate the set of virtual registers that must be passed through each basic
1195 // block in order to satisfy the requirements of successor blocks. This is very
1196 // similar to calcRegsPassed, only backwards.
1197 void MachineVerifier::calcRegsRequired() {
1198 // First push live-in regs to predecessors' vregsRequired.
1199 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1200 for (const auto &MBB : *MF) {
1201 BBInfo &MInfo = MBBInfoMap[&MBB];
1202 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1203 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1204 BBInfo &PInfo = MBBInfoMap[*PrI];
1205 if (PInfo.addRequired(MInfo.vregsLiveIn))
1210 // Iteratively push vregsRequired to predecessors. This will converge to the
1211 // same final state regardless of DenseSet iteration order.
1212 while (!todo.empty()) {
1213 const MachineBasicBlock *MBB = *todo.begin();
1215 BBInfo &MInfo = MBBInfoMap[MBB];
1216 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1217 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1220 BBInfo &SInfo = MBBInfoMap[*PrI];
1221 if (SInfo.addRequired(MInfo.vregsRequired))
1227 // Check PHI instructions at the beginning of MBB. It is assumed that
1228 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1229 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
1230 SmallPtrSet<const MachineBasicBlock*, 8> seen;
1231 for (const auto &BBI : *MBB) {
1236 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
1237 unsigned Reg = BBI.getOperand(i).getReg();
1238 const MachineBasicBlock *Pre = BBI.getOperand(i + 1).getMBB();
1239 if (!Pre->isSuccessor(MBB))
1242 BBInfo &PrInfo = MBBInfoMap[Pre];
1243 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
1244 report("PHI operand is not live-out from predecessor",
1245 &BBI.getOperand(i), i);
1248 // Did we see all predecessors?
1249 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1250 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1251 if (!seen.count(*PrI)) {
1252 report("Missing PHI operand", &BBI);
1253 *OS << "BB#" << (*PrI)->getNumber()
1254 << " is a predecessor according to the CFG.\n";
1260 void MachineVerifier::visitMachineFunctionAfter() {
1263 for (const auto &MBB : *MF) {
1264 BBInfo &MInfo = MBBInfoMap[&MBB];
1266 // Skip unreachable MBBs.
1267 if (!MInfo.reachable)
1273 // Now check liveness info if available
1276 // Check for killed virtual registers that should be live out.
1277 for (const auto &MBB : *MF) {
1278 BBInfo &MInfo = MBBInfoMap[&MBB];
1279 for (RegSet::iterator
1280 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1282 if (MInfo.regsKilled.count(*I)) {
1283 report("Virtual register killed in block, but needed live out.", &MBB);
1284 *OS << "Virtual register " << PrintReg(*I)
1285 << " is used after the block.\n";
1290 BBInfo &MInfo = MBBInfoMap[&MF->front()];
1291 for (RegSet::iterator
1292 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1294 report("Virtual register def doesn't dominate all uses.",
1295 MRI->getVRegDef(*I));
1299 verifyLiveVariables();
1301 verifyLiveIntervals();
1304 void MachineVerifier::verifyLiveVariables() {
1305 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1306 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1307 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1308 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1309 for (const auto &MBB : *MF) {
1310 BBInfo &MInfo = MBBInfoMap[&MBB];
1312 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1313 if (MInfo.vregsRequired.count(Reg)) {
1314 if (!VI.AliveBlocks.test(MBB.getNumber())) {
1315 report("LiveVariables: Block missing from AliveBlocks", &MBB);
1316 *OS << "Virtual register " << PrintReg(Reg)
1317 << " must be live through the block.\n";
1320 if (VI.AliveBlocks.test(MBB.getNumber())) {
1321 report("LiveVariables: Block should not be in AliveBlocks", &MBB);
1322 *OS << "Virtual register " << PrintReg(Reg)
1323 << " is not needed live through the block.\n";
1330 void MachineVerifier::verifyLiveIntervals() {
1331 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1332 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1333 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1335 // Spilling and splitting may leave unused registers around. Skip them.
1336 if (MRI->reg_nodbg_empty(Reg))
1339 if (!LiveInts->hasInterval(Reg)) {
1340 report("Missing live interval for virtual register", MF);
1341 *OS << PrintReg(Reg, TRI) << " still has defs or uses\n";
1345 const LiveInterval &LI = LiveInts->getInterval(Reg);
1346 assert(Reg == LI.reg && "Invalid reg to interval mapping");
1347 verifyLiveInterval(LI);
1350 // Verify all the cached regunit intervals.
1351 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1352 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1353 verifyLiveRange(*LR, i);
1356 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1359 if (VNI->isUnused())
1362 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1365 report("Valno not live at def and not marked unused", MF, LR, Reg);
1366 *OS << "Valno #" << VNI->id << '\n';
1370 if (DefVNI != VNI) {
1371 report("Live segment at def has different valno", MF, LR, Reg);
1372 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1373 << " where valno #" << DefVNI->id << " is live\n";
1377 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1379 report("Invalid definition index", MF, LR, Reg);
1380 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1381 << " in " << LR << '\n';
1385 if (VNI->isPHIDef()) {
1386 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1387 report("PHIDef value is not defined at MBB start", MBB, LR, Reg);
1388 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1389 << ", not at the beginning of BB#" << MBB->getNumber() << '\n';
1395 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1397 report("No instruction at def index", MBB, LR, Reg);
1398 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1403 bool hasDef = false;
1404 bool isEarlyClobber = false;
1405 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1406 if (!MOI->isReg() || !MOI->isDef())
1408 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1409 if (MOI->getReg() != Reg)
1412 if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1413 !TRI->hasRegUnit(MOI->getReg(), Reg))
1417 if (MOI->isEarlyClobber())
1418 isEarlyClobber = true;
1422 report("Defining instruction does not modify register", MI);
1423 *OS << "Valno #" << VNI->id << " in " << LR << '\n';
1426 // Early clobber defs begin at USE slots, but other defs must begin at
1428 if (isEarlyClobber) {
1429 if (!VNI->def.isEarlyClobber()) {
1430 report("Early clobber def must be at an early-clobber slot", MBB, LR,
1432 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1434 } else if (!VNI->def.isRegister()) {
1435 report("Non-PHI, non-early clobber def must be at a register slot",
1437 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1442 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1443 const LiveRange::const_iterator I,
1445 const LiveRange::Segment &S = *I;
1446 const VNInfo *VNI = S.valno;
1447 assert(VNI && "Live segment has no valno");
1449 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1450 report("Foreign valno in live segment", MF, LR, Reg);
1451 *OS << S << " has a bad valno\n";
1454 if (VNI->isUnused()) {
1455 report("Live segment valno is marked unused", MF, LR, Reg);
1459 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1461 report("Bad start of live segment, no basic block", MF, LR, Reg);
1465 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1466 if (S.start != MBBStartIdx && S.start != VNI->def) {
1467 report("Live segment must begin at MBB entry or valno def", MBB, LR, Reg);
1471 const MachineBasicBlock *EndMBB =
1472 LiveInts->getMBBFromIndex(S.end.getPrevSlot());
1474 report("Bad end of live segment, no basic block", MF, LR, Reg);
1479 // No more checks for live-out segments.
1480 if (S.end == LiveInts->getMBBEndIdx(EndMBB))
1483 // RegUnit intervals are allowed dead phis.
1484 if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
1485 S.start == VNI->def && S.end == VNI->def.getDeadSlot())
1488 // The live segment is ending inside EndMBB
1489 const MachineInstr *MI =
1490 LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
1492 report("Live segment doesn't end at a valid instruction", EndMBB, LR, Reg);
1497 // The block slot must refer to a basic block boundary.
1498 if (S.end.isBlock()) {
1499 report("Live segment ends at B slot of an instruction", EndMBB, LR, Reg);
1503 if (S.end.isDead()) {
1504 // Segment ends on the dead slot.
1505 // That means there must be a dead def.
1506 if (!SlotIndex::isSameInstr(S.start, S.end)) {
1507 report("Live segment ending at dead slot spans instructions", EndMBB, LR,
1513 // A live segment can only end at an early-clobber slot if it is being
1514 // redefined by an early-clobber def.
1515 if (S.end.isEarlyClobber()) {
1516 if (I+1 == LR.end() || (I+1)->start != S.end) {
1517 report("Live segment ending at early clobber slot must be "
1518 "redefined by an EC def in the same instruction", EndMBB, LR, Reg);
1523 // The following checks only apply to virtual registers. Physreg liveness
1524 // is too weird to check.
1525 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1526 // A live segment can end with either a redefinition, a kill flag on a
1527 // use, or a dead flag on a def.
1528 bool hasRead = false;
1529 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1530 if (!MOI->isReg() || MOI->getReg() != Reg)
1532 if (MOI->readsReg())
1535 if (!S.end.isDead()) {
1537 report("Instruction ending live segment doesn't read the register", MI);
1538 *OS << S << " in " << LR << '\n';
1543 // Now check all the basic blocks in this live segment.
1544 MachineFunction::const_iterator MFI = MBB;
1545 // Is this live segment the beginning of a non-PHIDef VN?
1546 if (S.start == VNI->def && !VNI->isPHIDef()) {
1547 // Not live-in to any blocks.
1554 assert(LiveInts->isLiveInToMBB(LR, MFI));
1555 // We don't know how to track physregs into a landing pad.
1556 if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
1557 MFI->isLandingPad()) {
1558 if (&*MFI == EndMBB)
1564 // Is VNI a PHI-def in the current block?
1565 bool IsPHI = VNI->isPHIDef() &&
1566 VNI->def == LiveInts->getMBBStartIdx(MFI);
1568 // Check that VNI is live-out of all predecessors.
1569 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1570 PE = MFI->pred_end(); PI != PE; ++PI) {
1571 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1572 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
1574 // All predecessors must have a live-out value.
1576 report("Register not marked live out of predecessor", *PI, LR, Reg);
1577 *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1578 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1583 // Only PHI-defs can take different predecessor values.
1584 if (!IsPHI && PVNI != VNI) {
1585 report("Different value live out of predecessor", *PI, LR, Reg);
1586 *OS << "Valno #" << PVNI->id << " live out of BB#"
1587 << (*PI)->getNumber() << '@' << PEnd
1588 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1589 << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
1592 if (&*MFI == EndMBB)
1598 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg) {
1599 for (LiveRange::const_vni_iterator I = LR.vni_begin(), E = LR.vni_end();
1601 verifyLiveRangeValue(LR, *I, Reg);
1603 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
1604 verifyLiveRangeSegment(LR, I, Reg);
1607 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
1608 verifyLiveRange(LI, LI.reg);
1610 // Check the LI only has one connected component.
1611 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1612 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1613 unsigned NumComp = ConEQ.Classify(&LI);
1615 report("Multiple connected components in live interval", MF, LI);
1616 for (unsigned comp = 0; comp != NumComp; ++comp) {
1617 *OS << comp << ": valnos";
1618 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1619 E = LI.vni_end(); I!=E; ++I)
1620 if (comp == ConEQ.getEqClass(*I))
1621 *OS << ' ' << (*I)->id;
1629 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
1630 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
1632 // We use a bool plus an integer to capture the stack state.
1633 struct StackStateOfBB {
1634 StackStateOfBB() : EntryValue(0), ExitValue(0), EntryIsSetup(false),
1635 ExitIsSetup(false) { }
1636 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
1637 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
1638 ExitIsSetup(ExitSetup) { }
1639 // Can be negative, which means we are setting up a frame.
1647 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
1648 /// by a FrameDestroy <n>, stack adjustments are identical on all
1649 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
1650 void MachineVerifier::verifyStackFrame() {
1651 int FrameSetupOpcode = TII->getCallFrameSetupOpcode();
1652 int FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
1654 SmallVector<StackStateOfBB, 8> SPState;
1655 SPState.resize(MF->getNumBlockIDs());
1656 SmallPtrSet<const MachineBasicBlock*, 8> Reachable;
1658 // Visit the MBBs in DFS order.
1659 for (df_ext_iterator<const MachineFunction*,
1660 SmallPtrSet<const MachineBasicBlock*, 8> >
1661 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
1662 DFI != DFE; ++DFI) {
1663 const MachineBasicBlock *MBB = *DFI;
1665 StackStateOfBB BBState;
1666 // Check the exit state of the DFS stack predecessor.
1667 if (DFI.getPathLength() >= 2) {
1668 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1669 assert(Reachable.count(StackPred) &&
1670 "DFS stack predecessor is already visited.\n");
1671 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
1672 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
1673 BBState.ExitValue = BBState.EntryValue;
1674 BBState.ExitIsSetup = BBState.EntryIsSetup;
1677 // Update stack state by checking contents of MBB.
1678 for (const auto &I : *MBB) {
1679 if (I.getOpcode() == FrameSetupOpcode) {
1680 // The first operand of a FrameOpcode should be i32.
1681 int Size = I.getOperand(0).getImm();
1683 "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1685 if (BBState.ExitIsSetup)
1686 report("FrameSetup is after another FrameSetup", &I);
1687 BBState.ExitValue -= Size;
1688 BBState.ExitIsSetup = true;
1691 if (I.getOpcode() == FrameDestroyOpcode) {
1692 // The first operand of a FrameOpcode should be i32.
1693 int Size = I.getOperand(0).getImm();
1695 "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1697 if (!BBState.ExitIsSetup)
1698 report("FrameDestroy is not after a FrameSetup", &I);
1699 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
1701 if (BBState.ExitIsSetup && AbsSPAdj != Size) {
1702 report("FrameDestroy <n> is after FrameSetup <m>", &I);
1703 *OS << "FrameDestroy <" << Size << "> is after FrameSetup <"
1704 << AbsSPAdj << ">.\n";
1706 BBState.ExitValue += Size;
1707 BBState.ExitIsSetup = false;
1710 SPState[MBB->getNumber()] = BBState;
1712 // Make sure the exit state of any predecessor is consistent with the entry
1714 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
1715 E = MBB->pred_end(); I != E; ++I) {
1716 if (Reachable.count(*I) &&
1717 (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
1718 SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
1719 report("The exit stack state of a predecessor is inconsistent.", MBB);
1720 *OS << "Predecessor BB#" << (*I)->getNumber() << " has exit state ("
1721 << SPState[(*I)->getNumber()].ExitValue << ", "
1722 << SPState[(*I)->getNumber()].ExitIsSetup
1723 << "), while BB#" << MBB->getNumber() << " has entry state ("
1724 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
1728 // Make sure the entry state of any successor is consistent with the exit
1730 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
1731 E = MBB->succ_end(); I != E; ++I) {
1732 if (Reachable.count(*I) &&
1733 (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
1734 SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
1735 report("The entry stack state of a successor is inconsistent.", MBB);
1736 *OS << "Successor BB#" << (*I)->getNumber() << " has entry state ("
1737 << SPState[(*I)->getNumber()].EntryValue << ", "
1738 << SPState[(*I)->getNumber()].EntryIsSetup
1739 << "), while BB#" << MBB->getNumber() << " has exit state ("
1740 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
1744 // Make sure a basic block with return ends with zero stack adjustment.
1745 if (!MBB->empty() && MBB->back().isReturn()) {
1746 if (BBState.ExitIsSetup)
1747 report("A return block ends with a FrameSetup.", MBB);
1748 if (BBState.ExitValue)
1749 report("A return block ends with a nonzero stack adjustment.", MBB);