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"
52 struct MachineVerifier {
54 MachineVerifier(Pass *pass, const char *b) :
57 OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
60 bool runOnMachineFunction(MachineFunction &MF);
64 const char *const OutFileName;
66 const MachineFunction *MF;
67 const TargetMachine *TM;
68 const TargetInstrInfo *TII;
69 const TargetRegisterInfo *TRI;
70 const MachineRegisterInfo *MRI;
74 typedef SmallVector<unsigned, 16> RegVector;
75 typedef SmallVector<const uint32_t*, 4> RegMaskVector;
76 typedef DenseSet<unsigned> RegSet;
77 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
78 typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet;
80 const MachineInstr *FirstTerminator;
81 BlockSet FunctionBlocks;
83 BitVector regsReserved;
85 RegVector regsDefined, regsDead, regsKilled;
86 RegMaskVector regMasks;
87 RegSet regsLiveInButUnused;
91 // Add Reg and any sub-registers to RV
92 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
94 if (TargetRegisterInfo::isPhysicalRegister(Reg))
95 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
96 RV.push_back(*SubRegs);
100 // Is this MBB reachable from the MF entry point?
103 // Vregs that must be live in because they are used without being
104 // defined. Map value is the user.
107 // Regs killed in MBB. They may be defined again, and will then be in both
108 // regsKilled and regsLiveOut.
111 // Regs defined in MBB and live out. Note that vregs passing through may
112 // be live out without being mentioned here.
115 // Vregs that pass through MBB untouched. This set is disjoint from
116 // regsKilled and regsLiveOut.
119 // Vregs that must pass through MBB because they are needed by a successor
120 // block. This set is disjoint from regsLiveOut.
121 RegSet vregsRequired;
123 // Set versions of block's predecessor and successor lists.
124 BlockSet Preds, Succs;
126 BBInfo() : reachable(false) {}
128 // Add register to vregsPassed if it belongs there. Return true if
130 bool addPassed(unsigned Reg) {
131 if (!TargetRegisterInfo::isVirtualRegister(Reg))
133 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
135 return vregsPassed.insert(Reg).second;
138 // Same for a full set.
139 bool addPassed(const RegSet &RS) {
140 bool changed = false;
141 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
147 // Add register to vregsRequired if it belongs there. Return true if
149 bool addRequired(unsigned Reg) {
150 if (!TargetRegisterInfo::isVirtualRegister(Reg))
152 if (regsLiveOut.count(Reg))
154 return vregsRequired.insert(Reg).second;
157 // Same for a full set.
158 bool addRequired(const RegSet &RS) {
159 bool changed = false;
160 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
166 // Same for a full map.
167 bool addRequired(const RegMap &RM) {
168 bool changed = false;
169 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
170 if (addRequired(I->first))
175 // Live-out registers are either in regsLiveOut or vregsPassed.
176 bool isLiveOut(unsigned Reg) const {
177 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
181 // Extra register info per MBB.
182 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
184 bool isReserved(unsigned Reg) {
185 return Reg < regsReserved.size() && regsReserved.test(Reg);
188 bool isAllocatable(unsigned Reg) {
189 return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg);
192 // Analysis information if available
193 LiveVariables *LiveVars;
194 LiveIntervals *LiveInts;
195 LiveStacks *LiveStks;
196 SlotIndexes *Indexes;
198 void visitMachineFunctionBefore();
199 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
200 void visitMachineBundleBefore(const MachineInstr *MI);
201 void visitMachineInstrBefore(const MachineInstr *MI);
202 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
203 void visitMachineInstrAfter(const MachineInstr *MI);
204 void visitMachineBundleAfter(const MachineInstr *MI);
205 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
206 void visitMachineFunctionAfter();
208 void report(const char *msg, const MachineFunction *MF);
209 void report(const char *msg, const MachineBasicBlock *MBB);
210 void report(const char *msg, const MachineInstr *MI);
211 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
212 void report(const char *msg, const MachineFunction *MF,
213 const LiveInterval &LI);
214 void report(const char *msg, const MachineBasicBlock *MBB,
215 const LiveInterval &LI);
216 void report(const char *msg, const MachineFunction *MF,
217 const LiveRange &LR);
218 void report(const char *msg, const MachineBasicBlock *MBB,
219 const LiveRange &LR);
221 void verifyInlineAsm(const MachineInstr *MI);
223 void checkLiveness(const MachineOperand *MO, unsigned MONum);
224 void markReachable(const MachineBasicBlock *MBB);
225 void calcRegsPassed();
226 void checkPHIOps(const MachineBasicBlock *MBB);
228 void calcRegsRequired();
229 void verifyLiveVariables();
230 void verifyLiveIntervals();
231 void verifyLiveInterval(const LiveInterval&);
232 void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned);
233 void verifyLiveRangeSegment(const LiveRange&,
234 const LiveRange::const_iterator I, unsigned);
235 void verifyLiveRange(const LiveRange&, unsigned);
237 void verifyStackFrame();
240 struct MachineVerifierPass : public MachineFunctionPass {
241 static char ID; // Pass ID, replacement for typeid
242 const char *const Banner;
244 MachineVerifierPass(const char *b = nullptr)
245 : MachineFunctionPass(ID), Banner(b) {
246 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
249 void getAnalysisUsage(AnalysisUsage &AU) const override {
250 AU.setPreservesAll();
251 MachineFunctionPass::getAnalysisUsage(AU);
254 bool runOnMachineFunction(MachineFunction &MF) override {
255 MF.verify(this, Banner);
262 char MachineVerifierPass::ID = 0;
263 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
264 "Verify generated machine code", false, false)
266 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
267 return new MachineVerifierPass(Banner);
270 void MachineFunction::verify(Pass *p, const char *Banner) const {
271 MachineVerifier(p, Banner)
272 .runOnMachineFunction(const_cast<MachineFunction&>(*this));
275 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
276 raw_ostream *OutFile = nullptr;
278 std::string ErrorInfo;
279 OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
280 sys::fs::F_Append | sys::fs::F_Text);
281 if (!ErrorInfo.empty()) {
282 errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
294 TM = &MF.getTarget();
295 TII = TM->getInstrInfo();
296 TRI = TM->getRegisterInfo();
297 MRI = &MF.getRegInfo();
304 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
305 // We don't want to verify LiveVariables if LiveIntervals is available.
307 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
308 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
309 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
312 visitMachineFunctionBefore();
313 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
315 visitMachineBasicBlockBefore(MFI);
316 // Keep track of the current bundle header.
317 const MachineInstr *CurBundle = nullptr;
318 // Do we expect the next instruction to be part of the same bundle?
319 bool InBundle = false;
321 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
322 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
323 if (MBBI->getParent() != MFI) {
324 report("Bad instruction parent pointer", MFI);
325 *OS << "Instruction: " << *MBBI;
329 // Check for consistent bundle flags.
330 if (InBundle && !MBBI->isBundledWithPred())
331 report("Missing BundledPred flag, "
332 "BundledSucc was set on predecessor", MBBI);
333 if (!InBundle && MBBI->isBundledWithPred())
334 report("BundledPred flag is set, "
335 "but BundledSucc not set on predecessor", MBBI);
337 // Is this a bundle header?
338 if (!MBBI->isInsideBundle()) {
340 visitMachineBundleAfter(CurBundle);
342 visitMachineBundleBefore(CurBundle);
343 } else if (!CurBundle)
344 report("No bundle header", MBBI);
345 visitMachineInstrBefore(MBBI);
346 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
347 visitMachineOperand(&MBBI->getOperand(I), I);
348 visitMachineInstrAfter(MBBI);
350 // Was this the last bundled instruction?
351 InBundle = MBBI->isBundledWithSucc();
354 visitMachineBundleAfter(CurBundle);
356 report("BundledSucc flag set on last instruction in block", &MFI->back());
357 visitMachineBasicBlockAfter(MFI);
359 visitMachineFunctionAfter();
363 else if (foundErrors)
364 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
372 regsLiveInButUnused.clear();
375 return false; // no changes
378 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
381 if (!foundErrors++) {
383 *OS << "# " << Banner << '\n';
384 MF->print(*OS, Indexes);
386 *OS << "*** Bad machine code: " << msg << " ***\n"
387 << "- function: " << MF->getName() << "\n";
390 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
392 report(msg, MBB->getParent());
393 *OS << "- basic block: BB#" << MBB->getNumber()
394 << ' ' << MBB->getName()
395 << " (" << (const void*)MBB << ')';
397 *OS << " [" << Indexes->getMBBStartIdx(MBB)
398 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
402 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
404 report(msg, MI->getParent());
405 *OS << "- instruction: ";
406 if (Indexes && Indexes->hasIndex(MI))
407 *OS << Indexes->getInstructionIndex(MI) << '\t';
411 void MachineVerifier::report(const char *msg,
412 const MachineOperand *MO, unsigned MONum) {
414 report(msg, MO->getParent());
415 *OS << "- operand " << MONum << ": ";
420 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
421 const LiveInterval &LI) {
423 *OS << "- interval: " << LI << '\n';
426 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
427 const LiveInterval &LI) {
429 *OS << "- interval: " << LI << '\n';
432 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
433 const LiveRange &LR) {
435 *OS << "- liverange: " << LR << "\n";
438 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
439 const LiveRange &LR) {
441 *OS << "- liverange: " << LR << "\n";
444 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
445 BBInfo &MInfo = MBBInfoMap[MBB];
446 if (!MInfo.reachable) {
447 MInfo.reachable = true;
448 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
449 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
454 void MachineVerifier::visitMachineFunctionBefore() {
455 lastIndex = SlotIndex();
456 regsReserved = MRI->getReservedRegs();
458 // A sub-register of a reserved register is also reserved
459 for (int Reg = regsReserved.find_first(); Reg>=0;
460 Reg = regsReserved.find_next(Reg)) {
461 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
462 // FIXME: This should probably be:
463 // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register");
464 regsReserved.set(*SubRegs);
468 markReachable(&MF->front());
470 // Build a set of the basic blocks in the function.
471 FunctionBlocks.clear();
472 for (const auto &MBB : *MF) {
473 FunctionBlocks.insert(&MBB);
474 BBInfo &MInfo = MBBInfoMap[&MBB];
476 MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
477 if (MInfo.Preds.size() != MBB.pred_size())
478 report("MBB has duplicate entries in its predecessor list.", &MBB);
480 MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
481 if (MInfo.Succs.size() != MBB.succ_size())
482 report("MBB has duplicate entries in its successor list.", &MBB);
485 // Check that the register use lists are sane.
486 MRI->verifyUseLists();
491 // Does iterator point to a and b as the first two elements?
492 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
493 const MachineBasicBlock *a, const MachineBasicBlock *b) {
502 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
503 FirstTerminator = nullptr;
506 // If this block has allocatable physical registers live-in, check that
507 // it is an entry block or landing pad.
508 for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
509 LE = MBB->livein_end();
512 if (isAllocatable(reg) && !MBB->isLandingPad() &&
513 MBB != MBB->getParent()->begin()) {
514 report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
519 // Count the number of landing pad successors.
520 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
521 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
522 E = MBB->succ_end(); I != E; ++I) {
523 if ((*I)->isLandingPad())
524 LandingPadSuccs.insert(*I);
525 if (!FunctionBlocks.count(*I))
526 report("MBB has successor that isn't part of the function.", MBB);
527 if (!MBBInfoMap[*I].Preds.count(MBB)) {
528 report("Inconsistent CFG", MBB);
529 *OS << "MBB is not in the predecessor list of the successor BB#"
530 << (*I)->getNumber() << ".\n";
534 // Check the predecessor list.
535 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
536 E = MBB->pred_end(); I != E; ++I) {
537 if (!FunctionBlocks.count(*I))
538 report("MBB has predecessor that isn't part of the function.", MBB);
539 if (!MBBInfoMap[*I].Succs.count(MBB)) {
540 report("Inconsistent CFG", MBB);
541 *OS << "MBB is not in the successor list of the predecessor BB#"
542 << (*I)->getNumber() << ".\n";
546 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
547 const BasicBlock *BB = MBB->getBasicBlock();
548 if (LandingPadSuccs.size() > 1 &&
550 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
551 BB && isa<SwitchInst>(BB->getTerminator())))
552 report("MBB has more than one landing pad successor", MBB);
554 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
555 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
556 SmallVector<MachineOperand, 4> Cond;
557 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
559 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
560 // check whether its answers match up with reality.
562 // Block falls through to its successor.
563 MachineFunction::const_iterator MBBI = MBB;
565 if (MBBI == MF->end()) {
566 // It's possible that the block legitimately ends with a noreturn
567 // call or an unreachable, in which case it won't actually fall
568 // out the bottom of the function.
569 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
570 // It's possible that the block legitimately ends with a noreturn
571 // call or an unreachable, in which case it won't actuall fall
573 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
574 report("MBB exits via unconditional fall-through but doesn't have "
575 "exactly one CFG successor!", MBB);
576 } else if (!MBB->isSuccessor(MBBI)) {
577 report("MBB exits via unconditional fall-through but its successor "
578 "differs from its CFG successor!", MBB);
580 if (!MBB->empty() && MBB->back().isBarrier() &&
581 !TII->isPredicated(&MBB->back())) {
582 report("MBB exits via unconditional fall-through but ends with a "
583 "barrier instruction!", MBB);
586 report("MBB exits via unconditional fall-through but has a condition!",
589 } else if (TBB && !FBB && Cond.empty()) {
590 // Block unconditionally branches somewhere.
591 if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
592 report("MBB exits via unconditional branch but doesn't have "
593 "exactly one CFG successor!", MBB);
594 } else if (!MBB->isSuccessor(TBB)) {
595 report("MBB exits via unconditional branch but the CFG "
596 "successor doesn't match the actual successor!", MBB);
599 report("MBB exits via unconditional branch but doesn't contain "
600 "any instructions!", MBB);
601 } else if (!MBB->back().isBarrier()) {
602 report("MBB exits via unconditional branch but doesn't end with a "
603 "barrier instruction!", MBB);
604 } else if (!MBB->back().isTerminator()) {
605 report("MBB exits via unconditional branch but the branch isn't a "
606 "terminator instruction!", MBB);
608 } else if (TBB && !FBB && !Cond.empty()) {
609 // Block conditionally branches somewhere, otherwise falls through.
610 MachineFunction::const_iterator MBBI = MBB;
612 if (MBBI == MF->end()) {
613 report("MBB conditionally falls through out of function!", MBB);
614 } else if (MBB->succ_size() == 1) {
615 // A conditional branch with only one successor is weird, but allowed.
617 report("MBB exits via conditional branch/fall-through but only has "
618 "one CFG successor!", MBB);
619 else if (TBB != *MBB->succ_begin())
620 report("MBB exits via conditional branch/fall-through but the CFG "
621 "successor don't match the actual successor!", MBB);
622 } else if (MBB->succ_size() != 2) {
623 report("MBB exits via conditional branch/fall-through but doesn't have "
624 "exactly two CFG successors!", MBB);
625 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
626 report("MBB exits via conditional branch/fall-through but the CFG "
627 "successors don't match the actual successors!", MBB);
630 report("MBB exits via conditional branch/fall-through but doesn't "
631 "contain any instructions!", MBB);
632 } else if (MBB->back().isBarrier()) {
633 report("MBB exits via conditional branch/fall-through but ends with a "
634 "barrier instruction!", MBB);
635 } else if (!MBB->back().isTerminator()) {
636 report("MBB exits via conditional branch/fall-through but the branch "
637 "isn't a terminator instruction!", MBB);
639 } else if (TBB && FBB) {
640 // Block conditionally branches somewhere, otherwise branches
642 if (MBB->succ_size() == 1) {
643 // A conditional branch with only one successor is weird, but allowed.
645 report("MBB exits via conditional branch/branch through but only has "
646 "one CFG successor!", MBB);
647 else if (TBB != *MBB->succ_begin())
648 report("MBB exits via conditional branch/branch through but the CFG "
649 "successor don't match the actual successor!", MBB);
650 } else if (MBB->succ_size() != 2) {
651 report("MBB exits via conditional branch/branch but doesn't have "
652 "exactly two CFG successors!", MBB);
653 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
654 report("MBB exits via conditional branch/branch but the CFG "
655 "successors don't match the actual successors!", MBB);
658 report("MBB exits via conditional branch/branch but doesn't "
659 "contain any instructions!", MBB);
660 } else if (!MBB->back().isBarrier()) {
661 report("MBB exits via conditional branch/branch but doesn't end with a "
662 "barrier instruction!", MBB);
663 } else if (!MBB->back().isTerminator()) {
664 report("MBB exits via conditional branch/branch but the branch "
665 "isn't a terminator instruction!", MBB);
668 report("MBB exits via conditinal branch/branch but there's no "
672 report("AnalyzeBranch returned invalid data!", MBB);
677 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
678 E = MBB->livein_end(); I != E; ++I) {
679 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
680 report("MBB live-in list contains non-physical register", MBB);
683 for (MCSubRegIterator SubRegs(*I, TRI, /*IncludeSelf=*/true);
684 SubRegs.isValid(); ++SubRegs)
685 regsLive.insert(*SubRegs);
687 regsLiveInButUnused = regsLive;
689 const MachineFrameInfo *MFI = MF->getFrameInfo();
690 assert(MFI && "Function has no frame info");
691 BitVector PR = MFI->getPristineRegs(MBB);
692 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
693 for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
694 SubRegs.isValid(); ++SubRegs)
695 regsLive.insert(*SubRegs);
702 lastIndex = Indexes->getMBBStartIdx(MBB);
705 // This function gets called for all bundle headers, including normal
706 // stand-alone unbundled instructions.
707 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
708 if (Indexes && Indexes->hasIndex(MI)) {
709 SlotIndex idx = Indexes->getInstructionIndex(MI);
710 if (!(idx > lastIndex)) {
711 report("Instruction index out of order", MI);
712 *OS << "Last instruction was at " << lastIndex << '\n';
717 // Ensure non-terminators don't follow terminators.
718 // Ignore predicated terminators formed by if conversion.
719 // FIXME: If conversion shouldn't need to violate this rule.
720 if (MI->isTerminator() && !TII->isPredicated(MI)) {
721 if (!FirstTerminator)
722 FirstTerminator = MI;
723 } else if (FirstTerminator) {
724 report("Non-terminator instruction after the first terminator", MI);
725 *OS << "First terminator was:\t" << *FirstTerminator;
729 // The operands on an INLINEASM instruction must follow a template.
730 // Verify that the flag operands make sense.
731 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
732 // The first two operands on INLINEASM are the asm string and global flags.
733 if (MI->getNumOperands() < 2) {
734 report("Too few operands on inline asm", MI);
737 if (!MI->getOperand(0).isSymbol())
738 report("Asm string must be an external symbol", MI);
739 if (!MI->getOperand(1).isImm())
740 report("Asm flags must be an immediate", MI);
741 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
742 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16.
743 if (!isUInt<5>(MI->getOperand(1).getImm()))
744 report("Unknown asm flags", &MI->getOperand(1), 1);
746 assert(InlineAsm::MIOp_FirstOperand == 2 && "Asm format changed");
748 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
750 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
751 const MachineOperand &MO = MI->getOperand(OpNo);
752 // There may be implicit ops after the fixed operands.
755 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
758 if (OpNo > MI->getNumOperands())
759 report("Missing operands in last group", MI);
761 // An optional MDNode follows the groups.
762 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
765 // All trailing operands must be implicit registers.
766 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
767 const MachineOperand &MO = MI->getOperand(OpNo);
768 if (!MO.isReg() || !MO.isImplicit())
769 report("Expected implicit register after groups", &MO, OpNo);
773 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
774 const MCInstrDesc &MCID = MI->getDesc();
775 if (MI->getNumOperands() < MCID.getNumOperands()) {
776 report("Too few operands", MI);
777 *OS << MCID.getNumOperands() << " operands expected, but "
778 << MI->getNumOperands() << " given.\n";
781 // Check the tied operands.
782 if (MI->isInlineAsm())
785 // Check the MachineMemOperands for basic consistency.
786 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
787 E = MI->memoperands_end(); I != E; ++I) {
788 if ((*I)->isLoad() && !MI->mayLoad())
789 report("Missing mayLoad flag", MI);
790 if ((*I)->isStore() && !MI->mayStore())
791 report("Missing mayStore flag", MI);
794 // Debug values must not have a slot index.
795 // Other instructions must have one, unless they are inside a bundle.
797 bool mapped = !LiveInts->isNotInMIMap(MI);
798 if (MI->isDebugValue()) {
800 report("Debug instruction has a slot index", MI);
801 } else if (MI->isInsideBundle()) {
803 report("Instruction inside bundle has a slot index", MI);
806 report("Missing slot index", MI);
811 if (!TII->verifyInstruction(MI, ErrorInfo))
812 report(ErrorInfo.data(), MI);
816 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
817 const MachineInstr *MI = MO->getParent();
818 const MCInstrDesc &MCID = MI->getDesc();
820 // The first MCID.NumDefs operands must be explicit register defines
821 if (MONum < MCID.getNumDefs()) {
822 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
824 report("Explicit definition must be a register", MO, MONum);
825 else if (!MO->isDef() && !MCOI.isOptionalDef())
826 report("Explicit definition marked as use", MO, MONum);
827 else if (MO->isImplicit())
828 report("Explicit definition marked as implicit", MO, MONum);
829 } else if (MONum < MCID.getNumOperands()) {
830 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
831 // Don't check if it's the last operand in a variadic instruction. See,
832 // e.g., LDM_RET in the arm back end.
834 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
835 if (MO->isDef() && !MCOI.isOptionalDef())
836 report("Explicit operand marked as def", MO, MONum);
837 if (MO->isImplicit())
838 report("Explicit operand marked as implicit", MO, MONum);
841 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
844 report("Tied use must be a register", MO, MONum);
845 else if (!MO->isTied())
846 report("Operand should be tied", MO, MONum);
847 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
848 report("Tied def doesn't match MCInstrDesc", MO, MONum);
849 } else if (MO->isReg() && MO->isTied())
850 report("Explicit operand should not be tied", MO, MONum);
852 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
853 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
854 report("Extra explicit operand on non-variadic instruction", MO, MONum);
857 switch (MO->getType()) {
858 case MachineOperand::MO_Register: {
859 const unsigned Reg = MO->getReg();
862 if (MRI->tracksLiveness() && !MI->isDebugValue())
863 checkLiveness(MO, MONum);
865 // Verify the consistency of tied operands.
867 unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
868 const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
869 if (!OtherMO.isReg())
870 report("Must be tied to a register", MO, MONum);
871 if (!OtherMO.isTied())
872 report("Missing tie flags on tied operand", MO, MONum);
873 if (MI->findTiedOperandIdx(OtherIdx) != MONum)
874 report("Inconsistent tie links", MO, MONum);
875 if (MONum < MCID.getNumDefs()) {
876 if (OtherIdx < MCID.getNumOperands()) {
877 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
878 report("Explicit def tied to explicit use without tie constraint",
881 if (!OtherMO.isImplicit())
882 report("Explicit def should be tied to implicit use", MO, MONum);
887 // Verify two-address constraints after leaving SSA form.
889 if (!MRI->isSSA() && MO->isUse() &&
890 MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
891 Reg != MI->getOperand(DefIdx).getReg())
892 report("Two-address instruction operands must be identical", MO, MONum);
894 // Check register classes.
895 if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
896 unsigned SubIdx = MO->getSubReg();
898 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
900 report("Illegal subregister index for physical register", MO, MONum);
903 if (const TargetRegisterClass *DRC =
904 TII->getRegClass(MCID, MONum, TRI, *MF)) {
905 if (!DRC->contains(Reg)) {
906 report("Illegal physical register for instruction", MO, MONum);
907 *OS << TRI->getName(Reg) << " is not a "
908 << DRC->getName() << " register.\n";
913 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
915 const TargetRegisterClass *SRC =
916 TRI->getSubClassWithSubReg(RC, SubIdx);
918 report("Invalid subregister index for virtual register", MO, MONum);
919 *OS << "Register class " << RC->getName()
920 << " does not support subreg index " << SubIdx << "\n";
924 report("Invalid register class for subregister index", MO, MONum);
925 *OS << "Register class " << RC->getName()
926 << " does not fully support subreg index " << SubIdx << "\n";
930 if (const TargetRegisterClass *DRC =
931 TII->getRegClass(MCID, MONum, TRI, *MF)) {
933 const TargetRegisterClass *SuperRC =
934 TRI->getLargestLegalSuperClass(RC);
936 report("No largest legal super class exists.", MO, MONum);
939 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
941 report("No matching super-reg register class.", MO, MONum);
945 if (!RC->hasSuperClassEq(DRC)) {
946 report("Illegal virtual register for instruction", MO, MONum);
947 *OS << "Expected a " << DRC->getName() << " register, but got a "
948 << RC->getName() << " register\n";
956 case MachineOperand::MO_RegisterMask:
957 regMasks.push_back(MO->getRegMask());
960 case MachineOperand::MO_MachineBasicBlock:
961 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
962 report("PHI operand is not in the CFG", MO, MONum);
965 case MachineOperand::MO_FrameIndex:
966 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
967 LiveInts && !LiveInts->isNotInMIMap(MI)) {
968 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
969 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
970 if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
971 report("Instruction loads from dead spill slot", MO, MONum);
972 *OS << "Live stack: " << LI << '\n';
974 if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
975 report("Instruction stores to dead spill slot", MO, MONum);
976 *OS << "Live stack: " << LI << '\n';
986 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
987 const MachineInstr *MI = MO->getParent();
988 const unsigned Reg = MO->getReg();
990 // Both use and def operands can read a register.
991 if (MO->readsReg()) {
992 regsLiveInButUnused.erase(Reg);
995 addRegWithSubRegs(regsKilled, Reg);
997 // Check that LiveVars knows this kill.
998 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1000 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1001 if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end())
1002 report("Kill missing from LiveVariables", MO, MONum);
1005 // Check LiveInts liveness and kill.
1006 if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
1007 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI);
1008 // Check the cached regunit intervals.
1009 if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1010 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1011 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) {
1012 LiveQueryResult LRQ = LR->Query(UseIdx);
1013 if (!LRQ.valueIn()) {
1014 report("No live segment at use", MO, MONum);
1015 *OS << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI)
1016 << ' ' << *LR << '\n';
1018 if (MO->isKill() && !LRQ.isKill()) {
1019 report("Live range continues after kill flag", MO, MONum);
1020 *OS << PrintRegUnit(*Units, TRI) << ' ' << *LR << '\n';
1026 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1027 if (LiveInts->hasInterval(Reg)) {
1028 // This is a virtual register interval.
1029 const LiveInterval &LI = LiveInts->getInterval(Reg);
1030 LiveQueryResult LRQ = LI.Query(UseIdx);
1031 if (!LRQ.valueIn()) {
1032 report("No live segment at use", MO, MONum);
1033 *OS << UseIdx << " is not live in " << LI << '\n';
1035 // Check for extra kill flags.
1036 // Note that we allow missing kill flags for now.
1037 if (MO->isKill() && !LRQ.isKill()) {
1038 report("Live range continues after kill flag", MO, MONum);
1039 *OS << "Live range: " << LI << '\n';
1042 report("Virtual register has no live interval", MO, MONum);
1047 // Use of a dead register.
1048 if (!regsLive.count(Reg)) {
1049 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1050 // Reserved registers may be used even when 'dead'.
1051 if (!isReserved(Reg))
1052 report("Using an undefined physical register", MO, MONum);
1053 } else if (MRI->def_empty(Reg)) {
1054 report("Reading virtual register without a def", MO, MONum);
1056 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1057 // We don't know which virtual registers are live in, so only complain
1058 // if vreg was killed in this MBB. Otherwise keep track of vregs that
1059 // must be live in. PHI instructions are handled separately.
1060 if (MInfo.regsKilled.count(Reg))
1061 report("Using a killed virtual register", MO, MONum);
1062 else if (!MI->isPHI())
1063 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1069 // Register defined.
1070 // TODO: verify that earlyclobber ops are not used.
1072 addRegWithSubRegs(regsDead, Reg);
1074 addRegWithSubRegs(regsDefined, Reg);
1077 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1078 std::next(MRI->def_begin(Reg)) != MRI->def_end())
1079 report("Multiple virtual register defs in SSA form", MO, MONum);
1081 // Check LiveInts for a live segment, but only for virtual registers.
1082 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
1083 !LiveInts->isNotInMIMap(MI)) {
1084 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI);
1085 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1086 if (LiveInts->hasInterval(Reg)) {
1087 const LiveInterval &LI = LiveInts->getInterval(Reg);
1088 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
1089 assert(VNI && "NULL valno is not allowed");
1090 if (VNI->def != DefIdx) {
1091 report("Inconsistent valno->def", MO, MONum);
1092 *OS << "Valno " << VNI->id << " is not defined at "
1093 << DefIdx << " in " << LI << '\n';
1096 report("No live segment at def", MO, MONum);
1097 *OS << DefIdx << " is not live in " << LI << '\n';
1099 // Check that, if the dead def flag is present, LiveInts agree.
1101 LiveQueryResult LRQ = LI.Query(DefIdx);
1102 if (!LRQ.isDeadDef()) {
1103 report("Live range continues after dead def flag", MO, MONum);
1104 *OS << "Live range: " << LI << '\n';
1108 report("Virtual register has no Live interval", MO, MONum);
1114 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
1117 // This function gets called after visiting all instructions in a bundle. The
1118 // argument points to the bundle header.
1119 // Normal stand-alone instructions are also considered 'bundles', and this
1120 // function is called for all of them.
1121 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1122 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1123 set_union(MInfo.regsKilled, regsKilled);
1124 set_subtract(regsLive, regsKilled); regsKilled.clear();
1125 // Kill any masked registers.
1126 while (!regMasks.empty()) {
1127 const uint32_t *Mask = regMasks.pop_back_val();
1128 for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1129 if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1130 MachineOperand::clobbersPhysReg(Mask, *I))
1131 regsDead.push_back(*I);
1133 set_subtract(regsLive, regsDead); regsDead.clear();
1134 set_union(regsLive, regsDefined); regsDefined.clear();
1138 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1139 MBBInfoMap[MBB].regsLiveOut = regsLive;
1143 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1144 if (!(stop > lastIndex)) {
1145 report("Block ends before last instruction index", MBB);
1146 *OS << "Block ends at " << stop
1147 << " last instruction was at " << lastIndex << '\n';
1153 // Calculate the largest possible vregsPassed sets. These are the registers that
1154 // can pass through an MBB live, but may not be live every time. It is assumed
1155 // that all vregsPassed sets are empty before the call.
1156 void MachineVerifier::calcRegsPassed() {
1157 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1158 // have any vregsPassed.
1159 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1160 for (const auto &MBB : *MF) {
1161 BBInfo &MInfo = MBBInfoMap[&MBB];
1162 if (!MInfo.reachable)
1164 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1165 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1166 BBInfo &SInfo = MBBInfoMap[*SuI];
1167 if (SInfo.addPassed(MInfo.regsLiveOut))
1172 // Iteratively push vregsPassed to successors. This will converge to the same
1173 // final state regardless of DenseSet iteration order.
1174 while (!todo.empty()) {
1175 const MachineBasicBlock *MBB = *todo.begin();
1177 BBInfo &MInfo = MBBInfoMap[MBB];
1178 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1179 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1182 BBInfo &SInfo = MBBInfoMap[*SuI];
1183 if (SInfo.addPassed(MInfo.vregsPassed))
1189 // Calculate the set of virtual registers that must be passed through each basic
1190 // block in order to satisfy the requirements of successor blocks. This is very
1191 // similar to calcRegsPassed, only backwards.
1192 void MachineVerifier::calcRegsRequired() {
1193 // First push live-in regs to predecessors' vregsRequired.
1194 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1195 for (const auto &MBB : *MF) {
1196 BBInfo &MInfo = MBBInfoMap[&MBB];
1197 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1198 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1199 BBInfo &PInfo = MBBInfoMap[*PrI];
1200 if (PInfo.addRequired(MInfo.vregsLiveIn))
1205 // Iteratively push vregsRequired to predecessors. This will converge to the
1206 // same final state regardless of DenseSet iteration order.
1207 while (!todo.empty()) {
1208 const MachineBasicBlock *MBB = *todo.begin();
1210 BBInfo &MInfo = MBBInfoMap[MBB];
1211 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1212 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1215 BBInfo &SInfo = MBBInfoMap[*PrI];
1216 if (SInfo.addRequired(MInfo.vregsRequired))
1222 // Check PHI instructions at the beginning of MBB. It is assumed that
1223 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1224 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
1225 SmallPtrSet<const MachineBasicBlock*, 8> seen;
1226 for (const auto &BBI : *MBB) {
1231 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
1232 unsigned Reg = BBI.getOperand(i).getReg();
1233 const MachineBasicBlock *Pre = BBI.getOperand(i + 1).getMBB();
1234 if (!Pre->isSuccessor(MBB))
1237 BBInfo &PrInfo = MBBInfoMap[Pre];
1238 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
1239 report("PHI operand is not live-out from predecessor",
1240 &BBI.getOperand(i), i);
1243 // Did we see all predecessors?
1244 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1245 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1246 if (!seen.count(*PrI)) {
1247 report("Missing PHI operand", &BBI);
1248 *OS << "BB#" << (*PrI)->getNumber()
1249 << " is a predecessor according to the CFG.\n";
1255 void MachineVerifier::visitMachineFunctionAfter() {
1258 for (const auto &MBB : *MF) {
1259 BBInfo &MInfo = MBBInfoMap[&MBB];
1261 // Skip unreachable MBBs.
1262 if (!MInfo.reachable)
1268 // Now check liveness info if available
1271 // Check for killed virtual registers that should be live out.
1272 for (const auto &MBB : *MF) {
1273 BBInfo &MInfo = MBBInfoMap[&MBB];
1274 for (RegSet::iterator
1275 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1277 if (MInfo.regsKilled.count(*I)) {
1278 report("Virtual register killed in block, but needed live out.", &MBB);
1279 *OS << "Virtual register " << PrintReg(*I)
1280 << " is used after the block.\n";
1285 BBInfo &MInfo = MBBInfoMap[&MF->front()];
1286 for (RegSet::iterator
1287 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1289 report("Virtual register def doesn't dominate all uses.",
1290 MRI->getVRegDef(*I));
1294 verifyLiveVariables();
1296 verifyLiveIntervals();
1299 void MachineVerifier::verifyLiveVariables() {
1300 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1301 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1302 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1303 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1304 for (const auto &MBB : *MF) {
1305 BBInfo &MInfo = MBBInfoMap[&MBB];
1307 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1308 if (MInfo.vregsRequired.count(Reg)) {
1309 if (!VI.AliveBlocks.test(MBB.getNumber())) {
1310 report("LiveVariables: Block missing from AliveBlocks", &MBB);
1311 *OS << "Virtual register " << PrintReg(Reg)
1312 << " must be live through the block.\n";
1315 if (VI.AliveBlocks.test(MBB.getNumber())) {
1316 report("LiveVariables: Block should not be in AliveBlocks", &MBB);
1317 *OS << "Virtual register " << PrintReg(Reg)
1318 << " is not needed live through the block.\n";
1325 void MachineVerifier::verifyLiveIntervals() {
1326 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1327 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1328 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1330 // Spilling and splitting may leave unused registers around. Skip them.
1331 if (MRI->reg_nodbg_empty(Reg))
1334 if (!LiveInts->hasInterval(Reg)) {
1335 report("Missing live interval for virtual register", MF);
1336 *OS << PrintReg(Reg, TRI) << " still has defs or uses\n";
1340 const LiveInterval &LI = LiveInts->getInterval(Reg);
1341 assert(Reg == LI.reg && "Invalid reg to interval mapping");
1342 verifyLiveInterval(LI);
1345 // Verify all the cached regunit intervals.
1346 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1347 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1348 verifyLiveRange(*LR, i);
1351 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1354 if (VNI->isUnused())
1357 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1360 report("Valno not live at def and not marked unused", MF, LR);
1361 *OS << "Valno #" << VNI->id << '\n';
1365 if (DefVNI != VNI) {
1366 report("Live segment at def has different valno", MF, LR);
1367 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1368 << " where valno #" << DefVNI->id << " is live\n";
1372 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1374 report("Invalid definition index", MF, LR);
1375 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1376 << " in " << LR << '\n';
1380 if (VNI->isPHIDef()) {
1381 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1382 report("PHIDef value is not defined at MBB start", MBB, LR);
1383 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1384 << ", not at the beginning of BB#" << MBB->getNumber() << '\n';
1390 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1392 report("No instruction at def index", MBB, LR);
1393 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1398 bool hasDef = false;
1399 bool isEarlyClobber = false;
1400 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1401 if (!MOI->isReg() || !MOI->isDef())
1403 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1404 if (MOI->getReg() != Reg)
1407 if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1408 !TRI->hasRegUnit(MOI->getReg(), Reg))
1412 if (MOI->isEarlyClobber())
1413 isEarlyClobber = true;
1417 report("Defining instruction does not modify register", MI);
1418 *OS << "Valno #" << VNI->id << " in " << LR << '\n';
1421 // Early clobber defs begin at USE slots, but other defs must begin at
1423 if (isEarlyClobber) {
1424 if (!VNI->def.isEarlyClobber()) {
1425 report("Early clobber def must be at an early-clobber slot", MBB, LR);
1426 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1428 } else if (!VNI->def.isRegister()) {
1429 report("Non-PHI, non-early clobber def must be at a register slot",
1431 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1436 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1437 const LiveRange::const_iterator I,
1439 const LiveRange::Segment &S = *I;
1440 const VNInfo *VNI = S.valno;
1441 assert(VNI && "Live segment has no valno");
1443 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1444 report("Foreign valno in live segment", MF, LR);
1445 *OS << S << " has a bad valno\n";
1448 if (VNI->isUnused()) {
1449 report("Live segment valno is marked unused", MF, LR);
1453 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1455 report("Bad start of live segment, no basic block", MF, LR);
1459 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1460 if (S.start != MBBStartIdx && S.start != VNI->def) {
1461 report("Live segment must begin at MBB entry or valno def", MBB, LR);
1465 const MachineBasicBlock *EndMBB =
1466 LiveInts->getMBBFromIndex(S.end.getPrevSlot());
1468 report("Bad end of live segment, no basic block", MF, LR);
1473 // No more checks for live-out segments.
1474 if (S.end == LiveInts->getMBBEndIdx(EndMBB))
1477 // RegUnit intervals are allowed dead phis.
1478 if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
1479 S.start == VNI->def && S.end == VNI->def.getDeadSlot())
1482 // The live segment is ending inside EndMBB
1483 const MachineInstr *MI =
1484 LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
1486 report("Live segment doesn't end at a valid instruction", EndMBB, LR);
1491 // The block slot must refer to a basic block boundary.
1492 if (S.end.isBlock()) {
1493 report("Live segment ends at B slot of an instruction", EndMBB, LR);
1497 if (S.end.isDead()) {
1498 // Segment ends on the dead slot.
1499 // That means there must be a dead def.
1500 if (!SlotIndex::isSameInstr(S.start, S.end)) {
1501 report("Live segment ending at dead slot spans instructions", EndMBB, LR);
1506 // A live segment can only end at an early-clobber slot if it is being
1507 // redefined by an early-clobber def.
1508 if (S.end.isEarlyClobber()) {
1509 if (I+1 == LR.end() || (I+1)->start != S.end) {
1510 report("Live segment ending at early clobber slot must be "
1511 "redefined by an EC def in the same instruction", EndMBB, LR);
1516 // The following checks only apply to virtual registers. Physreg liveness
1517 // is too weird to check.
1518 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1519 // A live segment can end with either a redefinition, a kill flag on a
1520 // use, or a dead flag on a def.
1521 bool hasRead = false;
1522 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1523 if (!MOI->isReg() || MOI->getReg() != Reg)
1525 if (MOI->readsReg())
1528 if (!S.end.isDead()) {
1530 report("Instruction ending live segment doesn't read the register", MI);
1531 *OS << S << " in " << LR << '\n';
1536 // Now check all the basic blocks in this live segment.
1537 MachineFunction::const_iterator MFI = MBB;
1538 // Is this live segment the beginning of a non-PHIDef VN?
1539 if (S.start == VNI->def && !VNI->isPHIDef()) {
1540 // Not live-in to any blocks.
1547 assert(LiveInts->isLiveInToMBB(LR, MFI));
1548 // We don't know how to track physregs into a landing pad.
1549 if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
1550 MFI->isLandingPad()) {
1551 if (&*MFI == EndMBB)
1557 // Is VNI a PHI-def in the current block?
1558 bool IsPHI = VNI->isPHIDef() &&
1559 VNI->def == LiveInts->getMBBStartIdx(MFI);
1561 // Check that VNI is live-out of all predecessors.
1562 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1563 PE = MFI->pred_end(); PI != PE; ++PI) {
1564 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1565 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
1567 // All predecessors must have a live-out value.
1569 report("Register not marked live out of predecessor", *PI, LR);
1570 *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1571 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1576 // Only PHI-defs can take different predecessor values.
1577 if (!IsPHI && PVNI != VNI) {
1578 report("Different value live out of predecessor", *PI, LR);
1579 *OS << "Valno #" << PVNI->id << " live out of BB#"
1580 << (*PI)->getNumber() << '@' << PEnd
1581 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1582 << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
1585 if (&*MFI == EndMBB)
1591 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg) {
1592 for (LiveRange::const_vni_iterator I = LR.vni_begin(), E = LR.vni_end();
1594 verifyLiveRangeValue(LR, *I, Reg);
1596 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
1597 verifyLiveRangeSegment(LR, I, Reg);
1600 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
1601 verifyLiveRange(LI, LI.reg);
1603 // Check the LI only has one connected component.
1604 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1605 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1606 unsigned NumComp = ConEQ.Classify(&LI);
1608 report("Multiple connected components in live interval", MF, LI);
1609 for (unsigned comp = 0; comp != NumComp; ++comp) {
1610 *OS << comp << ": valnos";
1611 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1612 E = LI.vni_end(); I!=E; ++I)
1613 if (comp == ConEQ.getEqClass(*I))
1614 *OS << ' ' << (*I)->id;
1622 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
1623 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
1625 // We use a bool plus an integer to capture the stack state.
1626 struct StackStateOfBB {
1627 StackStateOfBB() : EntryValue(0), ExitValue(0), EntryIsSetup(false),
1628 ExitIsSetup(false) { }
1629 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
1630 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
1631 ExitIsSetup(ExitSetup) { }
1632 // Can be negative, which means we are setting up a frame.
1640 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
1641 /// by a FrameDestroy <n>, stack adjustments are identical on all
1642 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
1643 void MachineVerifier::verifyStackFrame() {
1644 int FrameSetupOpcode = TII->getCallFrameSetupOpcode();
1645 int FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
1647 SmallVector<StackStateOfBB, 8> SPState;
1648 SPState.resize(MF->getNumBlockIDs());
1649 SmallPtrSet<const MachineBasicBlock*, 8> Reachable;
1651 // Visit the MBBs in DFS order.
1652 for (df_ext_iterator<const MachineFunction*,
1653 SmallPtrSet<const MachineBasicBlock*, 8> >
1654 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
1655 DFI != DFE; ++DFI) {
1656 const MachineBasicBlock *MBB = *DFI;
1658 StackStateOfBB BBState;
1659 // Check the exit state of the DFS stack predecessor.
1660 if (DFI.getPathLength() >= 2) {
1661 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1662 assert(Reachable.count(StackPred) &&
1663 "DFS stack predecessor is already visited.\n");
1664 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
1665 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
1666 BBState.ExitValue = BBState.EntryValue;
1667 BBState.ExitIsSetup = BBState.EntryIsSetup;
1670 // Update stack state by checking contents of MBB.
1671 for (const auto &I : *MBB) {
1672 if (I.getOpcode() == FrameSetupOpcode) {
1673 // The first operand of a FrameOpcode should be i32.
1674 int Size = I.getOperand(0).getImm();
1676 "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1678 if (BBState.ExitIsSetup)
1679 report("FrameSetup is after another FrameSetup", &I);
1680 BBState.ExitValue -= Size;
1681 BBState.ExitIsSetup = true;
1684 if (I.getOpcode() == FrameDestroyOpcode) {
1685 // The first operand of a FrameOpcode should be i32.
1686 int Size = I.getOperand(0).getImm();
1688 "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1690 if (!BBState.ExitIsSetup)
1691 report("FrameDestroy is not after a FrameSetup", &I);
1692 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
1694 if (BBState.ExitIsSetup && AbsSPAdj != Size) {
1695 report("FrameDestroy <n> is after FrameSetup <m>", &I);
1696 *OS << "FrameDestroy <" << Size << "> is after FrameSetup <"
1697 << AbsSPAdj << ">.\n";
1699 BBState.ExitValue += Size;
1700 BBState.ExitIsSetup = false;
1703 SPState[MBB->getNumber()] = BBState;
1705 // Make sure the exit state of any predecessor is consistent with the entry
1707 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
1708 E = MBB->pred_end(); I != E; ++I) {
1709 if (Reachable.count(*I) &&
1710 (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
1711 SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
1712 report("The exit stack state of a predecessor is inconsistent.", MBB);
1713 *OS << "Predecessor BB#" << (*I)->getNumber() << " has exit state ("
1714 << SPState[(*I)->getNumber()].ExitValue << ", "
1715 << SPState[(*I)->getNumber()].ExitIsSetup
1716 << "), while BB#" << MBB->getNumber() << " has entry state ("
1717 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
1721 // Make sure the entry state of any successor is consistent with the exit
1723 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
1724 E = MBB->succ_end(); I != E; ++I) {
1725 if (Reachable.count(*I) &&
1726 (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
1727 SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
1728 report("The entry stack state of a successor is inconsistent.", MBB);
1729 *OS << "Successor BB#" << (*I)->getNumber() << " has entry state ("
1730 << SPState[(*I)->getNumber()].EntryValue << ", "
1731 << SPState[(*I)->getNumber()].EntryIsSetup
1732 << "), while BB#" << MBB->getNumber() << " has exit state ("
1733 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
1737 // Make sure a basic block with return ends with zero stack adjustment.
1738 if (!MBB->empty() && MBB->back().isReturn()) {
1739 if (BBState.ExitIsSetup)
1740 report("A return block ends with a FrameSetup.", MBB);
1741 if (BBState.ExitValue)
1742 report("A return block ends with a nonzero stack adjustment.", MBB);