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