e08766d292f3596fb4769f63e25bd03f2ec31196
[oota-llvm.git] / lib / CodeGen / MachineVerifier.cpp
1 //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Pass to verify generated machine code. The following is checked:
11 //
12 // Operand counts: All explicit operands must be present.
13 //
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
16 //
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
19 //
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 //===----------------------------------------------------------------------===//
25
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"
50 using namespace llvm;
51
52 namespace {
53   struct MachineVerifier {
54
55     MachineVerifier(Pass *pass, const char *b) :
56       PASS(pass),
57       Banner(b),
58       OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
59       {}
60
61     bool runOnMachineFunction(MachineFunction &MF);
62
63     Pass *const PASS;
64     const char *Banner;
65     const char *const OutFileName;
66     raw_ostream *OS;
67     const MachineFunction *MF;
68     const TargetMachine *TM;
69     const TargetInstrInfo *TII;
70     const TargetRegisterInfo *TRI;
71     const MachineRegisterInfo *MRI;
72
73     unsigned foundErrors;
74
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;
80
81     const MachineInstr *FirstTerminator;
82     BlockSet FunctionBlocks;
83
84     BitVector regsReserved;
85     RegSet regsLive;
86     RegVector regsDefined, regsDead, regsKilled;
87     RegMaskVector regMasks;
88     RegSet regsLiveInButUnused;
89
90     SlotIndex lastIndex;
91
92     // Add Reg and any sub-registers to RV
93     void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
94       RV.push_back(Reg);
95       if (TargetRegisterInfo::isPhysicalRegister(Reg))
96         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
97           RV.push_back(*SubRegs);
98     }
99
100     struct BBInfo {
101       // Is this MBB reachable from the MF entry point?
102       bool reachable;
103
104       // Vregs that must be live in because they are used without being
105       // defined. Map value is the user.
106       RegMap vregsLiveIn;
107
108       // Regs killed in MBB. They may be defined again, and will then be in both
109       // regsKilled and regsLiveOut.
110       RegSet regsKilled;
111
112       // Regs defined in MBB and live out. Note that vregs passing through may
113       // be live out without being mentioned here.
114       RegSet regsLiveOut;
115
116       // Vregs that pass through MBB untouched. This set is disjoint from
117       // regsKilled and regsLiveOut.
118       RegSet vregsPassed;
119
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;
123
124       // Set versions of block's predecessor and successor lists.
125       BlockSet Preds, Succs;
126
127       BBInfo() : reachable(false) {}
128
129       // Add register to vregsPassed if it belongs there. Return true if
130       // anything changed.
131       bool addPassed(unsigned Reg) {
132         if (!TargetRegisterInfo::isVirtualRegister(Reg))
133           return false;
134         if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
135           return false;
136         return vregsPassed.insert(Reg).second;
137       }
138
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)
143           if (addPassed(*I))
144             changed = true;
145         return changed;
146       }
147
148       // Add register to vregsRequired if it belongs there. Return true if
149       // anything changed.
150       bool addRequired(unsigned Reg) {
151         if (!TargetRegisterInfo::isVirtualRegister(Reg))
152           return false;
153         if (regsLiveOut.count(Reg))
154           return false;
155         return vregsRequired.insert(Reg).second;
156       }
157
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)
162           if (addRequired(*I))
163             changed = true;
164         return changed;
165       }
166
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))
172             changed = true;
173         return changed;
174       }
175
176       // Live-out registers are either in regsLiveOut or vregsPassed.
177       bool isLiveOut(unsigned Reg) const {
178         return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
179       }
180     };
181
182     // Extra register info per MBB.
183     DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
184
185     bool isReserved(unsigned Reg) {
186       return Reg < regsReserved.size() && regsReserved.test(Reg);
187     }
188
189     bool isAllocatable(unsigned Reg) {
190       return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg);
191     }
192
193     // Analysis information if available
194     LiveVariables *LiveVars;
195     LiveIntervals *LiveInts;
196     LiveStacks *LiveStks;
197     SlotIndexes *Indexes;
198
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();
208
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);
219     void report(const char *msg, const MachineBasicBlock *MBB,
220                 const LiveRange &LR);
221
222     void verifyInlineAsm(const MachineInstr *MI);
223
224     void checkLiveness(const MachineOperand *MO, unsigned MONum);
225     void markReachable(const MachineBasicBlock *MBB);
226     void calcRegsPassed();
227     void checkPHIOps(const MachineBasicBlock *MBB);
228
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);
237
238     void verifyStackFrame();
239   };
240
241   struct MachineVerifierPass : public MachineFunctionPass {
242     static char ID; // Pass ID, replacement for typeid
243     const char *const Banner;
244
245     MachineVerifierPass(const char *b = nullptr)
246       : MachineFunctionPass(ID), Banner(b) {
247         initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
248       }
249
250     void getAnalysisUsage(AnalysisUsage &AU) const override {
251       AU.setPreservesAll();
252       MachineFunctionPass::getAnalysisUsage(AU);
253     }
254
255     bool runOnMachineFunction(MachineFunction &MF) override {
256       MF.verify(this, Banner);
257       return false;
258     }
259   };
260
261 }
262
263 char MachineVerifierPass::ID = 0;
264 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
265                 "Verify generated machine code", false, false)
266
267 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
268   return new MachineVerifierPass(Banner);
269 }
270
271 void MachineFunction::verify(Pass *p, const char *Banner) const {
272   MachineVerifier(p, Banner)
273     .runOnMachineFunction(const_cast<MachineFunction&>(*this));
274 }
275
276 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
277   raw_ostream *OutFile = nullptr;
278   if (OutFileName) {
279     std::string ErrorInfo;
280     OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
281                                  sys::fs::F_Append | sys::fs::F_Text);
282     if (!ErrorInfo.empty()) {
283       errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
284       exit(1);
285     }
286
287     OS = OutFile;
288   } else {
289     OS = &errs();
290   }
291
292   foundErrors = 0;
293
294   this->MF = &MF;
295   TM = &MF.getTarget();
296   TII = TM->getSubtargetImpl()->getInstrInfo();
297   TRI = TM->getSubtargetImpl()->getRegisterInfo();
298   MRI = &MF.getRegInfo();
299
300   LiveVars = nullptr;
301   LiveInts = nullptr;
302   LiveStks = nullptr;
303   Indexes = nullptr;
304   if (PASS) {
305     LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
306     // We don't want to verify LiveVariables if LiveIntervals is available.
307     if (!LiveInts)
308       LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
309     LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
310     Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
311   }
312
313   visitMachineFunctionBefore();
314   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
315        MFI!=MFE; ++MFI) {
316     visitMachineBasicBlockBefore(MFI);
317     // Keep track of the current bundle header.
318     const MachineInstr *CurBundle = nullptr;
319     // Do we expect the next instruction to be part of the same bundle?
320     bool InBundle = false;
321
322     for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
323            MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
324       if (MBBI->getParent() != MFI) {
325         report("Bad instruction parent pointer", MFI);
326         *OS << "Instruction: " << *MBBI;
327         continue;
328       }
329
330       // Check for consistent bundle flags.
331       if (InBundle && !MBBI->isBundledWithPred())
332         report("Missing BundledPred flag, "
333                "BundledSucc was set on predecessor", MBBI);
334       if (!InBundle && MBBI->isBundledWithPred())
335         report("BundledPred flag is set, "
336                "but BundledSucc not set on predecessor", MBBI);
337
338       // Is this a bundle header?
339       if (!MBBI->isInsideBundle()) {
340         if (CurBundle)
341           visitMachineBundleAfter(CurBundle);
342         CurBundle = MBBI;
343         visitMachineBundleBefore(CurBundle);
344       } else if (!CurBundle)
345         report("No bundle header", MBBI);
346       visitMachineInstrBefore(MBBI);
347       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
348         visitMachineOperand(&MBBI->getOperand(I), I);
349       visitMachineInstrAfter(MBBI);
350
351       // Was this the last bundled instruction?
352       InBundle = MBBI->isBundledWithSucc();
353     }
354     if (CurBundle)
355       visitMachineBundleAfter(CurBundle);
356     if (InBundle)
357       report("BundledSucc flag set on last instruction in block", &MFI->back());
358     visitMachineBasicBlockAfter(MFI);
359   }
360   visitMachineFunctionAfter();
361
362   if (OutFile)
363     delete OutFile;
364   else if (foundErrors)
365     report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
366
367   // Clean up.
368   regsLive.clear();
369   regsDefined.clear();
370   regsDead.clear();
371   regsKilled.clear();
372   regMasks.clear();
373   regsLiveInButUnused.clear();
374   MBBInfoMap.clear();
375
376   return false;                 // no changes
377 }
378
379 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
380   assert(MF);
381   *OS << '\n';
382   if (!foundErrors++) {
383     if (Banner)
384       *OS << "# " << Banner << '\n';
385     MF->print(*OS, Indexes);
386   }
387   *OS << "*** Bad machine code: " << msg << " ***\n"
388       << "- function:    " << MF->getName() << "\n";
389 }
390
391 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
392   assert(MBB);
393   report(msg, MBB->getParent());
394   *OS << "- basic block: BB#" << MBB->getNumber()
395       << ' ' << MBB->getName()
396       << " (" << (const void*)MBB << ')';
397   if (Indexes)
398     *OS << " [" << Indexes->getMBBStartIdx(MBB)
399         << ';' <<  Indexes->getMBBEndIdx(MBB) << ')';
400   *OS << '\n';
401 }
402
403 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
404   assert(MI);
405   report(msg, MI->getParent());
406   *OS << "- instruction: ";
407   if (Indexes && Indexes->hasIndex(MI))
408     *OS << Indexes->getInstructionIndex(MI) << '\t';
409   MI->print(*OS, TM);
410 }
411
412 void MachineVerifier::report(const char *msg,
413                              const MachineOperand *MO, unsigned MONum) {
414   assert(MO);
415   report(msg, MO->getParent());
416   *OS << "- operand " << MONum << ":   ";
417   MO->print(*OS, TM);
418   *OS << "\n";
419 }
420
421 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
422                              const LiveInterval &LI) {
423   report(msg, MF);
424   *OS << "- interval:    " << LI << '\n';
425 }
426
427 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
428                              const LiveInterval &LI) {
429   report(msg, MBB);
430   *OS << "- interval:    " << LI << '\n';
431 }
432
433 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
434                              const LiveRange &LR) {
435   report(msg, MBB);
436   *OS << "- liverange:    " << LR << "\n";
437 }
438
439 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
440                              const LiveRange &LR) {
441   report(msg, MF);
442   *OS << "- liverange:    " << LR << "\n";
443 }
444
445 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
446   BBInfo &MInfo = MBBInfoMap[MBB];
447   if (!MInfo.reachable) {
448     MInfo.reachable = true;
449     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
450            SuE = MBB->succ_end(); SuI != SuE; ++SuI)
451       markReachable(*SuI);
452   }
453 }
454
455 void MachineVerifier::visitMachineFunctionBefore() {
456   lastIndex = SlotIndex();
457   regsReserved = MRI->getReservedRegs();
458
459   // A sub-register of a reserved register is also reserved
460   for (int Reg = regsReserved.find_first(); Reg>=0;
461        Reg = regsReserved.find_next(Reg)) {
462     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
463       // FIXME: This should probably be:
464       // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register");
465       regsReserved.set(*SubRegs);
466     }
467   }
468
469   markReachable(&MF->front());
470
471   // Build a set of the basic blocks in the function.
472   FunctionBlocks.clear();
473   for (const auto &MBB : *MF) {
474     FunctionBlocks.insert(&MBB);
475     BBInfo &MInfo = MBBInfoMap[&MBB];
476
477     MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
478     if (MInfo.Preds.size() != MBB.pred_size())
479       report("MBB has duplicate entries in its predecessor list.", &MBB);
480
481     MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
482     if (MInfo.Succs.size() != MBB.succ_size())
483       report("MBB has duplicate entries in its successor list.", &MBB);
484   }
485
486   // Check that the register use lists are sane.
487   MRI->verifyUseLists();
488
489   verifyStackFrame();
490 }
491
492 // Does iterator point to a and b as the first two elements?
493 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
494                       const MachineBasicBlock *a, const MachineBasicBlock *b) {
495   if (*i == a)
496     return *++i == b;
497   if (*i == b)
498     return *++i == a;
499   return false;
500 }
501
502 void
503 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
504   FirstTerminator = nullptr;
505
506   if (MRI->isSSA()) {
507     // If this block has allocatable physical registers live-in, check that
508     // it is an entry block or landing pad.
509     for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
510            LE = MBB->livein_end();
511          LI != LE; ++LI) {
512       unsigned reg = *LI;
513       if (isAllocatable(reg) && !MBB->isLandingPad() &&
514           MBB != MBB->getParent()->begin()) {
515         report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
516       }
517     }
518   }
519
520   // Count the number of landing pad successors.
521   SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
522   for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
523        E = MBB->succ_end(); I != E; ++I) {
524     if ((*I)->isLandingPad())
525       LandingPadSuccs.insert(*I);
526     if (!FunctionBlocks.count(*I))
527       report("MBB has successor that isn't part of the function.", MBB);
528     if (!MBBInfoMap[*I].Preds.count(MBB)) {
529       report("Inconsistent CFG", MBB);
530       *OS << "MBB is not in the predecessor list of the successor BB#"
531           << (*I)->getNumber() << ".\n";
532     }
533   }
534
535   // Check the predecessor list.
536   for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
537        E = MBB->pred_end(); I != E; ++I) {
538     if (!FunctionBlocks.count(*I))
539       report("MBB has predecessor that isn't part of the function.", MBB);
540     if (!MBBInfoMap[*I].Succs.count(MBB)) {
541       report("Inconsistent CFG", MBB);
542       *OS << "MBB is not in the successor list of the predecessor BB#"
543           << (*I)->getNumber() << ".\n";
544     }
545   }
546
547   const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
548   const BasicBlock *BB = MBB->getBasicBlock();
549   if (LandingPadSuccs.size() > 1 &&
550       !(AsmInfo &&
551         AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
552         BB && isa<SwitchInst>(BB->getTerminator())))
553     report("MBB has more than one landing pad successor", MBB);
554
555   // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
556   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
557   SmallVector<MachineOperand, 4> Cond;
558   if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
559                           TBB, FBB, Cond)) {
560     // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
561     // check whether its answers match up with reality.
562     if (!TBB && !FBB) {
563       // Block falls through to its successor.
564       MachineFunction::const_iterator MBBI = MBB;
565       ++MBBI;
566       if (MBBI == MF->end()) {
567         // It's possible that the block legitimately ends with a noreturn
568         // call or an unreachable, in which case it won't actually fall
569         // out the bottom of the function.
570       } else if (MBB->succ_size() == LandingPadSuccs.size()) {
571         // It's possible that the block legitimately ends with a noreturn
572         // call or an unreachable, in which case it won't actuall fall
573         // out of the block.
574       } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
575         report("MBB exits via unconditional fall-through but doesn't have "
576                "exactly one CFG successor!", MBB);
577       } else if (!MBB->isSuccessor(MBBI)) {
578         report("MBB exits via unconditional fall-through but its successor "
579                "differs from its CFG successor!", MBB);
580       }
581       if (!MBB->empty() && MBB->back().isBarrier() &&
582           !TII->isPredicated(&MBB->back())) {
583         report("MBB exits via unconditional fall-through but ends with a "
584                "barrier instruction!", MBB);
585       }
586       if (!Cond.empty()) {
587         report("MBB exits via unconditional fall-through but has a condition!",
588                MBB);
589       }
590     } else if (TBB && !FBB && Cond.empty()) {
591       // Block unconditionally branches somewhere.
592       if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
593         report("MBB exits via unconditional branch but doesn't have "
594                "exactly one CFG successor!", MBB);
595       } else if (!MBB->isSuccessor(TBB)) {
596         report("MBB exits via unconditional branch but the CFG "
597                "successor doesn't match the actual successor!", MBB);
598       }
599       if (MBB->empty()) {
600         report("MBB exits via unconditional branch but doesn't contain "
601                "any instructions!", MBB);
602       } else if (!MBB->back().isBarrier()) {
603         report("MBB exits via unconditional branch but doesn't end with a "
604                "barrier instruction!", MBB);
605       } else if (!MBB->back().isTerminator()) {
606         report("MBB exits via unconditional branch but the branch isn't a "
607                "terminator instruction!", MBB);
608       }
609     } else if (TBB && !FBB && !Cond.empty()) {
610       // Block conditionally branches somewhere, otherwise falls through.
611       MachineFunction::const_iterator MBBI = MBB;
612       ++MBBI;
613       if (MBBI == MF->end()) {
614         report("MBB conditionally falls through out of function!", MBB);
615       } else if (MBB->succ_size() == 1) {
616         // A conditional branch with only one successor is weird, but allowed.
617         if (&*MBBI != TBB)
618           report("MBB exits via conditional branch/fall-through but only has "
619                  "one CFG successor!", MBB);
620         else if (TBB != *MBB->succ_begin())
621           report("MBB exits via conditional branch/fall-through but the CFG "
622                  "successor don't match the actual successor!", MBB);
623       } else if (MBB->succ_size() != 2) {
624         report("MBB exits via conditional branch/fall-through but doesn't have "
625                "exactly two CFG successors!", MBB);
626       } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
627         report("MBB exits via conditional branch/fall-through but the CFG "
628                "successors don't match the actual successors!", MBB);
629       }
630       if (MBB->empty()) {
631         report("MBB exits via conditional branch/fall-through but doesn't "
632                "contain any instructions!", MBB);
633       } else if (MBB->back().isBarrier()) {
634         report("MBB exits via conditional branch/fall-through but ends with a "
635                "barrier instruction!", MBB);
636       } else if (!MBB->back().isTerminator()) {
637         report("MBB exits via conditional branch/fall-through but the branch "
638                "isn't a terminator instruction!", MBB);
639       }
640     } else if (TBB && FBB) {
641       // Block conditionally branches somewhere, otherwise branches
642       // somewhere else.
643       if (MBB->succ_size() == 1) {
644         // A conditional branch with only one successor is weird, but allowed.
645         if (FBB != TBB)
646           report("MBB exits via conditional branch/branch through but only has "
647                  "one CFG successor!", MBB);
648         else if (TBB != *MBB->succ_begin())
649           report("MBB exits via conditional branch/branch through but the CFG "
650                  "successor don't match the actual successor!", MBB);
651       } else if (MBB->succ_size() != 2) {
652         report("MBB exits via conditional branch/branch but doesn't have "
653                "exactly two CFG successors!", MBB);
654       } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
655         report("MBB exits via conditional branch/branch but the CFG "
656                "successors don't match the actual successors!", MBB);
657       }
658       if (MBB->empty()) {
659         report("MBB exits via conditional branch/branch but doesn't "
660                "contain any instructions!", MBB);
661       } else if (!MBB->back().isBarrier()) {
662         report("MBB exits via conditional branch/branch but doesn't end with a "
663                "barrier instruction!", MBB);
664       } else if (!MBB->back().isTerminator()) {
665         report("MBB exits via conditional branch/branch but the branch "
666                "isn't a terminator instruction!", MBB);
667       }
668       if (Cond.empty()) {
669         report("MBB exits via conditinal branch/branch but there's no "
670                "condition!", MBB);
671       }
672     } else {
673       report("AnalyzeBranch returned invalid data!", MBB);
674     }
675   }
676
677   regsLive.clear();
678   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
679          E = MBB->livein_end(); I != E; ++I) {
680     if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
681       report("MBB live-in list contains non-physical register", MBB);
682       continue;
683     }
684     for (MCSubRegIterator SubRegs(*I, TRI, /*IncludeSelf=*/true);
685          SubRegs.isValid(); ++SubRegs)
686       regsLive.insert(*SubRegs);
687   }
688   regsLiveInButUnused = regsLive;
689
690   const MachineFrameInfo *MFI = MF->getFrameInfo();
691   assert(MFI && "Function has no frame info");
692   BitVector PR = MFI->getPristineRegs(MBB);
693   for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
694     for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
695          SubRegs.isValid(); ++SubRegs)
696       regsLive.insert(*SubRegs);
697   }
698
699   regsKilled.clear();
700   regsDefined.clear();
701
702   if (Indexes)
703     lastIndex = Indexes->getMBBStartIdx(MBB);
704 }
705
706 // This function gets called for all bundle headers, including normal
707 // stand-alone unbundled instructions.
708 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
709   if (Indexes && Indexes->hasIndex(MI)) {
710     SlotIndex idx = Indexes->getInstructionIndex(MI);
711     if (!(idx > lastIndex)) {
712       report("Instruction index out of order", MI);
713       *OS << "Last instruction was at " << lastIndex << '\n';
714     }
715     lastIndex = idx;
716   }
717
718   // Ensure non-terminators don't follow terminators.
719   // Ignore predicated terminators formed by if conversion.
720   // FIXME: If conversion shouldn't need to violate this rule.
721   if (MI->isTerminator() && !TII->isPredicated(MI)) {
722     if (!FirstTerminator)
723       FirstTerminator = MI;
724   } else if (FirstTerminator) {
725     report("Non-terminator instruction after the first terminator", MI);
726     *OS << "First terminator was:\t" << *FirstTerminator;
727   }
728 }
729
730 // The operands on an INLINEASM instruction must follow a template.
731 // Verify that the flag operands make sense.
732 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
733   // The first two operands on INLINEASM are the asm string and global flags.
734   if (MI->getNumOperands() < 2) {
735     report("Too few operands on inline asm", MI);
736     return;
737   }
738   if (!MI->getOperand(0).isSymbol())
739     report("Asm string must be an external symbol", MI);
740   if (!MI->getOperand(1).isImm())
741     report("Asm flags must be an immediate", MI);
742   // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
743   // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16.
744   if (!isUInt<5>(MI->getOperand(1).getImm()))
745     report("Unknown asm flags", &MI->getOperand(1), 1);
746
747   assert(InlineAsm::MIOp_FirstOperand == 2 && "Asm format changed");
748
749   unsigned OpNo = InlineAsm::MIOp_FirstOperand;
750   unsigned NumOps;
751   for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
752     const MachineOperand &MO = MI->getOperand(OpNo);
753     // There may be implicit ops after the fixed operands.
754     if (!MO.isImm())
755       break;
756     NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
757   }
758
759   if (OpNo > MI->getNumOperands())
760     report("Missing operands in last group", MI);
761
762   // An optional MDNode follows the groups.
763   if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
764     ++OpNo;
765
766   // All trailing operands must be implicit registers.
767   for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
768     const MachineOperand &MO = MI->getOperand(OpNo);
769     if (!MO.isReg() || !MO.isImplicit())
770       report("Expected implicit register after groups", &MO, OpNo);
771   }
772 }
773
774 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
775   const MCInstrDesc &MCID = MI->getDesc();
776   if (MI->getNumOperands() < MCID.getNumOperands()) {
777     report("Too few operands", MI);
778     *OS << MCID.getNumOperands() << " operands expected, but "
779         << MI->getNumOperands() << " given.\n";
780   }
781
782   // Check the tied operands.
783   if (MI->isInlineAsm())
784     verifyInlineAsm(MI);
785
786   // Check the MachineMemOperands for basic consistency.
787   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
788        E = MI->memoperands_end(); I != E; ++I) {
789     if ((*I)->isLoad() && !MI->mayLoad())
790       report("Missing mayLoad flag", MI);
791     if ((*I)->isStore() && !MI->mayStore())
792       report("Missing mayStore flag", MI);
793   }
794
795   // Debug values must not have a slot index.
796   // Other instructions must have one, unless they are inside a bundle.
797   if (LiveInts) {
798     bool mapped = !LiveInts->isNotInMIMap(MI);
799     if (MI->isDebugValue()) {
800       if (mapped)
801         report("Debug instruction has a slot index", MI);
802     } else if (MI->isInsideBundle()) {
803       if (mapped)
804         report("Instruction inside bundle has a slot index", MI);
805     } else {
806       if (!mapped)
807         report("Missing slot index", MI);
808     }
809   }
810
811   StringRef ErrorInfo;
812   if (!TII->verifyInstruction(MI, ErrorInfo))
813     report(ErrorInfo.data(), MI);
814 }
815
816 void
817 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
818   const MachineInstr *MI = MO->getParent();
819   const MCInstrDesc &MCID = MI->getDesc();
820
821   // The first MCID.NumDefs operands must be explicit register defines
822   if (MONum < MCID.getNumDefs()) {
823     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
824     if (!MO->isReg())
825       report("Explicit definition must be a register", MO, MONum);
826     else if (!MO->isDef() && !MCOI.isOptionalDef())
827       report("Explicit definition marked as use", MO, MONum);
828     else if (MO->isImplicit())
829       report("Explicit definition marked as implicit", MO, MONum);
830   } else if (MONum < MCID.getNumOperands()) {
831     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
832     // Don't check if it's the last operand in a variadic instruction. See,
833     // e.g., LDM_RET in the arm back end.
834     if (MO->isReg() &&
835         !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
836       if (MO->isDef() && !MCOI.isOptionalDef())
837         report("Explicit operand marked as def", MO, MONum);
838       if (MO->isImplicit())
839         report("Explicit operand marked as implicit", MO, MONum);
840     }
841
842     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
843     if (TiedTo != -1) {
844       if (!MO->isReg())
845         report("Tied use must be a register", MO, MONum);
846       else if (!MO->isTied())
847         report("Operand should be tied", MO, MONum);
848       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
849         report("Tied def doesn't match MCInstrDesc", MO, MONum);
850     } else if (MO->isReg() && MO->isTied())
851       report("Explicit operand should not be tied", MO, MONum);
852   } else {
853     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
854     if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
855       report("Extra explicit operand on non-variadic instruction", MO, MONum);
856   }
857
858   switch (MO->getType()) {
859   case MachineOperand::MO_Register: {
860     const unsigned Reg = MO->getReg();
861     if (!Reg)
862       return;
863     if (MRI->tracksLiveness() && !MI->isDebugValue())
864       checkLiveness(MO, MONum);
865
866     // Verify the consistency of tied operands.
867     if (MO->isTied()) {
868       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
869       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
870       if (!OtherMO.isReg())
871         report("Must be tied to a register", MO, MONum);
872       if (!OtherMO.isTied())
873         report("Missing tie flags on tied operand", MO, MONum);
874       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
875         report("Inconsistent tie links", MO, MONum);
876       if (MONum < MCID.getNumDefs()) {
877         if (OtherIdx < MCID.getNumOperands()) {
878           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
879             report("Explicit def tied to explicit use without tie constraint",
880                    MO, MONum);
881         } else {
882           if (!OtherMO.isImplicit())
883             report("Explicit def should be tied to implicit use", MO, MONum);
884         }
885       }
886     }
887
888     // Verify two-address constraints after leaving SSA form.
889     unsigned DefIdx;
890     if (!MRI->isSSA() && MO->isUse() &&
891         MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
892         Reg != MI->getOperand(DefIdx).getReg())
893       report("Two-address instruction operands must be identical", MO, MONum);
894
895     // Check register classes.
896     if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
897       unsigned SubIdx = MO->getSubReg();
898
899       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
900         if (SubIdx) {
901           report("Illegal subregister index for physical register", MO, MONum);
902           return;
903         }
904         if (const TargetRegisterClass *DRC =
905               TII->getRegClass(MCID, MONum, TRI, *MF)) {
906           if (!DRC->contains(Reg)) {
907             report("Illegal physical register for instruction", MO, MONum);
908             *OS << TRI->getName(Reg) << " is not a "
909                 << DRC->getName() << " register.\n";
910           }
911         }
912       } else {
913         // Virtual register.
914         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
915         if (SubIdx) {
916           const TargetRegisterClass *SRC =
917             TRI->getSubClassWithSubReg(RC, SubIdx);
918           if (!SRC) {
919             report("Invalid subregister index for virtual register", MO, MONum);
920             *OS << "Register class " << RC->getName()
921                 << " does not support subreg index " << SubIdx << "\n";
922             return;
923           }
924           if (RC != SRC) {
925             report("Invalid register class for subregister index", MO, MONum);
926             *OS << "Register class " << RC->getName()
927                 << " does not fully support subreg index " << SubIdx << "\n";
928             return;
929           }
930         }
931         if (const TargetRegisterClass *DRC =
932               TII->getRegClass(MCID, MONum, TRI, *MF)) {
933           if (SubIdx) {
934             const TargetRegisterClass *SuperRC =
935               TRI->getLargestLegalSuperClass(RC);
936             if (!SuperRC) {
937               report("No largest legal super class exists.", MO, MONum);
938               return;
939             }
940             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
941             if (!DRC) {
942               report("No matching super-reg register class.", MO, MONum);
943               return;
944             }
945           }
946           if (!RC->hasSuperClassEq(DRC)) {
947             report("Illegal virtual register for instruction", MO, MONum);
948             *OS << "Expected a " << DRC->getName() << " register, but got a "
949                 << RC->getName() << " register\n";
950           }
951         }
952       }
953     }
954     break;
955   }
956
957   case MachineOperand::MO_RegisterMask:
958     regMasks.push_back(MO->getRegMask());
959     break;
960
961   case MachineOperand::MO_MachineBasicBlock:
962     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
963       report("PHI operand is not in the CFG", MO, MONum);
964     break;
965
966   case MachineOperand::MO_FrameIndex:
967     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
968         LiveInts && !LiveInts->isNotInMIMap(MI)) {
969       LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
970       SlotIndex Idx = LiveInts->getInstructionIndex(MI);
971       if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
972         report("Instruction loads from dead spill slot", MO, MONum);
973         *OS << "Live stack: " << LI << '\n';
974       }
975       if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
976         report("Instruction stores to dead spill slot", MO, MONum);
977         *OS << "Live stack: " << LI << '\n';
978       }
979     }
980     break;
981
982   default:
983     break;
984   }
985 }
986
987 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
988   const MachineInstr *MI = MO->getParent();
989   const unsigned Reg = MO->getReg();
990
991   // Both use and def operands can read a register.
992   if (MO->readsReg()) {
993     regsLiveInButUnused.erase(Reg);
994
995     if (MO->isKill())
996       addRegWithSubRegs(regsKilled, Reg);
997
998     // Check that LiveVars knows this kill.
999     if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1000         MO->isKill()) {
1001       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1002       if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end())
1003         report("Kill missing from LiveVariables", MO, MONum);
1004     }
1005
1006     // Check LiveInts liveness and kill.
1007     if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
1008       SlotIndex UseIdx = LiveInts->getInstructionIndex(MI);
1009       // Check the cached regunit intervals.
1010       if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1011         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1012           if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) {
1013             LiveQueryResult LRQ = LR->Query(UseIdx);
1014             if (!LRQ.valueIn()) {
1015               report("No live segment at use", MO, MONum);
1016               *OS << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI)
1017                   << ' ' << *LR << '\n';
1018             }
1019             if (MO->isKill() && !LRQ.isKill()) {
1020               report("Live range continues after kill flag", MO, MONum);
1021               *OS << PrintRegUnit(*Units, TRI) << ' ' << *LR << '\n';
1022             }
1023           }
1024         }
1025       }
1026
1027       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1028         if (LiveInts->hasInterval(Reg)) {
1029           // This is a virtual register interval.
1030           const LiveInterval &LI = LiveInts->getInterval(Reg);
1031           LiveQueryResult LRQ = LI.Query(UseIdx);
1032           if (!LRQ.valueIn()) {
1033             report("No live segment at use", MO, MONum);
1034             *OS << UseIdx << " is not live in " << LI << '\n';
1035           }
1036           // Check for extra kill flags.
1037           // Note that we allow missing kill flags for now.
1038           if (MO->isKill() && !LRQ.isKill()) {
1039             report("Live range continues after kill flag", MO, MONum);
1040             *OS << "Live range: " << LI << '\n';
1041           }
1042         } else {
1043           report("Virtual register has no live interval", MO, MONum);
1044         }
1045       }
1046     }
1047
1048     // Use of a dead register.
1049     if (!regsLive.count(Reg)) {
1050       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1051         // Reserved registers may be used even when 'dead'.
1052         if (!isReserved(Reg))
1053           report("Using an undefined physical register", MO, MONum);
1054       } else if (MRI->def_empty(Reg)) {
1055         report("Reading virtual register without a def", MO, MONum);
1056       } else {
1057         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1058         // We don't know which virtual registers are live in, so only complain
1059         // if vreg was killed in this MBB. Otherwise keep track of vregs that
1060         // must be live in. PHI instructions are handled separately.
1061         if (MInfo.regsKilled.count(Reg))
1062           report("Using a killed virtual register", MO, MONum);
1063         else if (!MI->isPHI())
1064           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1065       }
1066     }
1067   }
1068
1069   if (MO->isDef()) {
1070     // Register defined.
1071     // TODO: verify that earlyclobber ops are not used.
1072     if (MO->isDead())
1073       addRegWithSubRegs(regsDead, Reg);
1074     else
1075       addRegWithSubRegs(regsDefined, Reg);
1076
1077     // Verify SSA form.
1078     if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1079         std::next(MRI->def_begin(Reg)) != MRI->def_end())
1080       report("Multiple virtual register defs in SSA form", MO, MONum);
1081
1082     // Check LiveInts for a live segment, but only for virtual registers.
1083     if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
1084         !LiveInts->isNotInMIMap(MI)) {
1085       SlotIndex DefIdx = LiveInts->getInstructionIndex(MI);
1086       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1087       if (LiveInts->hasInterval(Reg)) {
1088         const LiveInterval &LI = LiveInts->getInterval(Reg);
1089         if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
1090           assert(VNI && "NULL valno is not allowed");
1091           if (VNI->def != DefIdx) {
1092             report("Inconsistent valno->def", MO, MONum);
1093             *OS << "Valno " << VNI->id << " is not defined at "
1094               << DefIdx << " in " << LI << '\n';
1095           }
1096         } else {
1097           report("No live segment at def", MO, MONum);
1098           *OS << DefIdx << " is not live in " << LI << '\n';
1099         }
1100         // Check that, if the dead def flag is present, LiveInts agree.
1101         if (MO->isDead()) {
1102           LiveQueryResult LRQ = LI.Query(DefIdx);
1103           if (!LRQ.isDeadDef()) {
1104             report("Live range continues after dead def flag", MO, MONum);
1105             *OS << "Live range: " << LI << '\n';
1106           }
1107         }
1108       } else {
1109         report("Virtual register has no Live interval", MO, MONum);
1110       }
1111     }
1112   }
1113 }
1114
1115 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
1116 }
1117
1118 // This function gets called after visiting all instructions in a bundle. The
1119 // argument points to the bundle header.
1120 // Normal stand-alone instructions are also considered 'bundles', and this
1121 // function is called for all of them.
1122 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1123   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1124   set_union(MInfo.regsKilled, regsKilled);
1125   set_subtract(regsLive, regsKilled); regsKilled.clear();
1126   // Kill any masked registers.
1127   while (!regMasks.empty()) {
1128     const uint32_t *Mask = regMasks.pop_back_val();
1129     for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1130       if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1131           MachineOperand::clobbersPhysReg(Mask, *I))
1132         regsDead.push_back(*I);
1133   }
1134   set_subtract(regsLive, regsDead);   regsDead.clear();
1135   set_union(regsLive, regsDefined);   regsDefined.clear();
1136 }
1137
1138 void
1139 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1140   MBBInfoMap[MBB].regsLiveOut = regsLive;
1141   regsLive.clear();
1142
1143   if (Indexes) {
1144     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1145     if (!(stop > lastIndex)) {
1146       report("Block ends before last instruction index", MBB);
1147       *OS << "Block ends at " << stop
1148           << " last instruction was at " << lastIndex << '\n';
1149     }
1150     lastIndex = stop;
1151   }
1152 }
1153
1154 // Calculate the largest possible vregsPassed sets. These are the registers that
1155 // can pass through an MBB live, but may not be live every time. It is assumed
1156 // that all vregsPassed sets are empty before the call.
1157 void MachineVerifier::calcRegsPassed() {
1158   // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1159   // have any vregsPassed.
1160   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1161   for (const auto &MBB : *MF) {
1162     BBInfo &MInfo = MBBInfoMap[&MBB];
1163     if (!MInfo.reachable)
1164       continue;
1165     for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1166            SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1167       BBInfo &SInfo = MBBInfoMap[*SuI];
1168       if (SInfo.addPassed(MInfo.regsLiveOut))
1169         todo.insert(*SuI);
1170     }
1171   }
1172
1173   // Iteratively push vregsPassed to successors. This will converge to the same
1174   // final state regardless of DenseSet iteration order.
1175   while (!todo.empty()) {
1176     const MachineBasicBlock *MBB = *todo.begin();
1177     todo.erase(MBB);
1178     BBInfo &MInfo = MBBInfoMap[MBB];
1179     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1180            SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1181       if (*SuI == MBB)
1182         continue;
1183       BBInfo &SInfo = MBBInfoMap[*SuI];
1184       if (SInfo.addPassed(MInfo.vregsPassed))
1185         todo.insert(*SuI);
1186     }
1187   }
1188 }
1189
1190 // Calculate the set of virtual registers that must be passed through each basic
1191 // block in order to satisfy the requirements of successor blocks. This is very
1192 // similar to calcRegsPassed, only backwards.
1193 void MachineVerifier::calcRegsRequired() {
1194   // First push live-in regs to predecessors' vregsRequired.
1195   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1196   for (const auto &MBB : *MF) {
1197     BBInfo &MInfo = MBBInfoMap[&MBB];
1198     for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1199            PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1200       BBInfo &PInfo = MBBInfoMap[*PrI];
1201       if (PInfo.addRequired(MInfo.vregsLiveIn))
1202         todo.insert(*PrI);
1203     }
1204   }
1205
1206   // Iteratively push vregsRequired to predecessors. This will converge to the
1207   // same final state regardless of DenseSet iteration order.
1208   while (!todo.empty()) {
1209     const MachineBasicBlock *MBB = *todo.begin();
1210     todo.erase(MBB);
1211     BBInfo &MInfo = MBBInfoMap[MBB];
1212     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1213            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1214       if (*PrI == MBB)
1215         continue;
1216       BBInfo &SInfo = MBBInfoMap[*PrI];
1217       if (SInfo.addRequired(MInfo.vregsRequired))
1218         todo.insert(*PrI);
1219     }
1220   }
1221 }
1222
1223 // Check PHI instructions at the beginning of MBB. It is assumed that
1224 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1225 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
1226   SmallPtrSet<const MachineBasicBlock*, 8> seen;
1227   for (const auto &BBI : *MBB) {
1228     if (!BBI.isPHI())
1229       break;
1230     seen.clear();
1231
1232     for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
1233       unsigned Reg = BBI.getOperand(i).getReg();
1234       const MachineBasicBlock *Pre = BBI.getOperand(i + 1).getMBB();
1235       if (!Pre->isSuccessor(MBB))
1236         continue;
1237       seen.insert(Pre);
1238       BBInfo &PrInfo = MBBInfoMap[Pre];
1239       if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
1240         report("PHI operand is not live-out from predecessor",
1241                &BBI.getOperand(i), i);
1242     }
1243
1244     // Did we see all predecessors?
1245     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1246            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1247       if (!seen.count(*PrI)) {
1248         report("Missing PHI operand", &BBI);
1249         *OS << "BB#" << (*PrI)->getNumber()
1250             << " is a predecessor according to the CFG.\n";
1251       }
1252     }
1253   }
1254 }
1255
1256 void MachineVerifier::visitMachineFunctionAfter() {
1257   calcRegsPassed();
1258
1259   for (const auto &MBB : *MF) {
1260     BBInfo &MInfo = MBBInfoMap[&MBB];
1261
1262     // Skip unreachable MBBs.
1263     if (!MInfo.reachable)
1264       continue;
1265
1266     checkPHIOps(&MBB);
1267   }
1268
1269   // Now check liveness info if available
1270   calcRegsRequired();
1271
1272   // Check for killed virtual registers that should be live out.
1273   for (const auto &MBB : *MF) {
1274     BBInfo &MInfo = MBBInfoMap[&MBB];
1275     for (RegSet::iterator
1276          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1277          ++I)
1278       if (MInfo.regsKilled.count(*I)) {
1279         report("Virtual register killed in block, but needed live out.", &MBB);
1280         *OS << "Virtual register " << PrintReg(*I)
1281             << " is used after the block.\n";
1282       }
1283   }
1284
1285   if (!MF->empty()) {
1286     BBInfo &MInfo = MBBInfoMap[&MF->front()];
1287     for (RegSet::iterator
1288          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1289          ++I)
1290       report("Virtual register def doesn't dominate all uses.",
1291              MRI->getVRegDef(*I));
1292   }
1293
1294   if (LiveVars)
1295     verifyLiveVariables();
1296   if (LiveInts)
1297     verifyLiveIntervals();
1298 }
1299
1300 void MachineVerifier::verifyLiveVariables() {
1301   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1302   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1303     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1304     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1305     for (const auto &MBB : *MF) {
1306       BBInfo &MInfo = MBBInfoMap[&MBB];
1307
1308       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1309       if (MInfo.vregsRequired.count(Reg)) {
1310         if (!VI.AliveBlocks.test(MBB.getNumber())) {
1311           report("LiveVariables: Block missing from AliveBlocks", &MBB);
1312           *OS << "Virtual register " << PrintReg(Reg)
1313               << " must be live through the block.\n";
1314         }
1315       } else {
1316         if (VI.AliveBlocks.test(MBB.getNumber())) {
1317           report("LiveVariables: Block should not be in AliveBlocks", &MBB);
1318           *OS << "Virtual register " << PrintReg(Reg)
1319               << " is not needed live through the block.\n";
1320         }
1321       }
1322     }
1323   }
1324 }
1325
1326 void MachineVerifier::verifyLiveIntervals() {
1327   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1328   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1329     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1330
1331     // Spilling and splitting may leave unused registers around. Skip them.
1332     if (MRI->reg_nodbg_empty(Reg))
1333       continue;
1334
1335     if (!LiveInts->hasInterval(Reg)) {
1336       report("Missing live interval for virtual register", MF);
1337       *OS << PrintReg(Reg, TRI) << " still has defs or uses\n";
1338       continue;
1339     }
1340
1341     const LiveInterval &LI = LiveInts->getInterval(Reg);
1342     assert(Reg == LI.reg && "Invalid reg to interval mapping");
1343     verifyLiveInterval(LI);
1344   }
1345
1346   // Verify all the cached regunit intervals.
1347   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1348     if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1349       verifyLiveRange(*LR, i);
1350 }
1351
1352 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1353                                            const VNInfo *VNI,
1354                                            unsigned Reg) {
1355   if (VNI->isUnused())
1356     return;
1357
1358   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1359
1360   if (!DefVNI) {
1361     report("Valno not live at def and not marked unused", MF, LR);
1362     *OS << "Valno #" << VNI->id << '\n';
1363     return;
1364   }
1365
1366   if (DefVNI != VNI) {
1367     report("Live segment at def has different valno", MF, LR);
1368     *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1369         << " where valno #" << DefVNI->id << " is live\n";
1370     return;
1371   }
1372
1373   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1374   if (!MBB) {
1375     report("Invalid definition index", MF, LR);
1376     *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1377         << " in " << LR << '\n';
1378     return;
1379   }
1380
1381   if (VNI->isPHIDef()) {
1382     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1383       report("PHIDef value is not defined at MBB start", MBB, LR);
1384       *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1385           << ", not at the beginning of BB#" << MBB->getNumber() << '\n';
1386     }
1387     return;
1388   }
1389
1390   // Non-PHI def.
1391   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1392   if (!MI) {
1393     report("No instruction at def index", MBB, LR);
1394     *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1395     return;
1396   }
1397
1398   if (Reg != 0) {
1399     bool hasDef = false;
1400     bool isEarlyClobber = false;
1401     for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1402       if (!MOI->isReg() || !MOI->isDef())
1403         continue;
1404       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1405         if (MOI->getReg() != Reg)
1406           continue;
1407       } else {
1408         if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1409             !TRI->hasRegUnit(MOI->getReg(), Reg))
1410           continue;
1411       }
1412       hasDef = true;
1413       if (MOI->isEarlyClobber())
1414         isEarlyClobber = true;
1415     }
1416
1417     if (!hasDef) {
1418       report("Defining instruction does not modify register", MI);
1419       *OS << "Valno #" << VNI->id << " in " << LR << '\n';
1420     }
1421
1422     // Early clobber defs begin at USE slots, but other defs must begin at
1423     // DEF slots.
1424     if (isEarlyClobber) {
1425       if (!VNI->def.isEarlyClobber()) {
1426         report("Early clobber def must be at an early-clobber slot", MBB, LR);
1427         *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1428       }
1429     } else if (!VNI->def.isRegister()) {
1430       report("Non-PHI, non-early clobber def must be at a register slot",
1431              MBB, LR);
1432       *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1433     }
1434   }
1435 }
1436
1437 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1438                                              const LiveRange::const_iterator I,
1439                                              unsigned Reg) {
1440   const LiveRange::Segment &S = *I;
1441   const VNInfo *VNI = S.valno;
1442   assert(VNI && "Live segment has no valno");
1443
1444   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1445     report("Foreign valno in live segment", MF, LR);
1446     *OS << S << " has a bad valno\n";
1447   }
1448
1449   if (VNI->isUnused()) {
1450     report("Live segment valno is marked unused", MF, LR);
1451     *OS << S << '\n';
1452   }
1453
1454   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1455   if (!MBB) {
1456     report("Bad start of live segment, no basic block", MF, LR);
1457     *OS << S << '\n';
1458     return;
1459   }
1460   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1461   if (S.start != MBBStartIdx && S.start != VNI->def) {
1462     report("Live segment must begin at MBB entry or valno def", MBB, LR);
1463     *OS << S << '\n';
1464   }
1465
1466   const MachineBasicBlock *EndMBB =
1467     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
1468   if (!EndMBB) {
1469     report("Bad end of live segment, no basic block", MF, LR);
1470     *OS << S << '\n';
1471     return;
1472   }
1473
1474   // No more checks for live-out segments.
1475   if (S.end == LiveInts->getMBBEndIdx(EndMBB))
1476     return;
1477
1478   // RegUnit intervals are allowed dead phis.
1479   if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
1480       S.start == VNI->def && S.end == VNI->def.getDeadSlot())
1481     return;
1482
1483   // The live segment is ending inside EndMBB
1484   const MachineInstr *MI =
1485     LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
1486   if (!MI) {
1487     report("Live segment doesn't end at a valid instruction", EndMBB, LR);
1488     *OS << S << '\n';
1489     return;
1490   }
1491
1492   // The block slot must refer to a basic block boundary.
1493   if (S.end.isBlock()) {
1494     report("Live segment ends at B slot of an instruction", EndMBB, LR);
1495     *OS << S << '\n';
1496   }
1497
1498   if (S.end.isDead()) {
1499     // Segment ends on the dead slot.
1500     // That means there must be a dead def.
1501     if (!SlotIndex::isSameInstr(S.start, S.end)) {
1502       report("Live segment ending at dead slot spans instructions", EndMBB, LR);
1503       *OS << S << '\n';
1504     }
1505   }
1506
1507   // A live segment can only end at an early-clobber slot if it is being
1508   // redefined by an early-clobber def.
1509   if (S.end.isEarlyClobber()) {
1510     if (I+1 == LR.end() || (I+1)->start != S.end) {
1511       report("Live segment ending at early clobber slot must be "
1512              "redefined by an EC def in the same instruction", EndMBB, LR);
1513       *OS << S << '\n';
1514     }
1515   }
1516
1517   // The following checks only apply to virtual registers. Physreg liveness
1518   // is too weird to check.
1519   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1520     // A live segment can end with either a redefinition, a kill flag on a
1521     // use, or a dead flag on a def.
1522     bool hasRead = false;
1523     for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1524       if (!MOI->isReg() || MOI->getReg() != Reg)
1525         continue;
1526       if (MOI->readsReg())
1527         hasRead = true;
1528     }
1529     if (!S.end.isDead()) {
1530       if (!hasRead) {
1531         report("Instruction ending live segment doesn't read the register", MI);
1532         *OS << S << " in " << LR << '\n';
1533       }
1534     }
1535   }
1536
1537   // Now check all the basic blocks in this live segment.
1538   MachineFunction::const_iterator MFI = MBB;
1539   // Is this live segment the beginning of a non-PHIDef VN?
1540   if (S.start == VNI->def && !VNI->isPHIDef()) {
1541     // Not live-in to any blocks.
1542     if (MBB == EndMBB)
1543       return;
1544     // Skip this block.
1545     ++MFI;
1546   }
1547   for (;;) {
1548     assert(LiveInts->isLiveInToMBB(LR, MFI));
1549     // We don't know how to track physregs into a landing pad.
1550     if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
1551         MFI->isLandingPad()) {
1552       if (&*MFI == EndMBB)
1553         break;
1554       ++MFI;
1555       continue;
1556     }
1557
1558     // Is VNI a PHI-def in the current block?
1559     bool IsPHI = VNI->isPHIDef() &&
1560       VNI->def == LiveInts->getMBBStartIdx(MFI);
1561
1562     // Check that VNI is live-out of all predecessors.
1563     for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1564          PE = MFI->pred_end(); PI != PE; ++PI) {
1565       SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1566       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
1567
1568       // All predecessors must have a live-out value.
1569       if (!PVNI) {
1570         report("Register not marked live out of predecessor", *PI, LR);
1571         *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1572             << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1573             << PEnd << '\n';
1574         continue;
1575       }
1576
1577       // Only PHI-defs can take different predecessor values.
1578       if (!IsPHI && PVNI != VNI) {
1579         report("Different value live out of predecessor", *PI, LR);
1580         *OS << "Valno #" << PVNI->id << " live out of BB#"
1581             << (*PI)->getNumber() << '@' << PEnd
1582             << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1583             << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
1584       }
1585     }
1586     if (&*MFI == EndMBB)
1587       break;
1588     ++MFI;
1589   }
1590 }
1591
1592 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg) {
1593   for (LiveRange::const_vni_iterator I = LR.vni_begin(), E = LR.vni_end();
1594        I != E; ++I)
1595     verifyLiveRangeValue(LR, *I, Reg);
1596
1597   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
1598     verifyLiveRangeSegment(LR, I, Reg);
1599 }
1600
1601 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
1602   verifyLiveRange(LI, LI.reg);
1603
1604   // Check the LI only has one connected component.
1605   if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1606     ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1607     unsigned NumComp = ConEQ.Classify(&LI);
1608     if (NumComp > 1) {
1609       report("Multiple connected components in live interval", MF, LI);
1610       for (unsigned comp = 0; comp != NumComp; ++comp) {
1611         *OS << comp << ": valnos";
1612         for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1613              E = LI.vni_end(); I!=E; ++I)
1614           if (comp == ConEQ.getEqClass(*I))
1615             *OS << ' ' << (*I)->id;
1616         *OS << '\n';
1617       }
1618     }
1619   }
1620 }
1621
1622 namespace {
1623   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
1624   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
1625   // value is zero.
1626   // We use a bool plus an integer to capture the stack state.
1627   struct StackStateOfBB {
1628     StackStateOfBB() : EntryValue(0), ExitValue(0), EntryIsSetup(false),
1629       ExitIsSetup(false) { }
1630     StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
1631       EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
1632       ExitIsSetup(ExitSetup) { }
1633     // Can be negative, which means we are setting up a frame.
1634     int EntryValue;
1635     int ExitValue;
1636     bool EntryIsSetup;
1637     bool ExitIsSetup;
1638   };
1639 }
1640
1641 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
1642 /// by a FrameDestroy <n>, stack adjustments are identical on all
1643 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
1644 void MachineVerifier::verifyStackFrame() {
1645   int FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
1646   int FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
1647
1648   SmallVector<StackStateOfBB, 8> SPState;
1649   SPState.resize(MF->getNumBlockIDs());
1650   SmallPtrSet<const MachineBasicBlock*, 8> Reachable;
1651
1652   // Visit the MBBs in DFS order.
1653   for (df_ext_iterator<const MachineFunction*,
1654                        SmallPtrSet<const MachineBasicBlock*, 8> >
1655        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
1656        DFI != DFE; ++DFI) {
1657     const MachineBasicBlock *MBB = *DFI;
1658
1659     StackStateOfBB BBState;
1660     // Check the exit state of the DFS stack predecessor.
1661     if (DFI.getPathLength() >= 2) {
1662       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1663       assert(Reachable.count(StackPred) &&
1664              "DFS stack predecessor is already visited.\n");
1665       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
1666       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
1667       BBState.ExitValue = BBState.EntryValue;
1668       BBState.ExitIsSetup = BBState.EntryIsSetup;
1669     }
1670
1671     // Update stack state by checking contents of MBB.
1672     for (const auto &I : *MBB) {
1673       if (I.getOpcode() == FrameSetupOpcode) {
1674         // The first operand of a FrameOpcode should be i32.
1675         int Size = I.getOperand(0).getImm();
1676         assert(Size >= 0 &&
1677           "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1678
1679         if (BBState.ExitIsSetup)
1680           report("FrameSetup is after another FrameSetup", &I);
1681         BBState.ExitValue -= Size;
1682         BBState.ExitIsSetup = true;
1683       }
1684
1685       if (I.getOpcode() == FrameDestroyOpcode) {
1686         // The first operand of a FrameOpcode should be i32.
1687         int Size = I.getOperand(0).getImm();
1688         assert(Size >= 0 &&
1689           "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1690
1691         if (!BBState.ExitIsSetup)
1692           report("FrameDestroy is not after a FrameSetup", &I);
1693         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
1694                                                BBState.ExitValue;
1695         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
1696           report("FrameDestroy <n> is after FrameSetup <m>", &I);
1697           *OS << "FrameDestroy <" << Size << "> is after FrameSetup <"
1698               << AbsSPAdj << ">.\n";
1699         }
1700         BBState.ExitValue += Size;
1701         BBState.ExitIsSetup = false;
1702       }
1703     }
1704     SPState[MBB->getNumber()] = BBState;
1705
1706     // Make sure the exit state of any predecessor is consistent with the entry
1707     // state.
1708     for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
1709          E = MBB->pred_end(); I != E; ++I) {
1710       if (Reachable.count(*I) &&
1711           (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
1712            SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
1713         report("The exit stack state of a predecessor is inconsistent.", MBB);
1714         *OS << "Predecessor BB#" << (*I)->getNumber() << " has exit state ("
1715             << SPState[(*I)->getNumber()].ExitValue << ", "
1716             << SPState[(*I)->getNumber()].ExitIsSetup
1717             << "), while BB#" << MBB->getNumber() << " has entry state ("
1718             << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
1719       }
1720     }
1721
1722     // Make sure the entry state of any successor is consistent with the exit
1723     // state.
1724     for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
1725          E = MBB->succ_end(); I != E; ++I) {
1726       if (Reachable.count(*I) &&
1727           (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
1728            SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
1729         report("The entry stack state of a successor is inconsistent.", MBB);
1730         *OS << "Successor BB#" << (*I)->getNumber() << " has entry state ("
1731             << SPState[(*I)->getNumber()].EntryValue << ", "
1732             << SPState[(*I)->getNumber()].EntryIsSetup
1733             << "), while BB#" << MBB->getNumber() << " has exit state ("
1734             << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
1735       }
1736     }
1737
1738     // Make sure a basic block with return ends with zero stack adjustment.
1739     if (!MBB->empty() && MBB->back().isReturn()) {
1740       if (BBState.ExitIsSetup)
1741         report("A return block ends with a FrameSetup.", MBB);
1742       if (BBState.ExitValue)
1743         report("A return block ends with a nonzero stack adjustment.", MBB);
1744     }
1745   }
1746 }