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