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