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 "LiveRangeCalc.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SetOperations.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/Analysis/EHPersonalities.h"
38 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
39 #include "llvm/CodeGen/LiveInterval.h"
40 #include "llvm/CodeGen/LiveIntervals.h"
41 #include "llvm/CodeGen/LiveStacks.h"
42 #include "llvm/CodeGen/LiveVariables.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineFunctionPass.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBundle.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/PseudoSourceValue.h"
53 #include "llvm/CodeGen/SlotIndexes.h"
54 #include "llvm/CodeGen/StackMaps.h"
55 #include "llvm/CodeGen/TargetInstrInfo.h"
56 #include "llvm/CodeGen/TargetOpcodes.h"
57 #include "llvm/CodeGen/TargetRegisterInfo.h"
58 #include "llvm/CodeGen/TargetSubtargetInfo.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/InlineAsm.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/MC/LaneBitmask.h"
64 #include "llvm/MC/MCAsmInfo.h"
65 #include "llvm/MC/MCInstrDesc.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/MC/MCTargetOptions.h"
68 #include "llvm/Pass.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/LowLevelTypeImpl.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Target/TargetMachine.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdint>
79 #include <iterator>
80 #include <string>
81 #include <utility>
82 
83 using namespace llvm;
84 
85 namespace {
86 
87   struct MachineVerifier {
88     MachineVerifier(Pass *pass, const char *b) : PASS(pass), Banner(b) {}
89 
90     unsigned verify(MachineFunction &MF);
91 
92     Pass *const PASS;
93     const char *Banner;
94     const MachineFunction *MF;
95     const TargetMachine *TM;
96     const TargetInstrInfo *TII;
97     const TargetRegisterInfo *TRI;
98     const MachineRegisterInfo *MRI;
99 
100     unsigned foundErrors;
101 
102     // Avoid querying the MachineFunctionProperties for each operand.
103     bool isFunctionRegBankSelected;
104     bool isFunctionSelected;
105 
106     using RegVector = SmallVector<unsigned, 16>;
107     using RegMaskVector = SmallVector<const uint32_t *, 4>;
108     using RegSet = DenseSet<unsigned>;
109     using RegMap = DenseMap<unsigned, const MachineInstr *>;
110     using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>;
111 
112     const MachineInstr *FirstTerminator;
113     BlockSet FunctionBlocks;
114 
115     BitVector regsReserved;
116     RegSet regsLive;
117     RegVector regsDefined, regsDead, regsKilled;
118     RegMaskVector regMasks;
119 
120     SlotIndex lastIndex;
121 
122     // Add Reg and any sub-registers to RV
123     void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
124       RV.push_back(Reg);
125       if (TargetRegisterInfo::isPhysicalRegister(Reg))
126         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
127           RV.push_back(*SubRegs);
128     }
129 
130     struct BBInfo {
131       // Is this MBB reachable from the MF entry point?
132       bool reachable = false;
133 
134       // Vregs that must be live in because they are used without being
135       // defined. Map value is the user.
136       RegMap vregsLiveIn;
137 
138       // Regs killed in MBB. They may be defined again, and will then be in both
139       // regsKilled and regsLiveOut.
140       RegSet regsKilled;
141 
142       // Regs defined in MBB and live out. Note that vregs passing through may
143       // be live out without being mentioned here.
144       RegSet regsLiveOut;
145 
146       // Vregs that pass through MBB untouched. This set is disjoint from
147       // regsKilled and regsLiveOut.
148       RegSet vregsPassed;
149 
150       // Vregs that must pass through MBB because they are needed by a successor
151       // block. This set is disjoint from regsLiveOut.
152       RegSet vregsRequired;
153 
154       // Set versions of block's predecessor and successor lists.
155       BlockSet Preds, Succs;
156 
157       BBInfo() = default;
158 
159       // Add register to vregsPassed if it belongs there. Return true if
160       // anything changed.
161       bool addPassed(unsigned Reg) {
162         if (!TargetRegisterInfo::isVirtualRegister(Reg))
163           return false;
164         if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
165           return false;
166         return vregsPassed.insert(Reg).second;
167       }
168 
169       // Same for a full set.
170       bool addPassed(const RegSet &RS) {
171         bool changed = false;
172         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
173           if (addPassed(*I))
174             changed = true;
175         return changed;
176       }
177 
178       // Add register to vregsRequired if it belongs there. Return true if
179       // anything changed.
180       bool addRequired(unsigned Reg) {
181         if (!TargetRegisterInfo::isVirtualRegister(Reg))
182           return false;
183         if (regsLiveOut.count(Reg))
184           return false;
185         return vregsRequired.insert(Reg).second;
186       }
187 
188       // Same for a full set.
189       bool addRequired(const RegSet &RS) {
190         bool changed = false;
191         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
192           if (addRequired(*I))
193             changed = true;
194         return changed;
195       }
196 
197       // Same for a full map.
198       bool addRequired(const RegMap &RM) {
199         bool changed = false;
200         for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
201           if (addRequired(I->first))
202             changed = true;
203         return changed;
204       }
205 
206       // Live-out registers are either in regsLiveOut or vregsPassed.
207       bool isLiveOut(unsigned Reg) const {
208         return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
209       }
210     };
211 
212     // Extra register info per MBB.
213     DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
214 
215     bool isReserved(unsigned Reg) {
216       return Reg < regsReserved.size() && regsReserved.test(Reg);
217     }
218 
219     bool isAllocatable(unsigned Reg) const {
220       return Reg < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
221         !regsReserved.test(Reg);
222     }
223 
224     // Analysis information if available
225     LiveVariables *LiveVars;
226     LiveIntervals *LiveInts;
227     LiveStacks *LiveStks;
228     SlotIndexes *Indexes;
229 
230     void visitMachineFunctionBefore();
231     void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
232     void visitMachineBundleBefore(const MachineInstr *MI);
233     void visitMachineInstrBefore(const MachineInstr *MI);
234     void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
235     void visitMachineInstrAfter(const MachineInstr *MI);
236     void visitMachineBundleAfter(const MachineInstr *MI);
237     void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
238     void visitMachineFunctionAfter();
239 
240     void report(const char *msg, const MachineFunction *MF);
241     void report(const char *msg, const MachineBasicBlock *MBB);
242     void report(const char *msg, const MachineInstr *MI);
243     void report(const char *msg, const MachineOperand *MO, unsigned MONum,
244                 LLT MOVRegType = LLT{});
245 
246     void report_context(const LiveInterval &LI) const;
247     void report_context(const LiveRange &LR, unsigned VRegUnit,
248                         LaneBitmask LaneMask) const;
249     void report_context(const LiveRange::Segment &S) const;
250     void report_context(const VNInfo &VNI) const;
251     void report_context(SlotIndex Pos) const;
252     void report_context_liverange(const LiveRange &LR) const;
253     void report_context_lanemask(LaneBitmask LaneMask) const;
254     void report_context_vreg(unsigned VReg) const;
255     void report_context_vreg_regunit(unsigned VRegOrUnit) const;
256 
257     void verifyInlineAsm(const MachineInstr *MI);
258 
259     void checkLiveness(const MachineOperand *MO, unsigned MONum);
260     void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
261                             SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
262                             LaneBitmask LaneMask = LaneBitmask::getNone());
263     void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
264                             SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
265                             LaneBitmask LaneMask = LaneBitmask::getNone());
266 
267     void markReachable(const MachineBasicBlock *MBB);
268     void calcRegsPassed();
269     void checkPHIOps(const MachineBasicBlock &MBB);
270 
271     void calcRegsRequired();
272     void verifyLiveVariables();
273     void verifyLiveIntervals();
274     void verifyLiveInterval(const LiveInterval&);
275     void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned,
276                               LaneBitmask);
277     void verifyLiveRangeSegment(const LiveRange&,
278                                 const LiveRange::const_iterator I, unsigned,
279                                 LaneBitmask);
280     void verifyLiveRange(const LiveRange&, unsigned,
281                          LaneBitmask LaneMask = LaneBitmask::getNone());
282 
283     void verifyStackFrame();
284 
285     void verifySlotIndexes() const;
286     void verifyProperties(const MachineFunction &MF);
287   };
288 
289   struct MachineVerifierPass : public MachineFunctionPass {
290     static char ID; // Pass ID, replacement for typeid
291 
292     const std::string Banner;
293 
294     MachineVerifierPass(std::string banner = std::string())
295       : MachineFunctionPass(ID), Banner(std::move(banner)) {
296         initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
297       }
298 
299     void getAnalysisUsage(AnalysisUsage &AU) const override {
300       AU.setPreservesAll();
301       MachineFunctionPass::getAnalysisUsage(AU);
302     }
303 
304     bool runOnMachineFunction(MachineFunction &MF) override {
305       unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF);
306       if (FoundErrors)
307         report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
308       return false;
309     }
310   };
311 
312 } // end anonymous namespace
313 
314 char MachineVerifierPass::ID = 0;
315 
316 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
317                 "Verify generated machine code", false, false)
318 
319 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
320   return new MachineVerifierPass(Banner);
321 }
322 
323 bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors)
324     const {
325   MachineFunction &MF = const_cast<MachineFunction&>(*this);
326   unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF);
327   if (AbortOnErrors && FoundErrors)
328     report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
329   return FoundErrors == 0;
330 }
331 
332 void MachineVerifier::verifySlotIndexes() const {
333   if (Indexes == nullptr)
334     return;
335 
336   // Ensure the IdxMBB list is sorted by slot indexes.
337   SlotIndex Last;
338   for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
339        E = Indexes->MBBIndexEnd(); I != E; ++I) {
340     assert(!Last.isValid() || I->first > Last);
341     Last = I->first;
342   }
343 }
344 
345 void MachineVerifier::verifyProperties(const MachineFunction &MF) {
346   // If a pass has introduced virtual registers without clearing the
347   // NoVRegs property (or set it without allocating the vregs)
348   // then report an error.
349   if (MF.getProperties().hasProperty(
350           MachineFunctionProperties::Property::NoVRegs) &&
351       MRI->getNumVirtRegs())
352     report("Function has NoVRegs property but there are VReg operands", &MF);
353 }
354 
355 unsigned MachineVerifier::verify(MachineFunction &MF) {
356   foundErrors = 0;
357 
358   this->MF = &MF;
359   TM = &MF.getTarget();
360   TII = MF.getSubtarget().getInstrInfo();
361   TRI = MF.getSubtarget().getRegisterInfo();
362   MRI = &MF.getRegInfo();
363 
364   const bool isFunctionFailedISel = MF.getProperties().hasProperty(
365       MachineFunctionProperties::Property::FailedISel);
366   isFunctionRegBankSelected =
367       !isFunctionFailedISel &&
368       MF.getProperties().hasProperty(
369           MachineFunctionProperties::Property::RegBankSelected);
370   isFunctionSelected = !isFunctionFailedISel &&
371                        MF.getProperties().hasProperty(
372                            MachineFunctionProperties::Property::Selected);
373   LiveVars = nullptr;
374   LiveInts = nullptr;
375   LiveStks = nullptr;
376   Indexes = nullptr;
377   if (PASS) {
378     LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
379     // We don't want to verify LiveVariables if LiveIntervals is available.
380     if (!LiveInts)
381       LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
382     LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
383     Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
384   }
385 
386   verifySlotIndexes();
387 
388   verifyProperties(MF);
389 
390   visitMachineFunctionBefore();
391   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
392        MFI!=MFE; ++MFI) {
393     visitMachineBasicBlockBefore(&*MFI);
394     // Keep track of the current bundle header.
395     const MachineInstr *CurBundle = nullptr;
396     // Do we expect the next instruction to be part of the same bundle?
397     bool InBundle = false;
398 
399     for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
400            MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
401       if (MBBI->getParent() != &*MFI) {
402         report("Bad instruction parent pointer", &*MFI);
403         errs() << "Instruction: " << *MBBI;
404         continue;
405       }
406 
407       // Check for consistent bundle flags.
408       if (InBundle && !MBBI->isBundledWithPred())
409         report("Missing BundledPred flag, "
410                "BundledSucc was set on predecessor",
411                &*MBBI);
412       if (!InBundle && MBBI->isBundledWithPred())
413         report("BundledPred flag is set, "
414                "but BundledSucc not set on predecessor",
415                &*MBBI);
416 
417       // Is this a bundle header?
418       if (!MBBI->isInsideBundle()) {
419         if (CurBundle)
420           visitMachineBundleAfter(CurBundle);
421         CurBundle = &*MBBI;
422         visitMachineBundleBefore(CurBundle);
423       } else if (!CurBundle)
424         report("No bundle header", &*MBBI);
425       visitMachineInstrBefore(&*MBBI);
426       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
427         const MachineInstr &MI = *MBBI;
428         const MachineOperand &Op = MI.getOperand(I);
429         if (Op.getParent() != &MI) {
430           // Make sure to use correct addOperand / RemoveOperand / ChangeTo
431           // functions when replacing operands of a MachineInstr.
432           report("Instruction has operand with wrong parent set", &MI);
433         }
434 
435         visitMachineOperand(&Op, I);
436       }
437 
438       visitMachineInstrAfter(&*MBBI);
439 
440       // Was this the last bundled instruction?
441       InBundle = MBBI->isBundledWithSucc();
442     }
443     if (CurBundle)
444       visitMachineBundleAfter(CurBundle);
445     if (InBundle)
446       report("BundledSucc flag set on last instruction in block", &MFI->back());
447     visitMachineBasicBlockAfter(&*MFI);
448   }
449   visitMachineFunctionAfter();
450 
451   // Clean up.
452   regsLive.clear();
453   regsDefined.clear();
454   regsDead.clear();
455   regsKilled.clear();
456   regMasks.clear();
457   MBBInfoMap.clear();
458 
459   return foundErrors;
460 }
461 
462 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
463   assert(MF);
464   errs() << '\n';
465   if (!foundErrors++) {
466     if (Banner)
467       errs() << "# " << Banner << '\n';
468     if (LiveInts != nullptr)
469       LiveInts->print(errs());
470     else
471       MF->print(errs(), Indexes);
472   }
473   errs() << "*** Bad machine code: " << msg << " ***\n"
474       << "- function:    " << MF->getName() << "\n";
475 }
476 
477 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
478   assert(MBB);
479   report(msg, MBB->getParent());
480   errs() << "- basic block: " << printMBBReference(*MBB) << ' '
481          << MBB->getName() << " (" << (const void *)MBB << ')';
482   if (Indexes)
483     errs() << " [" << Indexes->getMBBStartIdx(MBB)
484         << ';' <<  Indexes->getMBBEndIdx(MBB) << ')';
485   errs() << '\n';
486 }
487 
488 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
489   assert(MI);
490   report(msg, MI->getParent());
491   errs() << "- instruction: ";
492   if (Indexes && Indexes->hasIndex(*MI))
493     errs() << Indexes->getInstructionIndex(*MI) << '\t';
494   MI->print(errs(), /*SkipOpers=*/true);
495 }
496 
497 void MachineVerifier::report(const char *msg, const MachineOperand *MO,
498                              unsigned MONum, LLT MOVRegType) {
499   assert(MO);
500   report(msg, MO->getParent());
501   errs() << "- operand " << MONum << ":   ";
502   MO->print(errs(), MOVRegType, TRI);
503   errs() << "\n";
504 }
505 
506 void MachineVerifier::report_context(SlotIndex Pos) const {
507   errs() << "- at:          " << Pos << '\n';
508 }
509 
510 void MachineVerifier::report_context(const LiveInterval &LI) const {
511   errs() << "- interval:    " << LI << '\n';
512 }
513 
514 void MachineVerifier::report_context(const LiveRange &LR, unsigned VRegUnit,
515                                      LaneBitmask LaneMask) const {
516   report_context_liverange(LR);
517   report_context_vreg_regunit(VRegUnit);
518   if (LaneMask.any())
519     report_context_lanemask(LaneMask);
520 }
521 
522 void MachineVerifier::report_context(const LiveRange::Segment &S) const {
523   errs() << "- segment:     " << S << '\n';
524 }
525 
526 void MachineVerifier::report_context(const VNInfo &VNI) const {
527   errs() << "- ValNo:       " << VNI.id << " (def " << VNI.def << ")\n";
528 }
529 
530 void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
531   errs() << "- liverange:   " << LR << '\n';
532 }
533 
534 void MachineVerifier::report_context_vreg(unsigned VReg) const {
535   errs() << "- v. register: " << printReg(VReg, TRI) << '\n';
536 }
537 
538 void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit) const {
539   if (TargetRegisterInfo::isVirtualRegister(VRegOrUnit)) {
540     report_context_vreg(VRegOrUnit);
541   } else {
542     errs() << "- regunit:     " << printRegUnit(VRegOrUnit, TRI) << '\n';
543   }
544 }
545 
546 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
547   errs() << "- lanemask:    " << PrintLaneMask(LaneMask) << '\n';
548 }
549 
550 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
551   BBInfo &MInfo = MBBInfoMap[MBB];
552   if (!MInfo.reachable) {
553     MInfo.reachable = true;
554     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
555            SuE = MBB->succ_end(); SuI != SuE; ++SuI)
556       markReachable(*SuI);
557   }
558 }
559 
560 void MachineVerifier::visitMachineFunctionBefore() {
561   lastIndex = SlotIndex();
562   regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
563                                            : TRI->getReservedRegs(*MF);
564 
565   if (!MF->empty())
566     markReachable(&MF->front());
567 
568   // Build a set of the basic blocks in the function.
569   FunctionBlocks.clear();
570   for (const auto &MBB : *MF) {
571     FunctionBlocks.insert(&MBB);
572     BBInfo &MInfo = MBBInfoMap[&MBB];
573 
574     MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
575     if (MInfo.Preds.size() != MBB.pred_size())
576       report("MBB has duplicate entries in its predecessor list.", &MBB);
577 
578     MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
579     if (MInfo.Succs.size() != MBB.succ_size())
580       report("MBB has duplicate entries in its successor list.", &MBB);
581   }
582 
583   // Check that the register use lists are sane.
584   MRI->verifyUseLists();
585 
586   if (!MF->empty())
587     verifyStackFrame();
588 }
589 
590 // Does iterator point to a and b as the first two elements?
591 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
592                       const MachineBasicBlock *a, const MachineBasicBlock *b) {
593   if (*i == a)
594     return *++i == b;
595   if (*i == b)
596     return *++i == a;
597   return false;
598 }
599 
600 void
601 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
602   FirstTerminator = nullptr;
603 
604   if (!MF->getProperties().hasProperty(
605       MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) {
606     // If this block has allocatable physical registers live-in, check that
607     // it is an entry block or landing pad.
608     for (const auto &LI : MBB->liveins()) {
609       if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
610           MBB->getIterator() != MBB->getParent()->begin()) {
611         report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB);
612       }
613     }
614   }
615 
616   // Count the number of landing pad successors.
617   SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
618   for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
619        E = MBB->succ_end(); I != E; ++I) {
620     if ((*I)->isEHPad())
621       LandingPadSuccs.insert(*I);
622     if (!FunctionBlocks.count(*I))
623       report("MBB has successor that isn't part of the function.", MBB);
624     if (!MBBInfoMap[*I].Preds.count(MBB)) {
625       report("Inconsistent CFG", MBB);
626       errs() << "MBB is not in the predecessor list of the successor "
627              << printMBBReference(*(*I)) << ".\n";
628     }
629   }
630 
631   // Check the predecessor list.
632   for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
633        E = MBB->pred_end(); I != E; ++I) {
634     if (!FunctionBlocks.count(*I))
635       report("MBB has predecessor that isn't part of the function.", MBB);
636     if (!MBBInfoMap[*I].Succs.count(MBB)) {
637       report("Inconsistent CFG", MBB);
638       errs() << "MBB is not in the successor list of the predecessor "
639              << printMBBReference(*(*I)) << ".\n";
640     }
641   }
642 
643   const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
644   const BasicBlock *BB = MBB->getBasicBlock();
645   const Function &F = MF->getFunction();
646   if (LandingPadSuccs.size() > 1 &&
647       !(AsmInfo &&
648         AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
649         BB && isa<SwitchInst>(BB->getTerminator())) &&
650       !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
651     report("MBB has more than one landing pad successor", MBB);
652 
653   // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
654   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
655   SmallVector<MachineOperand, 4> Cond;
656   if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB,
657                           Cond)) {
658     // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
659     // check whether its answers match up with reality.
660     if (!TBB && !FBB) {
661       // Block falls through to its successor.
662       MachineFunction::const_iterator MBBI = MBB->getIterator();
663       ++MBBI;
664       if (MBBI == MF->end()) {
665         // It's possible that the block legitimately ends with a noreturn
666         // call or an unreachable, in which case it won't actually fall
667         // out the bottom of the function.
668       } else if (MBB->succ_size() == LandingPadSuccs.size()) {
669         // It's possible that the block legitimately ends with a noreturn
670         // call or an unreachable, in which case it won't actuall fall
671         // out of the block.
672       } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
673         report("MBB exits via unconditional fall-through but doesn't have "
674                "exactly one CFG successor!", MBB);
675       } else if (!MBB->isSuccessor(&*MBBI)) {
676         report("MBB exits via unconditional fall-through but its successor "
677                "differs from its CFG successor!", MBB);
678       }
679       if (!MBB->empty() && MBB->back().isBarrier() &&
680           !TII->isPredicated(MBB->back())) {
681         report("MBB exits via unconditional fall-through but ends with a "
682                "barrier instruction!", MBB);
683       }
684       if (!Cond.empty()) {
685         report("MBB exits via unconditional fall-through but has a condition!",
686                MBB);
687       }
688     } else if (TBB && !FBB && Cond.empty()) {
689       // Block unconditionally branches somewhere.
690       // If the block has exactly one successor, that happens to be a
691       // landingpad, accept it as valid control flow.
692       if (MBB->succ_size() != 1+LandingPadSuccs.size() &&
693           (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 ||
694            *MBB->succ_begin() != *LandingPadSuccs.begin())) {
695         report("MBB exits via unconditional branch but doesn't have "
696                "exactly one CFG successor!", MBB);
697       } else if (!MBB->isSuccessor(TBB)) {
698         report("MBB exits via unconditional branch but the CFG "
699                "successor doesn't match the actual successor!", MBB);
700       }
701       if (MBB->empty()) {
702         report("MBB exits via unconditional branch but doesn't contain "
703                "any instructions!", MBB);
704       } else if (!MBB->back().isBarrier()) {
705         report("MBB exits via unconditional branch but doesn't end with a "
706                "barrier instruction!", MBB);
707       } else if (!MBB->back().isTerminator()) {
708         report("MBB exits via unconditional branch but the branch isn't a "
709                "terminator instruction!", MBB);
710       }
711     } else if (TBB && !FBB && !Cond.empty()) {
712       // Block conditionally branches somewhere, otherwise falls through.
713       MachineFunction::const_iterator MBBI = MBB->getIterator();
714       ++MBBI;
715       if (MBBI == MF->end()) {
716         report("MBB conditionally falls through out of function!", MBB);
717       } else if (MBB->succ_size() == 1) {
718         // A conditional branch with only one successor is weird, but allowed.
719         if (&*MBBI != TBB)
720           report("MBB exits via conditional branch/fall-through but only has "
721                  "one CFG successor!", MBB);
722         else if (TBB != *MBB->succ_begin())
723           report("MBB exits via conditional branch/fall-through but the CFG "
724                  "successor don't match the actual successor!", MBB);
725       } else if (MBB->succ_size() != 2) {
726         report("MBB exits via conditional branch/fall-through but doesn't have "
727                "exactly two CFG successors!", MBB);
728       } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
729         report("MBB exits via conditional branch/fall-through but the CFG "
730                "successors don't match the actual successors!", MBB);
731       }
732       if (MBB->empty()) {
733         report("MBB exits via conditional branch/fall-through but doesn't "
734                "contain any instructions!", MBB);
735       } else if (MBB->back().isBarrier()) {
736         report("MBB exits via conditional branch/fall-through but ends with a "
737                "barrier instruction!", MBB);
738       } else if (!MBB->back().isTerminator()) {
739         report("MBB exits via conditional branch/fall-through but the branch "
740                "isn't a terminator instruction!", MBB);
741       }
742     } else if (TBB && FBB) {
743       // Block conditionally branches somewhere, otherwise branches
744       // somewhere else.
745       if (MBB->succ_size() == 1) {
746         // A conditional branch with only one successor is weird, but allowed.
747         if (FBB != TBB)
748           report("MBB exits via conditional branch/branch through but only has "
749                  "one CFG successor!", MBB);
750         else if (TBB != *MBB->succ_begin())
751           report("MBB exits via conditional branch/branch through but the CFG "
752                  "successor don't match the actual successor!", MBB);
753       } else if (MBB->succ_size() != 2) {
754         report("MBB exits via conditional branch/branch but doesn't have "
755                "exactly two CFG successors!", MBB);
756       } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
757         report("MBB exits via conditional branch/branch but the CFG "
758                "successors don't match the actual successors!", MBB);
759       }
760       if (MBB->empty()) {
761         report("MBB exits via conditional branch/branch but doesn't "
762                "contain any instructions!", MBB);
763       } else if (!MBB->back().isBarrier()) {
764         report("MBB exits via conditional branch/branch but doesn't end with a "
765                "barrier instruction!", MBB);
766       } else if (!MBB->back().isTerminator()) {
767         report("MBB exits via conditional branch/branch but the branch "
768                "isn't a terminator instruction!", MBB);
769       }
770       if (Cond.empty()) {
771         report("MBB exits via conditinal branch/branch but there's no "
772                "condition!", MBB);
773       }
774     } else {
775       report("AnalyzeBranch returned invalid data!", MBB);
776     }
777   }
778 
779   regsLive.clear();
780   if (MRI->tracksLiveness()) {
781     for (const auto &LI : MBB->liveins()) {
782       if (!TargetRegisterInfo::isPhysicalRegister(LI.PhysReg)) {
783         report("MBB live-in list contains non-physical register", MBB);
784         continue;
785       }
786       for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
787            SubRegs.isValid(); ++SubRegs)
788         regsLive.insert(*SubRegs);
789     }
790   }
791 
792   const MachineFrameInfo &MFI = MF->getFrameInfo();
793   BitVector PR = MFI.getPristineRegs(*MF);
794   for (unsigned I : PR.set_bits()) {
795     for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
796          SubRegs.isValid(); ++SubRegs)
797       regsLive.insert(*SubRegs);
798   }
799 
800   regsKilled.clear();
801   regsDefined.clear();
802 
803   if (Indexes)
804     lastIndex = Indexes->getMBBStartIdx(MBB);
805 }
806 
807 // This function gets called for all bundle headers, including normal
808 // stand-alone unbundled instructions.
809 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
810   if (Indexes && Indexes->hasIndex(*MI)) {
811     SlotIndex idx = Indexes->getInstructionIndex(*MI);
812     if (!(idx > lastIndex)) {
813       report("Instruction index out of order", MI);
814       errs() << "Last instruction was at " << lastIndex << '\n';
815     }
816     lastIndex = idx;
817   }
818 
819   // Ensure non-terminators don't follow terminators.
820   // Ignore predicated terminators formed by if conversion.
821   // FIXME: If conversion shouldn't need to violate this rule.
822   if (MI->isTerminator() && !TII->isPredicated(*MI)) {
823     if (!FirstTerminator)
824       FirstTerminator = MI;
825   } else if (FirstTerminator) {
826     report("Non-terminator instruction after the first terminator", MI);
827     errs() << "First terminator was:\t" << *FirstTerminator;
828   }
829 }
830 
831 // The operands on an INLINEASM instruction must follow a template.
832 // Verify that the flag operands make sense.
833 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
834   // The first two operands on INLINEASM are the asm string and global flags.
835   if (MI->getNumOperands() < 2) {
836     report("Too few operands on inline asm", MI);
837     return;
838   }
839   if (!MI->getOperand(0).isSymbol())
840     report("Asm string must be an external symbol", MI);
841   if (!MI->getOperand(1).isImm())
842     report("Asm flags must be an immediate", MI);
843   // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
844   // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
845   // and Extra_IsConvergent = 32.
846   if (!isUInt<6>(MI->getOperand(1).getImm()))
847     report("Unknown asm flags", &MI->getOperand(1), 1);
848 
849   static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
850 
851   unsigned OpNo = InlineAsm::MIOp_FirstOperand;
852   unsigned NumOps;
853   for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
854     const MachineOperand &MO = MI->getOperand(OpNo);
855     // There may be implicit ops after the fixed operands.
856     if (!MO.isImm())
857       break;
858     NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
859   }
860 
861   if (OpNo > MI->getNumOperands())
862     report("Missing operands in last group", MI);
863 
864   // An optional MDNode follows the groups.
865   if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
866     ++OpNo;
867 
868   // All trailing operands must be implicit registers.
869   for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
870     const MachineOperand &MO = MI->getOperand(OpNo);
871     if (!MO.isReg() || !MO.isImplicit())
872       report("Expected implicit register after groups", &MO, OpNo);
873   }
874 }
875 
876 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
877   const MCInstrDesc &MCID = MI->getDesc();
878   if (MI->getNumOperands() < MCID.getNumOperands()) {
879     report("Too few operands", MI);
880     errs() << MCID.getNumOperands() << " operands expected, but "
881            << MI->getNumOperands() << " given.\n";
882   }
883 
884   if (MI->isPHI() && MF->getProperties().hasProperty(
885                          MachineFunctionProperties::Property::NoPHIs))
886     report("Found PHI instruction with NoPHIs property set", MI);
887 
888   // Check the tied operands.
889   if (MI->isInlineAsm())
890     verifyInlineAsm(MI);
891 
892   // Check the MachineMemOperands for basic consistency.
893   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
894                                   E = MI->memoperands_end();
895        I != E; ++I) {
896     if ((*I)->isLoad() && !MI->mayLoad())
897       report("Missing mayLoad flag", MI);
898     if ((*I)->isStore() && !MI->mayStore())
899       report("Missing mayStore flag", MI);
900   }
901 
902   // Debug values must not have a slot index.
903   // Other instructions must have one, unless they are inside a bundle.
904   if (LiveInts) {
905     bool mapped = !LiveInts->isNotInMIMap(*MI);
906     if (MI->isDebugInstr()) {
907       if (mapped)
908         report("Debug instruction has a slot index", MI);
909     } else if (MI->isInsideBundle()) {
910       if (mapped)
911         report("Instruction inside bundle has a slot index", MI);
912     } else {
913       if (!mapped)
914         report("Missing slot index", MI);
915     }
916   }
917 
918   if (isPreISelGenericOpcode(MCID.getOpcode())) {
919     if (isFunctionSelected)
920       report("Unexpected generic instruction in a Selected function", MI);
921 
922     // Check types.
923     SmallVector<LLT, 4> Types;
924     for (unsigned I = 0; I < MCID.getNumOperands(); ++I) {
925       if (!MCID.OpInfo[I].isGenericType())
926         continue;
927       // Generic instructions specify type equality constraints between some of
928       // their operands. Make sure these are consistent.
929       size_t TypeIdx = MCID.OpInfo[I].getGenericTypeIndex();
930       Types.resize(std::max(TypeIdx + 1, Types.size()));
931 
932       const MachineOperand *MO = &MI->getOperand(I);
933       LLT OpTy = MRI->getType(MO->getReg());
934       // Don't report a type mismatch if there is no actual mismatch, only a
935       // type missing, to reduce noise:
936       if (OpTy.isValid()) {
937         // Only the first valid type for a type index will be printed: don't
938         // overwrite it later so it's always clear which type was expected:
939         if (!Types[TypeIdx].isValid())
940           Types[TypeIdx] = OpTy;
941         else if (Types[TypeIdx] != OpTy)
942           report("Type mismatch in generic instruction", MO, I, OpTy);
943       } else {
944         // Generic instructions must have types attached to their operands.
945         report("Generic instruction is missing a virtual register type", MO, I);
946       }
947     }
948 
949     // Generic opcodes must not have physical register operands.
950     for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
951       const MachineOperand *MO = &MI->getOperand(I);
952       if (MO->isReg() && TargetRegisterInfo::isPhysicalRegister(MO->getReg()))
953         report("Generic instruction cannot have physical register", MO, I);
954     }
955   }
956 
957   StringRef ErrorInfo;
958   if (!TII->verifyInstruction(*MI, ErrorInfo))
959     report(ErrorInfo.data(), MI);
960 
961   // Verify properties of various specific instruction types
962   switch(MI->getOpcode()) {
963   default:
964     break;
965   case TargetOpcode::G_LOAD:
966   case TargetOpcode::G_STORE:
967     // Generic loads and stores must have a single MachineMemOperand
968     // describing that access.
969     if (!MI->hasOneMemOperand())
970       report("Generic instruction accessing memory must have one mem operand",
971              MI);
972     break;
973   case TargetOpcode::G_PHI: {
974     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
975     if (!DstTy.isValid() ||
976         !std::all_of(MI->operands_begin() + 1, MI->operands_end(),
977                      [this, &DstTy](const MachineOperand &MO) {
978                        if (!MO.isReg())
979                          return true;
980                        LLT Ty = MRI->getType(MO.getReg());
981                        if (!Ty.isValid() || (Ty != DstTy))
982                          return false;
983                        return true;
984                      }))
985       report("Generic Instruction G_PHI has operands with incompatible/missing "
986              "types",
987              MI);
988     break;
989   }
990   case TargetOpcode::G_SEXT:
991   case TargetOpcode::G_ZEXT:
992   case TargetOpcode::G_ANYEXT:
993   case TargetOpcode::G_TRUNC:
994   case TargetOpcode::G_FPEXT:
995   case TargetOpcode::G_FPTRUNC: {
996     // Number of operands and presense of types is already checked (and
997     // reported in case of any issues), so no need to report them again. As
998     // we're trying to report as many issues as possible at once, however, the
999     // instructions aren't guaranteed to have the right number of operands or
1000     // types attached to them at this point
1001     assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1002     if (MI->getNumOperands() < MCID.getNumOperands())
1003       break;
1004     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1005     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1006     if (!DstTy.isValid() || !SrcTy.isValid())
1007       break;
1008 
1009     LLT DstElTy = DstTy.isVector() ? DstTy.getElementType() : DstTy;
1010     LLT SrcElTy = SrcTy.isVector() ? SrcTy.getElementType() : SrcTy;
1011     if (DstElTy.isPointer() || SrcElTy.isPointer())
1012       report("Generic extend/truncate can not operate on pointers", MI);
1013 
1014     if (DstTy.isVector() != SrcTy.isVector()) {
1015       report("Generic extend/truncate must be all-vector or all-scalar", MI);
1016       // Generally we try to report as many issues as possible at once, but in
1017       // this case it's not clear what should we be comparing the size of the
1018       // scalar with: the size of the whole vector or its lane. Instead of
1019       // making an arbitrary choice and emitting not so helpful message, let's
1020       // avoid the extra noise and stop here.
1021       break;
1022     }
1023     if (DstTy.isVector() && DstTy.getNumElements() != SrcTy.getNumElements())
1024       report("Generic vector extend/truncate must preserve number of lanes",
1025              MI);
1026     unsigned DstSize = DstElTy.getSizeInBits();
1027     unsigned SrcSize = SrcElTy.getSizeInBits();
1028     switch (MI->getOpcode()) {
1029     default:
1030       if (DstSize <= SrcSize)
1031         report("Generic extend has destination type no larger than source", MI);
1032       break;
1033     case TargetOpcode::G_TRUNC:
1034     case TargetOpcode::G_FPTRUNC:
1035       if (DstSize >= SrcSize)
1036         report("Generic truncate has destination type no smaller than source",
1037                MI);
1038       break;
1039     }
1040     break;
1041   }
1042   case TargetOpcode::COPY: {
1043     if (foundErrors)
1044       break;
1045     const MachineOperand &DstOp = MI->getOperand(0);
1046     const MachineOperand &SrcOp = MI->getOperand(1);
1047     LLT DstTy = MRI->getType(DstOp.getReg());
1048     LLT SrcTy = MRI->getType(SrcOp.getReg());
1049     if (SrcTy.isValid() && DstTy.isValid()) {
1050       // If both types are valid, check that the types are the same.
1051       if (SrcTy != DstTy) {
1052         report("Copy Instruction is illegal with mismatching types", MI);
1053         errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n";
1054       }
1055     }
1056     if (SrcTy.isValid() || DstTy.isValid()) {
1057       // If one of them have valid types, let's just check they have the same
1058       // size.
1059       unsigned SrcSize = TRI->getRegSizeInBits(SrcOp.getReg(), *MRI);
1060       unsigned DstSize = TRI->getRegSizeInBits(DstOp.getReg(), *MRI);
1061       assert(SrcSize && "Expecting size here");
1062       assert(DstSize && "Expecting size here");
1063       if (SrcSize != DstSize)
1064         if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
1065           report("Copy Instruction is illegal with mismatching sizes", MI);
1066           errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize
1067                  << "\n";
1068         }
1069     }
1070     break;
1071   }
1072   case TargetOpcode::STATEPOINT:
1073     if (!MI->getOperand(StatepointOpers::IDPos).isImm() ||
1074         !MI->getOperand(StatepointOpers::NBytesPos).isImm() ||
1075         !MI->getOperand(StatepointOpers::NCallArgsPos).isImm())
1076       report("meta operands to STATEPOINT not constant!", MI);
1077     break;
1078 
1079     auto VerifyStackMapConstant = [&](unsigned Offset) {
1080       if (!MI->getOperand(Offset).isImm() ||
1081           MI->getOperand(Offset).getImm() != StackMaps::ConstantOp ||
1082           !MI->getOperand(Offset + 1).isImm())
1083         report("stack map constant to STATEPOINT not well formed!", MI);
1084     };
1085     const unsigned VarStart = StatepointOpers(MI).getVarIdx();
1086     VerifyStackMapConstant(VarStart + StatepointOpers::CCOffset);
1087     VerifyStackMapConstant(VarStart + StatepointOpers::FlagsOffset);
1088     VerifyStackMapConstant(VarStart + StatepointOpers::NumDeoptOperandsOffset);
1089 
1090     // TODO: verify we have properly encoded deopt arguments
1091   };
1092 }
1093 
1094 void
1095 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
1096   const MachineInstr *MI = MO->getParent();
1097   const MCInstrDesc &MCID = MI->getDesc();
1098   unsigned NumDefs = MCID.getNumDefs();
1099   if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
1100     NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
1101 
1102   // The first MCID.NumDefs operands must be explicit register defines
1103   if (MONum < NumDefs) {
1104     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
1105     if (!MO->isReg())
1106       report("Explicit definition must be a register", MO, MONum);
1107     else if (!MO->isDef() && !MCOI.isOptionalDef())
1108       report("Explicit definition marked as use", MO, MONum);
1109     else if (MO->isImplicit())
1110       report("Explicit definition marked as implicit", MO, MONum);
1111   } else if (MONum < MCID.getNumOperands()) {
1112     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
1113     // Don't check if it's the last operand in a variadic instruction. See,
1114     // e.g., LDM_RET in the arm back end.
1115     if (MO->isReg() &&
1116         !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
1117       if (MO->isDef() && !MCOI.isOptionalDef())
1118         report("Explicit operand marked as def", MO, MONum);
1119       if (MO->isImplicit())
1120         report("Explicit operand marked as implicit", MO, MONum);
1121     }
1122 
1123     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
1124     if (TiedTo != -1) {
1125       if (!MO->isReg())
1126         report("Tied use must be a register", MO, MONum);
1127       else if (!MO->isTied())
1128         report("Operand should be tied", MO, MONum);
1129       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
1130         report("Tied def doesn't match MCInstrDesc", MO, MONum);
1131       else if (TargetRegisterInfo::isPhysicalRegister(MO->getReg())) {
1132         const MachineOperand &MOTied = MI->getOperand(TiedTo);
1133         if (!MOTied.isReg())
1134           report("Tied counterpart must be a register", &MOTied, TiedTo);
1135         else if (TargetRegisterInfo::isPhysicalRegister(MOTied.getReg()) &&
1136                  MO->getReg() != MOTied.getReg())
1137           report("Tied physical registers must match.", &MOTied, TiedTo);
1138       }
1139     } else if (MO->isReg() && MO->isTied())
1140       report("Explicit operand should not be tied", MO, MONum);
1141   } else {
1142     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
1143     if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
1144       report("Extra explicit operand on non-variadic instruction", MO, MONum);
1145   }
1146 
1147   switch (MO->getType()) {
1148   case MachineOperand::MO_Register: {
1149     const unsigned Reg = MO->getReg();
1150     if (!Reg)
1151       return;
1152     if (MRI->tracksLiveness() && !MI->isDebugValue())
1153       checkLiveness(MO, MONum);
1154 
1155     // Verify the consistency of tied operands.
1156     if (MO->isTied()) {
1157       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
1158       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
1159       if (!OtherMO.isReg())
1160         report("Must be tied to a register", MO, MONum);
1161       if (!OtherMO.isTied())
1162         report("Missing tie flags on tied operand", MO, MONum);
1163       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
1164         report("Inconsistent tie links", MO, MONum);
1165       if (MONum < MCID.getNumDefs()) {
1166         if (OtherIdx < MCID.getNumOperands()) {
1167           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
1168             report("Explicit def tied to explicit use without tie constraint",
1169                    MO, MONum);
1170         } else {
1171           if (!OtherMO.isImplicit())
1172             report("Explicit def should be tied to implicit use", MO, MONum);
1173         }
1174       }
1175     }
1176 
1177     // Verify two-address constraints after leaving SSA form.
1178     unsigned DefIdx;
1179     if (!MRI->isSSA() && MO->isUse() &&
1180         MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
1181         Reg != MI->getOperand(DefIdx).getReg())
1182       report("Two-address instruction operands must be identical", MO, MONum);
1183 
1184     // Check register classes.
1185     unsigned SubIdx = MO->getSubReg();
1186 
1187     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1188       if (SubIdx) {
1189         report("Illegal subregister index for physical register", MO, MONum);
1190         return;
1191       }
1192       if (MONum < MCID.getNumOperands()) {
1193         if (const TargetRegisterClass *DRC =
1194               TII->getRegClass(MCID, MONum, TRI, *MF)) {
1195           if (!DRC->contains(Reg)) {
1196             report("Illegal physical register for instruction", MO, MONum);
1197             errs() << printReg(Reg, TRI) << " is not a "
1198                    << TRI->getRegClassName(DRC) << " register.\n";
1199           }
1200         }
1201       }
1202       if (MO->isRenamable()) {
1203         if (MRI->isReserved(Reg)) {
1204           report("isRenamable set on reserved register", MO, MONum);
1205           return;
1206         }
1207       }
1208       if (MI->isDebugValue() && MO->isUse() && !MO->isDebug()) {
1209         report("Use-reg is not IsDebug in a DBG_VALUE", MO, MONum);
1210         return;
1211       }
1212     } else {
1213       // Virtual register.
1214       const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
1215       if (!RC) {
1216         // This is a generic virtual register.
1217 
1218         // If we're post-Select, we can't have gvregs anymore.
1219         if (isFunctionSelected) {
1220           report("Generic virtual register invalid in a Selected function",
1221                  MO, MONum);
1222           return;
1223         }
1224 
1225         // The gvreg must have a type and it must not have a SubIdx.
1226         LLT Ty = MRI->getType(Reg);
1227         if (!Ty.isValid()) {
1228           report("Generic virtual register must have a valid type", MO,
1229                  MONum);
1230           return;
1231         }
1232 
1233         const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
1234 
1235         // If we're post-RegBankSelect, the gvreg must have a bank.
1236         if (!RegBank && isFunctionRegBankSelected) {
1237           report("Generic virtual register must have a bank in a "
1238                  "RegBankSelected function",
1239                  MO, MONum);
1240           return;
1241         }
1242 
1243         // Make sure the register fits into its register bank if any.
1244         if (RegBank && Ty.isValid() &&
1245             RegBank->getSize() < Ty.getSizeInBits()) {
1246           report("Register bank is too small for virtual register", MO,
1247                  MONum);
1248           errs() << "Register bank " << RegBank->getName() << " too small("
1249                  << RegBank->getSize() << ") to fit " << Ty.getSizeInBits()
1250                  << "-bits\n";
1251           return;
1252         }
1253         if (SubIdx)  {
1254           report("Generic virtual register does not subregister index", MO,
1255                  MONum);
1256           return;
1257         }
1258 
1259         // If this is a target specific instruction and this operand
1260         // has register class constraint, the virtual register must
1261         // comply to it.
1262         if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
1263             MONum < MCID.getNumOperands() &&
1264             TII->getRegClass(MCID, MONum, TRI, *MF)) {
1265           report("Virtual register does not match instruction constraint", MO,
1266                  MONum);
1267           errs() << "Expect register class "
1268                  << TRI->getRegClassName(
1269                         TII->getRegClass(MCID, MONum, TRI, *MF))
1270                  << " but got nothing\n";
1271           return;
1272         }
1273 
1274         break;
1275       }
1276       if (SubIdx) {
1277         const TargetRegisterClass *SRC =
1278           TRI->getSubClassWithSubReg(RC, SubIdx);
1279         if (!SRC) {
1280           report("Invalid subregister index for virtual register", MO, MONum);
1281           errs() << "Register class " << TRI->getRegClassName(RC)
1282               << " does not support subreg index " << SubIdx << "\n";
1283           return;
1284         }
1285         if (RC != SRC) {
1286           report("Invalid register class for subregister index", MO, MONum);
1287           errs() << "Register class " << TRI->getRegClassName(RC)
1288               << " does not fully support subreg index " << SubIdx << "\n";
1289           return;
1290         }
1291       }
1292       if (MONum < MCID.getNumOperands()) {
1293         if (const TargetRegisterClass *DRC =
1294               TII->getRegClass(MCID, MONum, TRI, *MF)) {
1295           if (SubIdx) {
1296             const TargetRegisterClass *SuperRC =
1297                 TRI->getLargestLegalSuperClass(RC, *MF);
1298             if (!SuperRC) {
1299               report("No largest legal super class exists.", MO, MONum);
1300               return;
1301             }
1302             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
1303             if (!DRC) {
1304               report("No matching super-reg register class.", MO, MONum);
1305               return;
1306             }
1307           }
1308           if (!RC->hasSuperClassEq(DRC)) {
1309             report("Illegal virtual register for instruction", MO, MONum);
1310             errs() << "Expected a " << TRI->getRegClassName(DRC)
1311                 << " register, but got a " << TRI->getRegClassName(RC)
1312                 << " register\n";
1313           }
1314         }
1315       }
1316     }
1317     break;
1318   }
1319 
1320   case MachineOperand::MO_RegisterMask:
1321     regMasks.push_back(MO->getRegMask());
1322     break;
1323 
1324   case MachineOperand::MO_MachineBasicBlock:
1325     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
1326       report("PHI operand is not in the CFG", MO, MONum);
1327     break;
1328 
1329   case MachineOperand::MO_FrameIndex:
1330     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
1331         LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1332       int FI = MO->getIndex();
1333       LiveInterval &LI = LiveStks->getInterval(FI);
1334       SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
1335 
1336       bool stores = MI->mayStore();
1337       bool loads = MI->mayLoad();
1338       // For a memory-to-memory move, we need to check if the frame
1339       // index is used for storing or loading, by inspecting the
1340       // memory operands.
1341       if (stores && loads) {
1342         for (auto *MMO : MI->memoperands()) {
1343           const PseudoSourceValue *PSV = MMO->getPseudoValue();
1344           if (PSV == nullptr) continue;
1345           const FixedStackPseudoSourceValue *Value =
1346             dyn_cast<FixedStackPseudoSourceValue>(PSV);
1347           if (Value == nullptr) continue;
1348           if (Value->getFrameIndex() != FI) continue;
1349 
1350           if (MMO->isStore())
1351             loads = false;
1352           else
1353             stores = false;
1354           break;
1355         }
1356         if (loads == stores)
1357           report("Missing fixed stack memoperand.", MI);
1358       }
1359       if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
1360         report("Instruction loads from dead spill slot", MO, MONum);
1361         errs() << "Live stack: " << LI << '\n';
1362       }
1363       if (stores && !LI.liveAt(Idx.getRegSlot())) {
1364         report("Instruction stores to dead spill slot", MO, MONum);
1365         errs() << "Live stack: " << LI << '\n';
1366       }
1367     }
1368     break;
1369 
1370   default:
1371     break;
1372   }
1373 }
1374 
1375 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
1376     unsigned MONum, SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
1377     LaneBitmask LaneMask) {
1378   LiveQueryResult LRQ = LR.Query(UseIdx);
1379   // Check if we have a segment at the use, note however that we only need one
1380   // live subregister range, the others may be dead.
1381   if (!LRQ.valueIn() && LaneMask.none()) {
1382     report("No live segment at use", MO, MONum);
1383     report_context_liverange(LR);
1384     report_context_vreg_regunit(VRegOrUnit);
1385     report_context(UseIdx);
1386   }
1387   if (MO->isKill() && !LRQ.isKill()) {
1388     report("Live range continues after kill flag", MO, MONum);
1389     report_context_liverange(LR);
1390     report_context_vreg_regunit(VRegOrUnit);
1391     if (LaneMask.any())
1392       report_context_lanemask(LaneMask);
1393     report_context(UseIdx);
1394   }
1395 }
1396 
1397 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
1398     unsigned MONum, SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
1399     LaneBitmask LaneMask) {
1400   if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
1401     assert(VNI && "NULL valno is not allowed");
1402     if (VNI->def != DefIdx) {
1403       report("Inconsistent valno->def", MO, MONum);
1404       report_context_liverange(LR);
1405       report_context_vreg_regunit(VRegOrUnit);
1406       if (LaneMask.any())
1407         report_context_lanemask(LaneMask);
1408       report_context(*VNI);
1409       report_context(DefIdx);
1410     }
1411   } else {
1412     report("No live segment at def", MO, MONum);
1413     report_context_liverange(LR);
1414     report_context_vreg_regunit(VRegOrUnit);
1415     if (LaneMask.any())
1416       report_context_lanemask(LaneMask);
1417     report_context(DefIdx);
1418   }
1419   // Check that, if the dead def flag is present, LiveInts agree.
1420   if (MO->isDead()) {
1421     LiveQueryResult LRQ = LR.Query(DefIdx);
1422     if (!LRQ.isDeadDef()) {
1423       // In case of physregs we can have a non-dead definition on another
1424       // operand.
1425       bool otherDef = false;
1426       if (!TargetRegisterInfo::isVirtualRegister(VRegOrUnit)) {
1427         const MachineInstr &MI = *MO->getParent();
1428         for (const MachineOperand &MO : MI.operands()) {
1429           if (!MO.isReg() || !MO.isDef() || MO.isDead())
1430             continue;
1431           unsigned Reg = MO.getReg();
1432           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1433             if (*Units == VRegOrUnit) {
1434               otherDef = true;
1435               break;
1436             }
1437           }
1438         }
1439       }
1440 
1441       if (!otherDef) {
1442         report("Live range continues after dead def flag", MO, MONum);
1443         report_context_liverange(LR);
1444         report_context_vreg_regunit(VRegOrUnit);
1445         if (LaneMask.any())
1446           report_context_lanemask(LaneMask);
1447       }
1448     }
1449   }
1450 }
1451 
1452 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
1453   const MachineInstr *MI = MO->getParent();
1454   const unsigned Reg = MO->getReg();
1455 
1456   // Both use and def operands can read a register.
1457   if (MO->readsReg()) {
1458     if (MO->isKill())
1459       addRegWithSubRegs(regsKilled, Reg);
1460 
1461     // Check that LiveVars knows this kill.
1462     if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1463         MO->isKill()) {
1464       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1465       if (!is_contained(VI.Kills, MI))
1466         report("Kill missing from LiveVariables", MO, MONum);
1467     }
1468 
1469     // Check LiveInts liveness and kill.
1470     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1471       SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI);
1472       // Check the cached regunit intervals.
1473       if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1474         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1475           if (MRI->isReservedRegUnit(*Units))
1476             continue;
1477           if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units))
1478             checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units);
1479         }
1480       }
1481 
1482       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1483         if (LiveInts->hasInterval(Reg)) {
1484           // This is a virtual register interval.
1485           const LiveInterval &LI = LiveInts->getInterval(Reg);
1486           checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg);
1487 
1488           if (LI.hasSubRanges() && !MO->isDef()) {
1489             unsigned SubRegIdx = MO->getSubReg();
1490             LaneBitmask MOMask = SubRegIdx != 0
1491                                ? TRI->getSubRegIndexLaneMask(SubRegIdx)
1492                                : MRI->getMaxLaneMaskForVReg(Reg);
1493             LaneBitmask LiveInMask;
1494             for (const LiveInterval::SubRange &SR : LI.subranges()) {
1495               if ((MOMask & SR.LaneMask).none())
1496                 continue;
1497               checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
1498               LiveQueryResult LRQ = SR.Query(UseIdx);
1499               if (LRQ.valueIn())
1500                 LiveInMask |= SR.LaneMask;
1501             }
1502             // At least parts of the register has to be live at the use.
1503             if ((LiveInMask & MOMask).none()) {
1504               report("No live subrange at use", MO, MONum);
1505               report_context(LI);
1506               report_context(UseIdx);
1507             }
1508           }
1509         } else {
1510           report("Virtual register has no live interval", MO, MONum);
1511         }
1512       }
1513     }
1514 
1515     // Use of a dead register.
1516     if (!regsLive.count(Reg)) {
1517       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1518         // Reserved registers may be used even when 'dead'.
1519         bool Bad = !isReserved(Reg);
1520         // We are fine if just any subregister has a defined value.
1521         if (Bad) {
1522           for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid();
1523                ++SubRegs) {
1524             if (regsLive.count(*SubRegs)) {
1525               Bad = false;
1526               break;
1527             }
1528           }
1529         }
1530         // If there is an additional implicit-use of a super register we stop
1531         // here. By definition we are fine if the super register is not
1532         // (completely) dead, if the complete super register is dead we will
1533         // get a report for its operand.
1534         if (Bad) {
1535           for (const MachineOperand &MOP : MI->uses()) {
1536             if (!MOP.isReg())
1537               continue;
1538             if (!MOP.isImplicit())
1539               continue;
1540             for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid();
1541                  ++SubRegs) {
1542               if (*SubRegs == Reg) {
1543                 Bad = false;
1544                 break;
1545               }
1546             }
1547           }
1548         }
1549         if (Bad)
1550           report("Using an undefined physical register", MO, MONum);
1551       } else if (MRI->def_empty(Reg)) {
1552         report("Reading virtual register without a def", MO, MONum);
1553       } else {
1554         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1555         // We don't know which virtual registers are live in, so only complain
1556         // if vreg was killed in this MBB. Otherwise keep track of vregs that
1557         // must be live in. PHI instructions are handled separately.
1558         if (MInfo.regsKilled.count(Reg))
1559           report("Using a killed virtual register", MO, MONum);
1560         else if (!MI->isPHI())
1561           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1562       }
1563     }
1564   }
1565 
1566   if (MO->isDef()) {
1567     // Register defined.
1568     // TODO: verify that earlyclobber ops are not used.
1569     if (MO->isDead())
1570       addRegWithSubRegs(regsDead, Reg);
1571     else
1572       addRegWithSubRegs(regsDefined, Reg);
1573 
1574     // Verify SSA form.
1575     if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1576         std::next(MRI->def_begin(Reg)) != MRI->def_end())
1577       report("Multiple virtual register defs in SSA form", MO, MONum);
1578 
1579     // Check LiveInts for a live segment, but only for virtual registers.
1580     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1581       SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
1582       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1583 
1584       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1585         if (LiveInts->hasInterval(Reg)) {
1586           const LiveInterval &LI = LiveInts->getInterval(Reg);
1587           checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg);
1588 
1589           if (LI.hasSubRanges()) {
1590             unsigned SubRegIdx = MO->getSubReg();
1591             LaneBitmask MOMask = SubRegIdx != 0
1592               ? TRI->getSubRegIndexLaneMask(SubRegIdx)
1593               : MRI->getMaxLaneMaskForVReg(Reg);
1594             for (const LiveInterval::SubRange &SR : LI.subranges()) {
1595               if ((SR.LaneMask & MOMask).none())
1596                 continue;
1597               checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, SR.LaneMask);
1598             }
1599           }
1600         } else {
1601           report("Virtual register has no Live interval", MO, MONum);
1602         }
1603       }
1604     }
1605   }
1606 }
1607 
1608 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {}
1609 
1610 // This function gets called after visiting all instructions in a bundle. The
1611 // argument points to the bundle header.
1612 // Normal stand-alone instructions are also considered 'bundles', and this
1613 // function is called for all of them.
1614 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1615   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1616   set_union(MInfo.regsKilled, regsKilled);
1617   set_subtract(regsLive, regsKilled); regsKilled.clear();
1618   // Kill any masked registers.
1619   while (!regMasks.empty()) {
1620     const uint32_t *Mask = regMasks.pop_back_val();
1621     for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1622       if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1623           MachineOperand::clobbersPhysReg(Mask, *I))
1624         regsDead.push_back(*I);
1625   }
1626   set_subtract(regsLive, regsDead);   regsDead.clear();
1627   set_union(regsLive, regsDefined);   regsDefined.clear();
1628 }
1629 
1630 void
1631 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1632   MBBInfoMap[MBB].regsLiveOut = regsLive;
1633   regsLive.clear();
1634 
1635   if (Indexes) {
1636     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1637     if (!(stop > lastIndex)) {
1638       report("Block ends before last instruction index", MBB);
1639       errs() << "Block ends at " << stop
1640           << " last instruction was at " << lastIndex << '\n';
1641     }
1642     lastIndex = stop;
1643   }
1644 }
1645 
1646 // Calculate the largest possible vregsPassed sets. These are the registers that
1647 // can pass through an MBB live, but may not be live every time. It is assumed
1648 // that all vregsPassed sets are empty before the call.
1649 void MachineVerifier::calcRegsPassed() {
1650   // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1651   // have any vregsPassed.
1652   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1653   for (const auto &MBB : *MF) {
1654     BBInfo &MInfo = MBBInfoMap[&MBB];
1655     if (!MInfo.reachable)
1656       continue;
1657     for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1658            SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1659       BBInfo &SInfo = MBBInfoMap[*SuI];
1660       if (SInfo.addPassed(MInfo.regsLiveOut))
1661         todo.insert(*SuI);
1662     }
1663   }
1664 
1665   // Iteratively push vregsPassed to successors. This will converge to the same
1666   // final state regardless of DenseSet iteration order.
1667   while (!todo.empty()) {
1668     const MachineBasicBlock *MBB = *todo.begin();
1669     todo.erase(MBB);
1670     BBInfo &MInfo = MBBInfoMap[MBB];
1671     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1672            SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1673       if (*SuI == MBB)
1674         continue;
1675       BBInfo &SInfo = MBBInfoMap[*SuI];
1676       if (SInfo.addPassed(MInfo.vregsPassed))
1677         todo.insert(*SuI);
1678     }
1679   }
1680 }
1681 
1682 // Calculate the set of virtual registers that must be passed through each basic
1683 // block in order to satisfy the requirements of successor blocks. This is very
1684 // similar to calcRegsPassed, only backwards.
1685 void MachineVerifier::calcRegsRequired() {
1686   // First push live-in regs to predecessors' vregsRequired.
1687   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1688   for (const auto &MBB : *MF) {
1689     BBInfo &MInfo = MBBInfoMap[&MBB];
1690     for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1691            PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1692       BBInfo &PInfo = MBBInfoMap[*PrI];
1693       if (PInfo.addRequired(MInfo.vregsLiveIn))
1694         todo.insert(*PrI);
1695     }
1696   }
1697 
1698   // Iteratively push vregsRequired to predecessors. This will converge to the
1699   // same final state regardless of DenseSet iteration order.
1700   while (!todo.empty()) {
1701     const MachineBasicBlock *MBB = *todo.begin();
1702     todo.erase(MBB);
1703     BBInfo &MInfo = MBBInfoMap[MBB];
1704     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1705            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1706       if (*PrI == MBB)
1707         continue;
1708       BBInfo &SInfo = MBBInfoMap[*PrI];
1709       if (SInfo.addRequired(MInfo.vregsRequired))
1710         todo.insert(*PrI);
1711     }
1712   }
1713 }
1714 
1715 // Check PHI instructions at the beginning of MBB. It is assumed that
1716 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1717 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
1718   BBInfo &MInfo = MBBInfoMap[&MBB];
1719 
1720   SmallPtrSet<const MachineBasicBlock*, 8> seen;
1721   for (const MachineInstr &Phi : MBB) {
1722     if (!Phi.isPHI())
1723       break;
1724     seen.clear();
1725 
1726     const MachineOperand &MODef = Phi.getOperand(0);
1727     if (!MODef.isReg() || !MODef.isDef()) {
1728       report("Expected first PHI operand to be a register def", &MODef, 0);
1729       continue;
1730     }
1731     if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
1732         MODef.isEarlyClobber() || MODef.isDebug())
1733       report("Unexpected flag on PHI operand", &MODef, 0);
1734     unsigned DefReg = MODef.getReg();
1735     if (!TargetRegisterInfo::isVirtualRegister(DefReg))
1736       report("Expected first PHI operand to be a virtual register", &MODef, 0);
1737 
1738     for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
1739       const MachineOperand &MO0 = Phi.getOperand(I);
1740       if (!MO0.isReg()) {
1741         report("Expected PHI operand to be a register", &MO0, I);
1742         continue;
1743       }
1744       if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
1745           MO0.isDebug() || MO0.isTied())
1746         report("Unexpected flag on PHI operand", &MO0, I);
1747 
1748       const MachineOperand &MO1 = Phi.getOperand(I + 1);
1749       if (!MO1.isMBB()) {
1750         report("Expected PHI operand to be a basic block", &MO1, I + 1);
1751         continue;
1752       }
1753 
1754       const MachineBasicBlock &Pre = *MO1.getMBB();
1755       if (!Pre.isSuccessor(&MBB)) {
1756         report("PHI input is not a predecessor block", &MO1, I + 1);
1757         continue;
1758       }
1759 
1760       if (MInfo.reachable) {
1761         seen.insert(&Pre);
1762         BBInfo &PrInfo = MBBInfoMap[&Pre];
1763         if (!MO0.isUndef() && PrInfo.reachable &&
1764             !PrInfo.isLiveOut(MO0.getReg()))
1765           report("PHI operand is not live-out from predecessor", &MO0, I);
1766       }
1767     }
1768 
1769     // Did we see all predecessors?
1770     if (MInfo.reachable) {
1771       for (MachineBasicBlock *Pred : MBB.predecessors()) {
1772         if (!seen.count(Pred)) {
1773           report("Missing PHI operand", &Phi);
1774           errs() << printMBBReference(*Pred)
1775                  << " is a predecessor according to the CFG.\n";
1776         }
1777       }
1778     }
1779   }
1780 }
1781 
1782 void MachineVerifier::visitMachineFunctionAfter() {
1783   calcRegsPassed();
1784 
1785   for (const MachineBasicBlock &MBB : *MF)
1786     checkPHIOps(MBB);
1787 
1788   // Now check liveness info if available
1789   calcRegsRequired();
1790 
1791   // Check for killed virtual registers that should be live out.
1792   for (const auto &MBB : *MF) {
1793     BBInfo &MInfo = MBBInfoMap[&MBB];
1794     for (RegSet::iterator
1795          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1796          ++I)
1797       if (MInfo.regsKilled.count(*I)) {
1798         report("Virtual register killed in block, but needed live out.", &MBB);
1799         errs() << "Virtual register " << printReg(*I)
1800                << " is used after the block.\n";
1801       }
1802   }
1803 
1804   if (!MF->empty()) {
1805     BBInfo &MInfo = MBBInfoMap[&MF->front()];
1806     for (RegSet::iterator
1807          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1808          ++I) {
1809       report("Virtual register defs don't dominate all uses.", MF);
1810       report_context_vreg(*I);
1811     }
1812   }
1813 
1814   if (LiveVars)
1815     verifyLiveVariables();
1816   if (LiveInts)
1817     verifyLiveIntervals();
1818 }
1819 
1820 void MachineVerifier::verifyLiveVariables() {
1821   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1822   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1823     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1824     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1825     for (const auto &MBB : *MF) {
1826       BBInfo &MInfo = MBBInfoMap[&MBB];
1827 
1828       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1829       if (MInfo.vregsRequired.count(Reg)) {
1830         if (!VI.AliveBlocks.test(MBB.getNumber())) {
1831           report("LiveVariables: Block missing from AliveBlocks", &MBB);
1832           errs() << "Virtual register " << printReg(Reg)
1833                  << " must be live through the block.\n";
1834         }
1835       } else {
1836         if (VI.AliveBlocks.test(MBB.getNumber())) {
1837           report("LiveVariables: Block should not be in AliveBlocks", &MBB);
1838           errs() << "Virtual register " << printReg(Reg)
1839                  << " is not needed live through the block.\n";
1840         }
1841       }
1842     }
1843   }
1844 }
1845 
1846 void MachineVerifier::verifyLiveIntervals() {
1847   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1848   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1849     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1850 
1851     // Spilling and splitting may leave unused registers around. Skip them.
1852     if (MRI->reg_nodbg_empty(Reg))
1853       continue;
1854 
1855     if (!LiveInts->hasInterval(Reg)) {
1856       report("Missing live interval for virtual register", MF);
1857       errs() << printReg(Reg, TRI) << " still has defs or uses\n";
1858       continue;
1859     }
1860 
1861     const LiveInterval &LI = LiveInts->getInterval(Reg);
1862     assert(Reg == LI.reg && "Invalid reg to interval mapping");
1863     verifyLiveInterval(LI);
1864   }
1865 
1866   // Verify all the cached regunit intervals.
1867   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1868     if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1869       verifyLiveRange(*LR, i);
1870 }
1871 
1872 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1873                                            const VNInfo *VNI, unsigned Reg,
1874                                            LaneBitmask LaneMask) {
1875   if (VNI->isUnused())
1876     return;
1877 
1878   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1879 
1880   if (!DefVNI) {
1881     report("Value not live at VNInfo def and not marked unused", MF);
1882     report_context(LR, Reg, LaneMask);
1883     report_context(*VNI);
1884     return;
1885   }
1886 
1887   if (DefVNI != VNI) {
1888     report("Live segment at def has different VNInfo", MF);
1889     report_context(LR, Reg, LaneMask);
1890     report_context(*VNI);
1891     return;
1892   }
1893 
1894   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1895   if (!MBB) {
1896     report("Invalid VNInfo definition index", MF);
1897     report_context(LR, Reg, LaneMask);
1898     report_context(*VNI);
1899     return;
1900   }
1901 
1902   if (VNI->isPHIDef()) {
1903     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1904       report("PHIDef VNInfo is not defined at MBB start", MBB);
1905       report_context(LR, Reg, LaneMask);
1906       report_context(*VNI);
1907     }
1908     return;
1909   }
1910 
1911   // Non-PHI def.
1912   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1913   if (!MI) {
1914     report("No instruction at VNInfo def index", MBB);
1915     report_context(LR, Reg, LaneMask);
1916     report_context(*VNI);
1917     return;
1918   }
1919 
1920   if (Reg != 0) {
1921     bool hasDef = false;
1922     bool isEarlyClobber = false;
1923     for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
1924       if (!MOI->isReg() || !MOI->isDef())
1925         continue;
1926       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1927         if (MOI->getReg() != Reg)
1928           continue;
1929       } else {
1930         if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1931             !TRI->hasRegUnit(MOI->getReg(), Reg))
1932           continue;
1933       }
1934       if (LaneMask.any() &&
1935           (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
1936         continue;
1937       hasDef = true;
1938       if (MOI->isEarlyClobber())
1939         isEarlyClobber = true;
1940     }
1941 
1942     if (!hasDef) {
1943       report("Defining instruction does not modify register", MI);
1944       report_context(LR, Reg, LaneMask);
1945       report_context(*VNI);
1946     }
1947 
1948     // Early clobber defs begin at USE slots, but other defs must begin at
1949     // DEF slots.
1950     if (isEarlyClobber) {
1951       if (!VNI->def.isEarlyClobber()) {
1952         report("Early clobber def must be at an early-clobber slot", MBB);
1953         report_context(LR, Reg, LaneMask);
1954         report_context(*VNI);
1955       }
1956     } else if (!VNI->def.isRegister()) {
1957       report("Non-PHI, non-early clobber def must be at a register slot", MBB);
1958       report_context(LR, Reg, LaneMask);
1959       report_context(*VNI);
1960     }
1961   }
1962 }
1963 
1964 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1965                                              const LiveRange::const_iterator I,
1966                                              unsigned Reg, LaneBitmask LaneMask)
1967 {
1968   const LiveRange::Segment &S = *I;
1969   const VNInfo *VNI = S.valno;
1970   assert(VNI && "Live segment has no valno");
1971 
1972   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1973     report("Foreign valno in live segment", MF);
1974     report_context(LR, Reg, LaneMask);
1975     report_context(S);
1976     report_context(*VNI);
1977   }
1978 
1979   if (VNI->isUnused()) {
1980     report("Live segment valno is marked unused", MF);
1981     report_context(LR, Reg, LaneMask);
1982     report_context(S);
1983   }
1984 
1985   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1986   if (!MBB) {
1987     report("Bad start of live segment, no basic block", MF);
1988     report_context(LR, Reg, LaneMask);
1989     report_context(S);
1990     return;
1991   }
1992   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1993   if (S.start != MBBStartIdx && S.start != VNI->def) {
1994     report("Live segment must begin at MBB entry or valno def", MBB);
1995     report_context(LR, Reg, LaneMask);
1996     report_context(S);
1997   }
1998 
1999   const MachineBasicBlock *EndMBB =
2000     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
2001   if (!EndMBB) {
2002     report("Bad end of live segment, no basic block", MF);
2003     report_context(LR, Reg, LaneMask);
2004     report_context(S);
2005     return;
2006   }
2007 
2008   // No more checks for live-out segments.
2009   if (S.end == LiveInts->getMBBEndIdx(EndMBB))
2010     return;
2011 
2012   // RegUnit intervals are allowed dead phis.
2013   if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
2014       S.start == VNI->def && S.end == VNI->def.getDeadSlot())
2015     return;
2016 
2017   // The live segment is ending inside EndMBB
2018   const MachineInstr *MI =
2019     LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
2020   if (!MI) {
2021     report("Live segment doesn't end at a valid instruction", EndMBB);
2022     report_context(LR, Reg, LaneMask);
2023     report_context(S);
2024     return;
2025   }
2026 
2027   // The block slot must refer to a basic block boundary.
2028   if (S.end.isBlock()) {
2029     report("Live segment ends at B slot of an instruction", EndMBB);
2030     report_context(LR, Reg, LaneMask);
2031     report_context(S);
2032   }
2033 
2034   if (S.end.isDead()) {
2035     // Segment ends on the dead slot.
2036     // That means there must be a dead def.
2037     if (!SlotIndex::isSameInstr(S.start, S.end)) {
2038       report("Live segment ending at dead slot spans instructions", EndMBB);
2039       report_context(LR, Reg, LaneMask);
2040       report_context(S);
2041     }
2042   }
2043 
2044   // A live segment can only end at an early-clobber slot if it is being
2045   // redefined by an early-clobber def.
2046   if (S.end.isEarlyClobber()) {
2047     if (I+1 == LR.end() || (I+1)->start != S.end) {
2048       report("Live segment ending at early clobber slot must be "
2049              "redefined by an EC def in the same instruction", EndMBB);
2050       report_context(LR, Reg, LaneMask);
2051       report_context(S);
2052     }
2053   }
2054 
2055   // The following checks only apply to virtual registers. Physreg liveness
2056   // is too weird to check.
2057   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2058     // A live segment can end with either a redefinition, a kill flag on a
2059     // use, or a dead flag on a def.
2060     bool hasRead = false;
2061     bool hasSubRegDef = false;
2062     bool hasDeadDef = false;
2063     for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
2064       if (!MOI->isReg() || MOI->getReg() != Reg)
2065         continue;
2066       unsigned Sub = MOI->getSubReg();
2067       LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
2068                                  : LaneBitmask::getAll();
2069       if (MOI->isDef()) {
2070         if (Sub != 0) {
2071           hasSubRegDef = true;
2072           // An operand %0:sub0 reads %0:sub1..n. Invert the lane
2073           // mask for subregister defs. Read-undef defs will be handled by
2074           // readsReg below.
2075           SLM = ~SLM;
2076         }
2077         if (MOI->isDead())
2078           hasDeadDef = true;
2079       }
2080       if (LaneMask.any() && (LaneMask & SLM).none())
2081         continue;
2082       if (MOI->readsReg())
2083         hasRead = true;
2084     }
2085     if (S.end.isDead()) {
2086       // Make sure that the corresponding machine operand for a "dead" live
2087       // range has the dead flag. We cannot perform this check for subregister
2088       // liveranges as partially dead values are allowed.
2089       if (LaneMask.none() && !hasDeadDef) {
2090         report("Instruction ending live segment on dead slot has no dead flag",
2091                MI);
2092         report_context(LR, Reg, LaneMask);
2093         report_context(S);
2094       }
2095     } else {
2096       if (!hasRead) {
2097         // When tracking subregister liveness, the main range must start new
2098         // values on partial register writes, even if there is no read.
2099         if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
2100             !hasSubRegDef) {
2101           report("Instruction ending live segment doesn't read the register",
2102                  MI);
2103           report_context(LR, Reg, LaneMask);
2104           report_context(S);
2105         }
2106       }
2107     }
2108   }
2109 
2110   // Now check all the basic blocks in this live segment.
2111   MachineFunction::const_iterator MFI = MBB->getIterator();
2112   // Is this live segment the beginning of a non-PHIDef VN?
2113   if (S.start == VNI->def && !VNI->isPHIDef()) {
2114     // Not live-in to any blocks.
2115     if (MBB == EndMBB)
2116       return;
2117     // Skip this block.
2118     ++MFI;
2119   }
2120 
2121   SmallVector<SlotIndex, 4> Undefs;
2122   if (LaneMask.any()) {
2123     LiveInterval &OwnerLI = LiveInts->getInterval(Reg);
2124     OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
2125   }
2126 
2127   while (true) {
2128     assert(LiveInts->isLiveInToMBB(LR, &*MFI));
2129     // We don't know how to track physregs into a landing pad.
2130     if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
2131         MFI->isEHPad()) {
2132       if (&*MFI == EndMBB)
2133         break;
2134       ++MFI;
2135       continue;
2136     }
2137 
2138     // Is VNI a PHI-def in the current block?
2139     bool IsPHI = VNI->isPHIDef() &&
2140       VNI->def == LiveInts->getMBBStartIdx(&*MFI);
2141 
2142     // Check that VNI is live-out of all predecessors.
2143     for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
2144          PE = MFI->pred_end(); PI != PE; ++PI) {
2145       SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
2146       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
2147 
2148       // All predecessors must have a live-out value. However for a phi
2149       // instruction with subregister intervals
2150       // only one of the subregisters (not necessarily the current one) needs to
2151       // be defined.
2152       if (!PVNI && (LaneMask.none() || !IsPHI)) {
2153         if (LiveRangeCalc::isJointlyDominated(*PI, Undefs, *Indexes))
2154           continue;
2155         report("Register not marked live out of predecessor", *PI);
2156         report_context(LR, Reg, LaneMask);
2157         report_context(*VNI);
2158         errs() << " live into " << printMBBReference(*MFI) << '@'
2159                << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
2160                << PEnd << '\n';
2161         continue;
2162       }
2163 
2164       // Only PHI-defs can take different predecessor values.
2165       if (!IsPHI && PVNI != VNI) {
2166         report("Different value live out of predecessor", *PI);
2167         report_context(LR, Reg, LaneMask);
2168         errs() << "Valno #" << PVNI->id << " live out of "
2169                << printMBBReference(*(*PI)) << '@' << PEnd << "\nValno #"
2170                << VNI->id << " live into " << printMBBReference(*MFI) << '@'
2171                << LiveInts->getMBBStartIdx(&*MFI) << '\n';
2172       }
2173     }
2174     if (&*MFI == EndMBB)
2175       break;
2176     ++MFI;
2177   }
2178 }
2179 
2180 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg,
2181                                       LaneBitmask LaneMask) {
2182   for (const VNInfo *VNI : LR.valnos)
2183     verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
2184 
2185   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
2186     verifyLiveRangeSegment(LR, I, Reg, LaneMask);
2187 }
2188 
2189 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
2190   unsigned Reg = LI.reg;
2191   assert(TargetRegisterInfo::isVirtualRegister(Reg));
2192   verifyLiveRange(LI, Reg);
2193 
2194   LaneBitmask Mask;
2195   LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2196   for (const LiveInterval::SubRange &SR : LI.subranges()) {
2197     if ((Mask & SR.LaneMask).any()) {
2198       report("Lane masks of sub ranges overlap in live interval", MF);
2199       report_context(LI);
2200     }
2201     if ((SR.LaneMask & ~MaxMask).any()) {
2202       report("Subrange lanemask is invalid", MF);
2203       report_context(LI);
2204     }
2205     if (SR.empty()) {
2206       report("Subrange must not be empty", MF);
2207       report_context(SR, LI.reg, SR.LaneMask);
2208     }
2209     Mask |= SR.LaneMask;
2210     verifyLiveRange(SR, LI.reg, SR.LaneMask);
2211     if (!LI.covers(SR)) {
2212       report("A Subrange is not covered by the main range", MF);
2213       report_context(LI);
2214     }
2215   }
2216 
2217   // Check the LI only has one connected component.
2218   ConnectedVNInfoEqClasses ConEQ(*LiveInts);
2219   unsigned NumComp = ConEQ.Classify(LI);
2220   if (NumComp > 1) {
2221     report("Multiple connected components in live interval", MF);
2222     report_context(LI);
2223     for (unsigned comp = 0; comp != NumComp; ++comp) {
2224       errs() << comp << ": valnos";
2225       for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
2226            E = LI.vni_end(); I!=E; ++I)
2227         if (comp == ConEQ.getEqClass(*I))
2228           errs() << ' ' << (*I)->id;
2229       errs() << '\n';
2230     }
2231   }
2232 }
2233 
2234 namespace {
2235 
2236   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
2237   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
2238   // value is zero.
2239   // We use a bool plus an integer to capture the stack state.
2240   struct StackStateOfBB {
2241     StackStateOfBB() = default;
2242     StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
2243       EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
2244       ExitIsSetup(ExitSetup) {}
2245 
2246     // Can be negative, which means we are setting up a frame.
2247     int EntryValue = 0;
2248     int ExitValue = 0;
2249     bool EntryIsSetup = false;
2250     bool ExitIsSetup = false;
2251   };
2252 
2253 } // end anonymous namespace
2254 
2255 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
2256 /// by a FrameDestroy <n>, stack adjustments are identical on all
2257 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
2258 void MachineVerifier::verifyStackFrame() {
2259   unsigned FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
2260   unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
2261   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
2262     return;
2263 
2264   SmallVector<StackStateOfBB, 8> SPState;
2265   SPState.resize(MF->getNumBlockIDs());
2266   df_iterator_default_set<const MachineBasicBlock*> Reachable;
2267 
2268   // Visit the MBBs in DFS order.
2269   for (df_ext_iterator<const MachineFunction *,
2270                        df_iterator_default_set<const MachineBasicBlock *>>
2271        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
2272        DFI != DFE; ++DFI) {
2273     const MachineBasicBlock *MBB = *DFI;
2274 
2275     StackStateOfBB BBState;
2276     // Check the exit state of the DFS stack predecessor.
2277     if (DFI.getPathLength() >= 2) {
2278       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
2279       assert(Reachable.count(StackPred) &&
2280              "DFS stack predecessor is already visited.\n");
2281       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
2282       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
2283       BBState.ExitValue = BBState.EntryValue;
2284       BBState.ExitIsSetup = BBState.EntryIsSetup;
2285     }
2286 
2287     // Update stack state by checking contents of MBB.
2288     for (const auto &I : *MBB) {
2289       if (I.getOpcode() == FrameSetupOpcode) {
2290         if (BBState.ExitIsSetup)
2291           report("FrameSetup is after another FrameSetup", &I);
2292         BBState.ExitValue -= TII->getFrameTotalSize(I);
2293         BBState.ExitIsSetup = true;
2294       }
2295 
2296       if (I.getOpcode() == FrameDestroyOpcode) {
2297         int Size = TII->getFrameTotalSize(I);
2298         if (!BBState.ExitIsSetup)
2299           report("FrameDestroy is not after a FrameSetup", &I);
2300         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
2301                                                BBState.ExitValue;
2302         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
2303           report("FrameDestroy <n> is after FrameSetup <m>", &I);
2304           errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
2305               << AbsSPAdj << ">.\n";
2306         }
2307         BBState.ExitValue += Size;
2308         BBState.ExitIsSetup = false;
2309       }
2310     }
2311     SPState[MBB->getNumber()] = BBState;
2312 
2313     // Make sure the exit state of any predecessor is consistent with the entry
2314     // state.
2315     for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
2316          E = MBB->pred_end(); I != E; ++I) {
2317       if (Reachable.count(*I) &&
2318           (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
2319            SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
2320         report("The exit stack state of a predecessor is inconsistent.", MBB);
2321         errs() << "Predecessor " << printMBBReference(*(*I))
2322                << " has exit state (" << SPState[(*I)->getNumber()].ExitValue
2323                << ", " << SPState[(*I)->getNumber()].ExitIsSetup << "), while "
2324                << printMBBReference(*MBB) << " has entry state ("
2325                << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
2326       }
2327     }
2328 
2329     // Make sure the entry state of any successor is consistent with the exit
2330     // state.
2331     for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
2332          E = MBB->succ_end(); I != E; ++I) {
2333       if (Reachable.count(*I) &&
2334           (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
2335            SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
2336         report("The entry stack state of a successor is inconsistent.", MBB);
2337         errs() << "Successor " << printMBBReference(*(*I))
2338                << " has entry state (" << SPState[(*I)->getNumber()].EntryValue
2339                << ", " << SPState[(*I)->getNumber()].EntryIsSetup << "), while "
2340                << printMBBReference(*MBB) << " has exit state ("
2341                << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
2342       }
2343     }
2344 
2345     // Make sure a basic block with return ends with zero stack adjustment.
2346     if (!MBB->empty() && MBB->back().isReturn()) {
2347       if (BBState.ExitIsSetup)
2348         report("A return block ends with a FrameSetup.", MBB);
2349       if (BBState.ExitValue)
2350         report("A return block ends with a nonzero stack adjustment.", MBB);
2351     }
2352   }
2353 }
2354