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