xref: /llvm-project/llvm/lib/CodeGen/MachineVerifier.cpp (revision e494e2a29449a5ce7fce16b5dc1d0033b1ba69e8)
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 with the command-line option
20 // -verify-machineinstrs.
21 //===----------------------------------------------------------------------===//
22 
23 #include "llvm/CodeGen/MachineVerifier.h"
24 #include "llvm/ADT/BitVector.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/PostOrderIterator.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/CodeGen/CodeGenCommonISel.h"
36 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.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/MachineConvergenceVerifier.h"
44 #include "llvm/CodeGen/MachineDominators.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineFunctionPass.h"
48 #include "llvm/CodeGen/MachineInstr.h"
49 #include "llvm/CodeGen/MachineInstrBundle.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/PseudoSourceValue.h"
54 #include "llvm/CodeGen/RegisterBank.h"
55 #include "llvm/CodeGen/RegisterBankInfo.h"
56 #include "llvm/CodeGen/SlotIndexes.h"
57 #include "llvm/CodeGen/StackMaps.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGenTypes/LowLevelType.h"
64 #include "llvm/IR/BasicBlock.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/EHPersonalities.h"
67 #include "llvm/IR/Function.h"
68 #include "llvm/IR/InlineAsm.h"
69 #include "llvm/IR/Instructions.h"
70 #include "llvm/InitializePasses.h"
71 #include "llvm/MC/LaneBitmask.h"
72 #include "llvm/MC/MCAsmInfo.h"
73 #include "llvm/MC/MCDwarf.h"
74 #include "llvm/MC/MCInstrDesc.h"
75 #include "llvm/MC/MCRegisterInfo.h"
76 #include "llvm/MC/MCTargetOptions.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/MathExtras.h"
81 #include "llvm/Support/ModRef.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include "llvm/Target/TargetMachine.h"
84 #include <algorithm>
85 #include <cassert>
86 #include <cstddef>
87 #include <cstdint>
88 #include <iterator>
89 #include <string>
90 #include <utility>
91 
92 using namespace llvm;
93 
94 namespace {
95 
96   struct MachineVerifier {
97     MachineVerifier(MachineFunctionAnalysisManager &MFAM, const char *b)
98         : MFAM(&MFAM), Banner(b) {}
99 
100     MachineVerifier(Pass *pass, const char *b) : PASS(pass), Banner(b) {}
101 
102     MachineVerifier(const char *b, LiveVariables *LiveVars,
103                     LiveIntervals *LiveInts, LiveStacks *LiveStks,
104                     SlotIndexes *Indexes)
105         : Banner(b), LiveVars(LiveVars), LiveInts(LiveInts), LiveStks(LiveStks),
106           Indexes(Indexes) {}
107 
108     unsigned verify(const MachineFunction &MF);
109 
110     MachineFunctionAnalysisManager *MFAM = nullptr;
111     Pass *const PASS = nullptr;
112     const char *Banner;
113     const MachineFunction *MF = nullptr;
114     const TargetMachine *TM = nullptr;
115     const TargetInstrInfo *TII = nullptr;
116     const TargetRegisterInfo *TRI = nullptr;
117     const MachineRegisterInfo *MRI = nullptr;
118     const RegisterBankInfo *RBI = nullptr;
119 
120     unsigned foundErrors = 0;
121 
122     // Avoid querying the MachineFunctionProperties for each operand.
123     bool isFunctionRegBankSelected = false;
124     bool isFunctionSelected = false;
125     bool isFunctionTracksDebugUserValues = false;
126 
127     using RegVector = SmallVector<Register, 16>;
128     using RegMaskVector = SmallVector<const uint32_t *, 4>;
129     using RegSet = DenseSet<Register>;
130     using RegMap = DenseMap<Register, const MachineInstr *>;
131     using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>;
132 
133     const MachineInstr *FirstNonPHI = nullptr;
134     const MachineInstr *FirstTerminator = nullptr;
135     BlockSet FunctionBlocks;
136 
137     BitVector regsReserved;
138     RegSet regsLive;
139     RegVector regsDefined, regsDead, regsKilled;
140     RegMaskVector regMasks;
141 
142     SlotIndex lastIndex;
143 
144     // Add Reg and any sub-registers to RV
145     void addRegWithSubRegs(RegVector &RV, Register Reg) {
146       RV.push_back(Reg);
147       if (Reg.isPhysical())
148         append_range(RV, TRI->subregs(Reg.asMCReg()));
149     }
150 
151     struct BBInfo {
152       // Is this MBB reachable from the MF entry point?
153       bool reachable = false;
154 
155       // Vregs that must be live in because they are used without being
156       // defined. Map value is the user. vregsLiveIn doesn't include regs
157       // that only are used by PHI nodes.
158       RegMap vregsLiveIn;
159 
160       // Regs killed in MBB. They may be defined again, and will then be in both
161       // regsKilled and regsLiveOut.
162       RegSet regsKilled;
163 
164       // Regs defined in MBB and live out. Note that vregs passing through may
165       // be live out without being mentioned here.
166       RegSet regsLiveOut;
167 
168       // Vregs that pass through MBB untouched. This set is disjoint from
169       // regsKilled and regsLiveOut.
170       RegSet vregsPassed;
171 
172       // Vregs that must pass through MBB because they are needed by a successor
173       // block. This set is disjoint from regsLiveOut.
174       RegSet vregsRequired;
175 
176       // Set versions of block's predecessor and successor lists.
177       BlockSet Preds, Succs;
178 
179       BBInfo() = default;
180 
181       // Add register to vregsRequired if it belongs there. Return true if
182       // anything changed.
183       bool addRequired(Register Reg) {
184         if (!Reg.isVirtual())
185           return false;
186         if (regsLiveOut.count(Reg))
187           return false;
188         return vregsRequired.insert(Reg).second;
189       }
190 
191       // Same for a full set.
192       bool addRequired(const RegSet &RS) {
193         bool Changed = false;
194         for (Register Reg : RS)
195           Changed |= addRequired(Reg);
196         return Changed;
197       }
198 
199       // Same for a full map.
200       bool addRequired(const RegMap &RM) {
201         bool Changed = false;
202         for (const auto &I : RM)
203           Changed |= addRequired(I.first);
204         return Changed;
205       }
206 
207       // Live-out registers are either in regsLiveOut or vregsPassed.
208       bool isLiveOut(Register 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(Register Reg) {
217       return Reg.id() < regsReserved.size() && regsReserved.test(Reg.id());
218     }
219 
220     bool isAllocatable(Register Reg) const {
221       return Reg.id() < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
222              !regsReserved.test(Reg.id());
223     }
224 
225     // Analysis information if available
226     LiveVariables *LiveVars = nullptr;
227     LiveIntervals *LiveInts = nullptr;
228     LiveStacks *LiveStks = nullptr;
229     SlotIndexes *Indexes = nullptr;
230 
231     // This is calculated only when trying to verify convergence control tokens.
232     // Similar to the LLVM IR verifier, we calculate this locally instead of
233     // relying on the pass manager.
234     MachineDominatorTree DT;
235 
236     void visitMachineFunctionBefore();
237     void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
238     void visitMachineBundleBefore(const MachineInstr *MI);
239 
240     /// Verify that all of \p MI's virtual register operands are scalars.
241     /// \returns True if all virtual register operands are scalar. False
242     /// otherwise.
243     bool verifyAllRegOpsScalar(const MachineInstr &MI,
244                                const MachineRegisterInfo &MRI);
245     bool verifyVectorElementMatch(LLT Ty0, LLT Ty1, const MachineInstr *MI);
246 
247     bool verifyGIntrinsicSideEffects(const MachineInstr *MI);
248     bool verifyGIntrinsicConvergence(const MachineInstr *MI);
249     void verifyPreISelGenericInstruction(const MachineInstr *MI);
250 
251     void visitMachineInstrBefore(const MachineInstr *MI);
252     void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
253     void visitMachineBundleAfter(const MachineInstr *MI);
254     void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
255     void visitMachineFunctionAfter();
256 
257     void report(const char *msg, const MachineFunction *MF);
258     void report(const char *msg, const MachineBasicBlock *MBB);
259     void report(const char *msg, const MachineInstr *MI);
260     void report(const char *msg, const MachineOperand *MO, unsigned MONum,
261                 LLT MOVRegType = LLT{});
262     void report(const Twine &Msg, const MachineInstr *MI);
263 
264     void report_context(const LiveInterval &LI) const;
265     void report_context(const LiveRange &LR, Register VRegUnit,
266                         LaneBitmask LaneMask) const;
267     void report_context(const LiveRange::Segment &S) const;
268     void report_context(const VNInfo &VNI) const;
269     void report_context(SlotIndex Pos) const;
270     void report_context(MCPhysReg PhysReg) const;
271     void report_context_liverange(const LiveRange &LR) const;
272     void report_context_lanemask(LaneBitmask LaneMask) const;
273     void report_context_vreg(Register VReg) const;
274     void report_context_vreg_regunit(Register VRegOrUnit) const;
275 
276     void verifyInlineAsm(const MachineInstr *MI);
277 
278     void checkLiveness(const MachineOperand *MO, unsigned MONum);
279     void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
280                             SlotIndex UseIdx, const LiveRange &LR,
281                             Register VRegOrUnit,
282                             LaneBitmask LaneMask = LaneBitmask::getNone());
283     void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
284                             SlotIndex DefIdx, const LiveRange &LR,
285                             Register VRegOrUnit, bool SubRangeCheck = false,
286                             LaneBitmask LaneMask = LaneBitmask::getNone());
287 
288     void markReachable(const MachineBasicBlock *MBB);
289     void calcRegsPassed();
290     void checkPHIOps(const MachineBasicBlock &MBB);
291 
292     void calcRegsRequired();
293     void verifyLiveVariables();
294     void verifyLiveIntervals();
295     void verifyLiveInterval(const LiveInterval&);
296     void verifyLiveRangeValue(const LiveRange &, const VNInfo *, Register,
297                               LaneBitmask);
298     void verifyLiveRangeSegment(const LiveRange &,
299                                 const LiveRange::const_iterator I, Register,
300                                 LaneBitmask);
301     void verifyLiveRange(const LiveRange &, Register,
302                          LaneBitmask LaneMask = LaneBitmask::getNone());
303 
304     void verifyStackFrame();
305 
306     void verifySlotIndexes() const;
307     void verifyProperties(const MachineFunction &MF);
308   };
309 
310   struct MachineVerifierLegacyPass : public MachineFunctionPass {
311     static char ID; // Pass ID, replacement for typeid
312 
313     const std::string Banner;
314 
315     MachineVerifierLegacyPass(std::string banner = std::string())
316         : MachineFunctionPass(ID), Banner(std::move(banner)) {
317       initializeMachineVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
318     }
319 
320     void getAnalysisUsage(AnalysisUsage &AU) const override {
321       AU.addUsedIfAvailable<LiveStacks>();
322       AU.addUsedIfAvailable<LiveVariablesWrapperPass>();
323       AU.addUsedIfAvailable<SlotIndexesWrapperPass>();
324       AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
325       AU.setPreservesAll();
326       MachineFunctionPass::getAnalysisUsage(AU);
327     }
328 
329     bool runOnMachineFunction(MachineFunction &MF) override {
330       // Skip functions that have known verification problems.
331       // FIXME: Remove this mechanism when all problematic passes have been
332       // fixed.
333       if (MF.getProperties().hasProperty(
334               MachineFunctionProperties::Property::FailsVerification))
335         return false;
336 
337       unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF);
338       if (FoundErrors)
339         report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
340       return false;
341     }
342   };
343 
344 } // end anonymous namespace
345 
346 PreservedAnalyses
347 MachineVerifierPass::run(MachineFunction &MF,
348                          MachineFunctionAnalysisManager &MFAM) {
349   // Skip functions that have known verification problems.
350   // FIXME: Remove this mechanism when all problematic passes have been
351   // fixed.
352   if (MF.getProperties().hasProperty(
353           MachineFunctionProperties::Property::FailsVerification))
354     return PreservedAnalyses::all();
355   unsigned FoundErrors = MachineVerifier(MFAM, Banner.c_str()).verify(MF);
356   if (FoundErrors)
357     report_fatal_error("Found " + Twine(FoundErrors) + " machine code errors.");
358   return PreservedAnalyses::all();
359 }
360 
361 char MachineVerifierLegacyPass::ID = 0;
362 
363 INITIALIZE_PASS(MachineVerifierLegacyPass, "machineverifier",
364                 "Verify generated machine code", false, false)
365 
366 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
367   return new MachineVerifierLegacyPass(Banner);
368 }
369 
370 void llvm::verifyMachineFunction(const std::string &Banner,
371                                  const MachineFunction &MF) {
372   // TODO: Use MFAM after porting below analyses.
373   // LiveVariables *LiveVars;
374   // LiveIntervals *LiveInts;
375   // LiveStacks *LiveStks;
376   // SlotIndexes *Indexes;
377   unsigned FoundErrors = MachineVerifier(nullptr, Banner.c_str()).verify(MF);
378   if (FoundErrors)
379     report_fatal_error("Found " + Twine(FoundErrors) + " machine code errors.");
380 }
381 
382 bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors)
383     const {
384   MachineFunction &MF = const_cast<MachineFunction&>(*this);
385   unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF);
386   if (AbortOnErrors && FoundErrors)
387     report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
388   return FoundErrors == 0;
389 }
390 
391 bool MachineFunction::verify(LiveIntervals *LiveInts, SlotIndexes *Indexes,
392                              const char *Banner, bool AbortOnErrors) const {
393   MachineFunction &MF = const_cast<MachineFunction &>(*this);
394   unsigned FoundErrors =
395       MachineVerifier(Banner, nullptr, LiveInts, nullptr, Indexes).verify(MF);
396   if (AbortOnErrors && FoundErrors)
397     report_fatal_error("Found " + Twine(FoundErrors) + " machine code errors.");
398   return FoundErrors == 0;
399 }
400 
401 void MachineVerifier::verifySlotIndexes() const {
402   if (Indexes == nullptr)
403     return;
404 
405   // Ensure the IdxMBB list is sorted by slot indexes.
406   SlotIndex Last;
407   for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
408        E = Indexes->MBBIndexEnd(); I != E; ++I) {
409     assert(!Last.isValid() || I->first > Last);
410     Last = I->first;
411   }
412 }
413 
414 void MachineVerifier::verifyProperties(const MachineFunction &MF) {
415   // If a pass has introduced virtual registers without clearing the
416   // NoVRegs property (or set it without allocating the vregs)
417   // then report an error.
418   if (MF.getProperties().hasProperty(
419           MachineFunctionProperties::Property::NoVRegs) &&
420       MRI->getNumVirtRegs())
421     report("Function has NoVRegs property but there are VReg operands", &MF);
422 }
423 
424 unsigned MachineVerifier::verify(const MachineFunction &MF) {
425   foundErrors = 0;
426 
427   this->MF = &MF;
428   TM = &MF.getTarget();
429   TII = MF.getSubtarget().getInstrInfo();
430   TRI = MF.getSubtarget().getRegisterInfo();
431   RBI = MF.getSubtarget().getRegBankInfo();
432   MRI = &MF.getRegInfo();
433 
434   const bool isFunctionFailedISel = MF.getProperties().hasProperty(
435       MachineFunctionProperties::Property::FailedISel);
436 
437   // If we're mid-GlobalISel and we already triggered the fallback path then
438   // it's expected that the MIR is somewhat broken but that's ok since we'll
439   // reset it and clear the FailedISel attribute in ResetMachineFunctions.
440   if (isFunctionFailedISel)
441     return foundErrors;
442 
443   isFunctionRegBankSelected = MF.getProperties().hasProperty(
444       MachineFunctionProperties::Property::RegBankSelected);
445   isFunctionSelected = MF.getProperties().hasProperty(
446       MachineFunctionProperties::Property::Selected);
447   isFunctionTracksDebugUserValues = MF.getProperties().hasProperty(
448       MachineFunctionProperties::Property::TracksDebugUserValues);
449 
450   if (PASS) {
451     auto *LISWrapper = PASS->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
452     LiveInts = LISWrapper ? &LISWrapper->getLIS() : nullptr;
453     // We don't want to verify LiveVariables if LiveIntervals is available.
454     auto *LVWrapper = PASS->getAnalysisIfAvailable<LiveVariablesWrapperPass>();
455     if (!LiveInts)
456       LiveVars = LVWrapper ? &LVWrapper->getLV() : nullptr;
457     LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
458     auto *SIWrapper = PASS->getAnalysisIfAvailable<SlotIndexesWrapperPass>();
459     Indexes = SIWrapper ? &SIWrapper->getSI() : nullptr;
460   }
461   if (MFAM) {
462     MachineFunction &Func = const_cast<MachineFunction &>(MF);
463     LiveInts = MFAM->getCachedResult<LiveIntervalsAnalysis>(Func);
464     if (!LiveInts)
465       LiveVars = MFAM->getCachedResult<LiveVariablesAnalysis>(Func);
466     // TODO: LiveStks = MFAM->getCachedResult<LiveStacksAnalysis>(Func);
467     Indexes = MFAM->getCachedResult<SlotIndexesAnalysis>(Func);
468   }
469 
470   verifySlotIndexes();
471 
472   verifyProperties(MF);
473 
474   visitMachineFunctionBefore();
475   for (const MachineBasicBlock &MBB : MF) {
476     visitMachineBasicBlockBefore(&MBB);
477     // Keep track of the current bundle header.
478     const MachineInstr *CurBundle = nullptr;
479     // Do we expect the next instruction to be part of the same bundle?
480     bool InBundle = false;
481 
482     for (const MachineInstr &MI : MBB.instrs()) {
483       if (MI.getParent() != &MBB) {
484         report("Bad instruction parent pointer", &MBB);
485         errs() << "Instruction: " << MI;
486         continue;
487       }
488 
489       // Check for consistent bundle flags.
490       if (InBundle && !MI.isBundledWithPred())
491         report("Missing BundledPred flag, "
492                "BundledSucc was set on predecessor",
493                &MI);
494       if (!InBundle && MI.isBundledWithPred())
495         report("BundledPred flag is set, "
496                "but BundledSucc not set on predecessor",
497                &MI);
498 
499       // Is this a bundle header?
500       if (!MI.isInsideBundle()) {
501         if (CurBundle)
502           visitMachineBundleAfter(CurBundle);
503         CurBundle = &MI;
504         visitMachineBundleBefore(CurBundle);
505       } else if (!CurBundle)
506         report("No bundle header", &MI);
507       visitMachineInstrBefore(&MI);
508       for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
509         const MachineOperand &Op = MI.getOperand(I);
510         if (Op.getParent() != &MI) {
511           // Make sure to use correct addOperand / removeOperand / ChangeTo
512           // functions when replacing operands of a MachineInstr.
513           report("Instruction has operand with wrong parent set", &MI);
514         }
515 
516         visitMachineOperand(&Op, I);
517       }
518 
519       // Was this the last bundled instruction?
520       InBundle = MI.isBundledWithSucc();
521     }
522     if (CurBundle)
523       visitMachineBundleAfter(CurBundle);
524     if (InBundle)
525       report("BundledSucc flag set on last instruction in block", &MBB.back());
526     visitMachineBasicBlockAfter(&MBB);
527   }
528   visitMachineFunctionAfter();
529 
530   // Clean up.
531   regsLive.clear();
532   regsDefined.clear();
533   regsDead.clear();
534   regsKilled.clear();
535   regMasks.clear();
536   MBBInfoMap.clear();
537 
538   return foundErrors;
539 }
540 
541 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
542   assert(MF);
543   errs() << '\n';
544   if (!foundErrors++) {
545     if (Banner)
546       errs() << "# " << Banner << '\n';
547     if (LiveInts != nullptr)
548       LiveInts->print(errs());
549     else
550       MF->print(errs(), Indexes);
551   }
552   errs() << "*** Bad machine code: " << msg << " ***\n"
553       << "- function:    " << MF->getName() << "\n";
554 }
555 
556 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
557   assert(MBB);
558   report(msg, MBB->getParent());
559   errs() << "- basic block: " << printMBBReference(*MBB) << ' '
560          << MBB->getName() << " (" << (const void *)MBB << ')';
561   if (Indexes)
562     errs() << " [" << Indexes->getMBBStartIdx(MBB)
563         << ';' <<  Indexes->getMBBEndIdx(MBB) << ')';
564   errs() << '\n';
565 }
566 
567 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
568   assert(MI);
569   report(msg, MI->getParent());
570   errs() << "- instruction: ";
571   if (Indexes && Indexes->hasIndex(*MI))
572     errs() << Indexes->getInstructionIndex(*MI) << '\t';
573   MI->print(errs(), /*IsStandalone=*/true);
574 }
575 
576 void MachineVerifier::report(const char *msg, const MachineOperand *MO,
577                              unsigned MONum, LLT MOVRegType) {
578   assert(MO);
579   report(msg, MO->getParent());
580   errs() << "- operand " << MONum << ":   ";
581   MO->print(errs(), MOVRegType, TRI);
582   errs() << "\n";
583 }
584 
585 void MachineVerifier::report(const Twine &Msg, const MachineInstr *MI) {
586   report(Msg.str().c_str(), MI);
587 }
588 
589 void MachineVerifier::report_context(SlotIndex Pos) const {
590   errs() << "- at:          " << Pos << '\n';
591 }
592 
593 void MachineVerifier::report_context(const LiveInterval &LI) const {
594   errs() << "- interval:    " << LI << '\n';
595 }
596 
597 void MachineVerifier::report_context(const LiveRange &LR, Register VRegUnit,
598                                      LaneBitmask LaneMask) const {
599   report_context_liverange(LR);
600   report_context_vreg_regunit(VRegUnit);
601   if (LaneMask.any())
602     report_context_lanemask(LaneMask);
603 }
604 
605 void MachineVerifier::report_context(const LiveRange::Segment &S) const {
606   errs() << "- segment:     " << S << '\n';
607 }
608 
609 void MachineVerifier::report_context(const VNInfo &VNI) const {
610   errs() << "- ValNo:       " << VNI.id << " (def " << VNI.def << ")\n";
611 }
612 
613 void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
614   errs() << "- liverange:   " << LR << '\n';
615 }
616 
617 void MachineVerifier::report_context(MCPhysReg PReg) const {
618   errs() << "- p. register: " << printReg(PReg, TRI) << '\n';
619 }
620 
621 void MachineVerifier::report_context_vreg(Register VReg) const {
622   errs() << "- v. register: " << printReg(VReg, TRI) << '\n';
623 }
624 
625 void MachineVerifier::report_context_vreg_regunit(Register VRegOrUnit) const {
626   if (VRegOrUnit.isVirtual()) {
627     report_context_vreg(VRegOrUnit);
628   } else {
629     errs() << "- regunit:     " << printRegUnit(VRegOrUnit, TRI) << '\n';
630   }
631 }
632 
633 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
634   errs() << "- lanemask:    " << PrintLaneMask(LaneMask) << '\n';
635 }
636 
637 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
638   BBInfo &MInfo = MBBInfoMap[MBB];
639   if (!MInfo.reachable) {
640     MInfo.reachable = true;
641     for (const MachineBasicBlock *Succ : MBB->successors())
642       markReachable(Succ);
643   }
644 }
645 
646 void MachineVerifier::visitMachineFunctionBefore() {
647   lastIndex = SlotIndex();
648   regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
649                                            : TRI->getReservedRegs(*MF);
650 
651   if (!MF->empty())
652     markReachable(&MF->front());
653 
654   // Build a set of the basic blocks in the function.
655   FunctionBlocks.clear();
656   for (const auto &MBB : *MF) {
657     FunctionBlocks.insert(&MBB);
658     BBInfo &MInfo = MBBInfoMap[&MBB];
659 
660     MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
661     if (MInfo.Preds.size() != MBB.pred_size())
662       report("MBB has duplicate entries in its predecessor list.", &MBB);
663 
664     MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
665     if (MInfo.Succs.size() != MBB.succ_size())
666       report("MBB has duplicate entries in its successor list.", &MBB);
667   }
668 
669   // Check that the register use lists are sane.
670   MRI->verifyUseLists();
671 
672   if (!MF->empty())
673     verifyStackFrame();
674 }
675 
676 void
677 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
678   FirstTerminator = nullptr;
679   FirstNonPHI = nullptr;
680 
681   if (!MF->getProperties().hasProperty(
682       MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) {
683     // If this block has allocatable physical registers live-in, check that
684     // it is an entry block or landing pad.
685     for (const auto &LI : MBB->liveins()) {
686       if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
687           MBB->getIterator() != MBB->getParent()->begin() &&
688           !MBB->isInlineAsmBrIndirectTarget()) {
689         report("MBB has allocatable live-in, but isn't entry, landing-pad, or "
690                "inlineasm-br-indirect-target.",
691                MBB);
692         report_context(LI.PhysReg);
693       }
694     }
695   }
696 
697   if (MBB->isIRBlockAddressTaken()) {
698     if (!MBB->getAddressTakenIRBlock()->hasAddressTaken())
699       report("ir-block-address-taken is associated with basic block not used by "
700              "a blockaddress.",
701              MBB);
702   }
703 
704   // Count the number of landing pad successors.
705   SmallPtrSet<const MachineBasicBlock*, 4> LandingPadSuccs;
706   for (const auto *succ : MBB->successors()) {
707     if (succ->isEHPad())
708       LandingPadSuccs.insert(succ);
709     if (!FunctionBlocks.count(succ))
710       report("MBB has successor that isn't part of the function.", MBB);
711     if (!MBBInfoMap[succ].Preds.count(MBB)) {
712       report("Inconsistent CFG", MBB);
713       errs() << "MBB is not in the predecessor list of the successor "
714              << printMBBReference(*succ) << ".\n";
715     }
716   }
717 
718   // Check the predecessor list.
719   for (const MachineBasicBlock *Pred : MBB->predecessors()) {
720     if (!FunctionBlocks.count(Pred))
721       report("MBB has predecessor that isn't part of the function.", MBB);
722     if (!MBBInfoMap[Pred].Succs.count(MBB)) {
723       report("Inconsistent CFG", MBB);
724       errs() << "MBB is not in the successor list of the predecessor "
725              << printMBBReference(*Pred) << ".\n";
726     }
727   }
728 
729   const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
730   const BasicBlock *BB = MBB->getBasicBlock();
731   const Function &F = MF->getFunction();
732   if (LandingPadSuccs.size() > 1 &&
733       !(AsmInfo &&
734         AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
735         BB && isa<SwitchInst>(BB->getTerminator())) &&
736       !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
737     report("MBB has more than one landing pad successor", MBB);
738 
739   // Call analyzeBranch. If it succeeds, there several more conditions to check.
740   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
741   SmallVector<MachineOperand, 4> Cond;
742   if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB,
743                           Cond)) {
744     // Ok, analyzeBranch thinks it knows what's going on with this block. Let's
745     // check whether its answers match up with reality.
746     if (!TBB && !FBB) {
747       // Block falls through to its successor.
748       if (!MBB->empty() && MBB->back().isBarrier() &&
749           !TII->isPredicated(MBB->back())) {
750         report("MBB exits via unconditional fall-through but ends with a "
751                "barrier instruction!", MBB);
752       }
753       if (!Cond.empty()) {
754         report("MBB exits via unconditional fall-through but has a condition!",
755                MBB);
756       }
757     } else if (TBB && !FBB && Cond.empty()) {
758       // Block unconditionally branches somewhere.
759       if (MBB->empty()) {
760         report("MBB exits via unconditional branch but doesn't contain "
761                "any instructions!", MBB);
762       } else if (!MBB->back().isBarrier()) {
763         report("MBB exits via unconditional branch but doesn't end with a "
764                "barrier instruction!", MBB);
765       } else if (!MBB->back().isTerminator()) {
766         report("MBB exits via unconditional branch but the branch isn't a "
767                "terminator instruction!", MBB);
768       }
769     } else if (TBB && !FBB && !Cond.empty()) {
770       // Block conditionally branches somewhere, otherwise falls through.
771       if (MBB->empty()) {
772         report("MBB exits via conditional branch/fall-through but doesn't "
773                "contain any instructions!", MBB);
774       } else if (MBB->back().isBarrier()) {
775         report("MBB exits via conditional branch/fall-through but ends with a "
776                "barrier instruction!", MBB);
777       } else if (!MBB->back().isTerminator()) {
778         report("MBB exits via conditional branch/fall-through but the branch "
779                "isn't a terminator instruction!", MBB);
780       }
781     } else if (TBB && FBB) {
782       // Block conditionally branches somewhere, otherwise branches
783       // somewhere else.
784       if (MBB->empty()) {
785         report("MBB exits via conditional branch/branch but doesn't "
786                "contain any instructions!", MBB);
787       } else if (!MBB->back().isBarrier()) {
788         report("MBB exits via conditional branch/branch but doesn't end with a "
789                "barrier instruction!", MBB);
790       } else if (!MBB->back().isTerminator()) {
791         report("MBB exits via conditional branch/branch but the branch "
792                "isn't a terminator instruction!", MBB);
793       }
794       if (Cond.empty()) {
795         report("MBB exits via conditional branch/branch but there's no "
796                "condition!", MBB);
797       }
798     } else {
799       report("analyzeBranch returned invalid data!", MBB);
800     }
801 
802     // Now check that the successors match up with the answers reported by
803     // analyzeBranch.
804     if (TBB && !MBB->isSuccessor(TBB))
805       report("MBB exits via jump or conditional branch, but its target isn't a "
806              "CFG successor!",
807              MBB);
808     if (FBB && !MBB->isSuccessor(FBB))
809       report("MBB exits via conditional branch, but its target isn't a CFG "
810              "successor!",
811              MBB);
812 
813     // There might be a fallthrough to the next block if there's either no
814     // unconditional true branch, or if there's a condition, and one of the
815     // branches is missing.
816     bool Fallthrough = !TBB || (!Cond.empty() && !FBB);
817 
818     // A conditional fallthrough must be an actual CFG successor, not
819     // unreachable. (Conversely, an unconditional fallthrough might not really
820     // be a successor, because the block might end in unreachable.)
821     if (!Cond.empty() && !FBB) {
822       MachineFunction::const_iterator MBBI = std::next(MBB->getIterator());
823       if (MBBI == MF->end()) {
824         report("MBB conditionally falls through out of function!", MBB);
825       } else if (!MBB->isSuccessor(&*MBBI))
826         report("MBB exits via conditional branch/fall-through but the CFG "
827                "successors don't match the actual successors!",
828                MBB);
829     }
830 
831     // Verify that there aren't any extra un-accounted-for successors.
832     for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
833       // If this successor is one of the branch targets, it's okay.
834       if (SuccMBB == TBB || SuccMBB == FBB)
835         continue;
836       // If we might have a fallthrough, and the successor is the fallthrough
837       // block, that's also ok.
838       if (Fallthrough && SuccMBB == MBB->getNextNode())
839         continue;
840       // Also accept successors which are for exception-handling or might be
841       // inlineasm_br targets.
842       if (SuccMBB->isEHPad() || SuccMBB->isInlineAsmBrIndirectTarget())
843         continue;
844       report("MBB has unexpected successors which are not branch targets, "
845              "fallthrough, EHPads, or inlineasm_br targets.",
846              MBB);
847     }
848   }
849 
850   regsLive.clear();
851   if (MRI->tracksLiveness()) {
852     for (const auto &LI : MBB->liveins()) {
853       if (!Register::isPhysicalRegister(LI.PhysReg)) {
854         report("MBB live-in list contains non-physical register", MBB);
855         continue;
856       }
857       for (const MCPhysReg &SubReg : TRI->subregs_inclusive(LI.PhysReg))
858         regsLive.insert(SubReg);
859     }
860   }
861 
862   const MachineFrameInfo &MFI = MF->getFrameInfo();
863   BitVector PR = MFI.getPristineRegs(*MF);
864   for (unsigned I : PR.set_bits()) {
865     for (const MCPhysReg &SubReg : TRI->subregs_inclusive(I))
866       regsLive.insert(SubReg);
867   }
868 
869   regsKilled.clear();
870   regsDefined.clear();
871 
872   if (Indexes)
873     lastIndex = Indexes->getMBBStartIdx(MBB);
874 }
875 
876 // This function gets called for all bundle headers, including normal
877 // stand-alone unbundled instructions.
878 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
879   if (Indexes && Indexes->hasIndex(*MI)) {
880     SlotIndex idx = Indexes->getInstructionIndex(*MI);
881     if (!(idx > lastIndex)) {
882       report("Instruction index out of order", MI);
883       errs() << "Last instruction was at " << lastIndex << '\n';
884     }
885     lastIndex = idx;
886   }
887 
888   // Ensure non-terminators don't follow terminators.
889   if (MI->isTerminator()) {
890     if (!FirstTerminator)
891       FirstTerminator = MI;
892   } else if (FirstTerminator) {
893     // For GlobalISel, G_INVOKE_REGION_START is a terminator that we allow to
894     // precede non-terminators.
895     if (FirstTerminator->getOpcode() != TargetOpcode::G_INVOKE_REGION_START) {
896       report("Non-terminator instruction after the first terminator", MI);
897       errs() << "First terminator was:\t" << *FirstTerminator;
898     }
899   }
900 }
901 
902 // The operands on an INLINEASM instruction must follow a template.
903 // Verify that the flag operands make sense.
904 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
905   // The first two operands on INLINEASM are the asm string and global flags.
906   if (MI->getNumOperands() < 2) {
907     report("Too few operands on inline asm", MI);
908     return;
909   }
910   if (!MI->getOperand(0).isSymbol())
911     report("Asm string must be an external symbol", MI);
912   if (!MI->getOperand(1).isImm())
913     report("Asm flags must be an immediate", MI);
914   // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
915   // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
916   // and Extra_IsConvergent = 32.
917   if (!isUInt<6>(MI->getOperand(1).getImm()))
918     report("Unknown asm flags", &MI->getOperand(1), 1);
919 
920   static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
921 
922   unsigned OpNo = InlineAsm::MIOp_FirstOperand;
923   unsigned NumOps;
924   for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
925     const MachineOperand &MO = MI->getOperand(OpNo);
926     // There may be implicit ops after the fixed operands.
927     if (!MO.isImm())
928       break;
929     const InlineAsm::Flag F(MO.getImm());
930     NumOps = 1 + F.getNumOperandRegisters();
931   }
932 
933   if (OpNo > MI->getNumOperands())
934     report("Missing operands in last group", MI);
935 
936   // An optional MDNode follows the groups.
937   if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
938     ++OpNo;
939 
940   // All trailing operands must be implicit registers.
941   for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
942     const MachineOperand &MO = MI->getOperand(OpNo);
943     if (!MO.isReg() || !MO.isImplicit())
944       report("Expected implicit register after groups", &MO, OpNo);
945   }
946 
947   if (MI->getOpcode() == TargetOpcode::INLINEASM_BR) {
948     const MachineBasicBlock *MBB = MI->getParent();
949 
950     for (unsigned i = InlineAsm::MIOp_FirstOperand, e = MI->getNumOperands();
951          i != e; ++i) {
952       const MachineOperand &MO = MI->getOperand(i);
953 
954       if (!MO.isMBB())
955         continue;
956 
957       // Check the successor & predecessor lists look ok, assume they are
958       // not. Find the indirect target without going through the successors.
959       const MachineBasicBlock *IndirectTargetMBB = MO.getMBB();
960       if (!IndirectTargetMBB) {
961         report("INLINEASM_BR indirect target does not exist", &MO, i);
962         break;
963       }
964 
965       if (!MBB->isSuccessor(IndirectTargetMBB))
966         report("INLINEASM_BR indirect target missing from successor list", &MO,
967                i);
968 
969       if (!IndirectTargetMBB->isPredecessor(MBB))
970         report("INLINEASM_BR indirect target predecessor list missing parent",
971                &MO, i);
972     }
973   }
974 }
975 
976 bool MachineVerifier::verifyAllRegOpsScalar(const MachineInstr &MI,
977                                             const MachineRegisterInfo &MRI) {
978   if (none_of(MI.explicit_operands(), [&MRI](const MachineOperand &Op) {
979         if (!Op.isReg())
980           return false;
981         const auto Reg = Op.getReg();
982         if (Reg.isPhysical())
983           return false;
984         return !MRI.getType(Reg).isScalar();
985       }))
986     return true;
987   report("All register operands must have scalar types", &MI);
988   return false;
989 }
990 
991 /// Check that types are consistent when two operands need to have the same
992 /// number of vector elements.
993 /// \return true if the types are valid.
994 bool MachineVerifier::verifyVectorElementMatch(LLT Ty0, LLT Ty1,
995                                                const MachineInstr *MI) {
996   if (Ty0.isVector() != Ty1.isVector()) {
997     report("operand types must be all-vector or all-scalar", MI);
998     // Generally we try to report as many issues as possible at once, but in
999     // this case it's not clear what should we be comparing the size of the
1000     // scalar with: the size of the whole vector or its lane. Instead of
1001     // making an arbitrary choice and emitting not so helpful message, let's
1002     // avoid the extra noise and stop here.
1003     return false;
1004   }
1005 
1006   if (Ty0.isVector() && Ty0.getElementCount() != Ty1.getElementCount()) {
1007     report("operand types must preserve number of vector elements", MI);
1008     return false;
1009   }
1010 
1011   return true;
1012 }
1013 
1014 bool MachineVerifier::verifyGIntrinsicSideEffects(const MachineInstr *MI) {
1015   auto Opcode = MI->getOpcode();
1016   bool NoSideEffects = Opcode == TargetOpcode::G_INTRINSIC ||
1017                        Opcode == TargetOpcode::G_INTRINSIC_CONVERGENT;
1018   unsigned IntrID = cast<GIntrinsic>(MI)->getIntrinsicID();
1019   if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
1020     AttributeList Attrs = Intrinsic::getAttributes(
1021         MF->getFunction().getContext(), static_cast<Intrinsic::ID>(IntrID));
1022     bool DeclHasSideEffects = !Attrs.getMemoryEffects().doesNotAccessMemory();
1023     if (NoSideEffects && DeclHasSideEffects) {
1024       report(Twine(TII->getName(Opcode),
1025                    " used with intrinsic that accesses memory"),
1026              MI);
1027       return false;
1028     }
1029     if (!NoSideEffects && !DeclHasSideEffects) {
1030       report(Twine(TII->getName(Opcode), " used with readnone intrinsic"), MI);
1031       return false;
1032     }
1033   }
1034 
1035   return true;
1036 }
1037 
1038 bool MachineVerifier::verifyGIntrinsicConvergence(const MachineInstr *MI) {
1039   auto Opcode = MI->getOpcode();
1040   bool NotConvergent = Opcode == TargetOpcode::G_INTRINSIC ||
1041                        Opcode == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS;
1042   unsigned IntrID = cast<GIntrinsic>(MI)->getIntrinsicID();
1043   if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
1044     AttributeList Attrs = Intrinsic::getAttributes(
1045         MF->getFunction().getContext(), static_cast<Intrinsic::ID>(IntrID));
1046     bool DeclIsConvergent = Attrs.hasFnAttr(Attribute::Convergent);
1047     if (NotConvergent && DeclIsConvergent) {
1048       report(Twine(TII->getName(Opcode), " used with a convergent intrinsic"),
1049              MI);
1050       return false;
1051     }
1052     if (!NotConvergent && !DeclIsConvergent) {
1053       report(
1054           Twine(TII->getName(Opcode), " used with a non-convergent intrinsic"),
1055           MI);
1056       return false;
1057     }
1058   }
1059 
1060   return true;
1061 }
1062 
1063 void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr *MI) {
1064   if (isFunctionSelected)
1065     report("Unexpected generic instruction in a Selected function", MI);
1066 
1067   const MCInstrDesc &MCID = MI->getDesc();
1068   unsigned NumOps = MI->getNumOperands();
1069 
1070   // Branches must reference a basic block if they are not indirect
1071   if (MI->isBranch() && !MI->isIndirectBranch()) {
1072     bool HasMBB = false;
1073     for (const MachineOperand &Op : MI->operands()) {
1074       if (Op.isMBB()) {
1075         HasMBB = true;
1076         break;
1077       }
1078     }
1079 
1080     if (!HasMBB) {
1081       report("Branch instruction is missing a basic block operand or "
1082              "isIndirectBranch property",
1083              MI);
1084     }
1085   }
1086 
1087   // Check types.
1088   SmallVector<LLT, 4> Types;
1089   for (unsigned I = 0, E = std::min(MCID.getNumOperands(), NumOps);
1090        I != E; ++I) {
1091     if (!MCID.operands()[I].isGenericType())
1092       continue;
1093     // Generic instructions specify type equality constraints between some of
1094     // their operands. Make sure these are consistent.
1095     size_t TypeIdx = MCID.operands()[I].getGenericTypeIndex();
1096     Types.resize(std::max(TypeIdx + 1, Types.size()));
1097 
1098     const MachineOperand *MO = &MI->getOperand(I);
1099     if (!MO->isReg()) {
1100       report("generic instruction must use register operands", MI);
1101       continue;
1102     }
1103 
1104     LLT OpTy = MRI->getType(MO->getReg());
1105     // Don't report a type mismatch if there is no actual mismatch, only a
1106     // type missing, to reduce noise:
1107     if (OpTy.isValid()) {
1108       // Only the first valid type for a type index will be printed: don't
1109       // overwrite it later so it's always clear which type was expected:
1110       if (!Types[TypeIdx].isValid())
1111         Types[TypeIdx] = OpTy;
1112       else if (Types[TypeIdx] != OpTy)
1113         report("Type mismatch in generic instruction", MO, I, OpTy);
1114     } else {
1115       // Generic instructions must have types attached to their operands.
1116       report("Generic instruction is missing a virtual register type", MO, I);
1117     }
1118   }
1119 
1120   // Generic opcodes must not have physical register operands.
1121   for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
1122     const MachineOperand *MO = &MI->getOperand(I);
1123     if (MO->isReg() && MO->getReg().isPhysical())
1124       report("Generic instruction cannot have physical register", MO, I);
1125   }
1126 
1127   // Avoid out of bounds in checks below. This was already reported earlier.
1128   if (MI->getNumOperands() < MCID.getNumOperands())
1129     return;
1130 
1131   StringRef ErrorInfo;
1132   if (!TII->verifyInstruction(*MI, ErrorInfo))
1133     report(ErrorInfo.data(), MI);
1134 
1135   // Verify properties of various specific instruction types
1136   unsigned Opc = MI->getOpcode();
1137   switch (Opc) {
1138   case TargetOpcode::G_ASSERT_SEXT:
1139   case TargetOpcode::G_ASSERT_ZEXT: {
1140     std::string OpcName =
1141         Opc == TargetOpcode::G_ASSERT_ZEXT ? "G_ASSERT_ZEXT" : "G_ASSERT_SEXT";
1142     if (!MI->getOperand(2).isImm()) {
1143       report(Twine(OpcName, " expects an immediate operand #2"), MI);
1144       break;
1145     }
1146 
1147     Register Dst = MI->getOperand(0).getReg();
1148     Register Src = MI->getOperand(1).getReg();
1149     LLT SrcTy = MRI->getType(Src);
1150     int64_t Imm = MI->getOperand(2).getImm();
1151     if (Imm <= 0) {
1152       report(Twine(OpcName, " size must be >= 1"), MI);
1153       break;
1154     }
1155 
1156     if (Imm >= SrcTy.getScalarSizeInBits()) {
1157       report(Twine(OpcName, " size must be less than source bit width"), MI);
1158       break;
1159     }
1160 
1161     const RegisterBank *SrcRB = RBI->getRegBank(Src, *MRI, *TRI);
1162     const RegisterBank *DstRB = RBI->getRegBank(Dst, *MRI, *TRI);
1163 
1164     // Allow only the source bank to be set.
1165     if ((SrcRB && DstRB && SrcRB != DstRB) || (DstRB && !SrcRB)) {
1166       report(Twine(OpcName, " cannot change register bank"), MI);
1167       break;
1168     }
1169 
1170     // Don't allow a class change. Do allow member class->regbank.
1171     const TargetRegisterClass *DstRC = MRI->getRegClassOrNull(Dst);
1172     if (DstRC && DstRC != MRI->getRegClassOrNull(Src)) {
1173       report(
1174           Twine(OpcName, " source and destination register classes must match"),
1175           MI);
1176       break;
1177     }
1178 
1179     break;
1180   }
1181 
1182   case TargetOpcode::G_CONSTANT:
1183   case TargetOpcode::G_FCONSTANT: {
1184     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1185     if (DstTy.isVector())
1186       report("Instruction cannot use a vector result type", MI);
1187 
1188     if (MI->getOpcode() == TargetOpcode::G_CONSTANT) {
1189       if (!MI->getOperand(1).isCImm()) {
1190         report("G_CONSTANT operand must be cimm", MI);
1191         break;
1192       }
1193 
1194       const ConstantInt *CI = MI->getOperand(1).getCImm();
1195       if (CI->getBitWidth() != DstTy.getSizeInBits())
1196         report("inconsistent constant size", MI);
1197     } else {
1198       if (!MI->getOperand(1).isFPImm()) {
1199         report("G_FCONSTANT operand must be fpimm", MI);
1200         break;
1201       }
1202       const ConstantFP *CF = MI->getOperand(1).getFPImm();
1203 
1204       if (APFloat::getSizeInBits(CF->getValueAPF().getSemantics()) !=
1205           DstTy.getSizeInBits()) {
1206         report("inconsistent constant size", MI);
1207       }
1208     }
1209 
1210     break;
1211   }
1212   case TargetOpcode::G_LOAD:
1213   case TargetOpcode::G_STORE:
1214   case TargetOpcode::G_ZEXTLOAD:
1215   case TargetOpcode::G_SEXTLOAD: {
1216     LLT ValTy = MRI->getType(MI->getOperand(0).getReg());
1217     LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
1218     if (!PtrTy.isPointer())
1219       report("Generic memory instruction must access a pointer", MI);
1220 
1221     // Generic loads and stores must have a single MachineMemOperand
1222     // describing that access.
1223     if (!MI->hasOneMemOperand()) {
1224       report("Generic instruction accessing memory must have one mem operand",
1225              MI);
1226     } else {
1227       const MachineMemOperand &MMO = **MI->memoperands_begin();
1228       if (MI->getOpcode() == TargetOpcode::G_ZEXTLOAD ||
1229           MI->getOpcode() == TargetOpcode::G_SEXTLOAD) {
1230         if (TypeSize::isKnownGE(MMO.getSizeInBits().getValue(),
1231                                 ValTy.getSizeInBits()))
1232           report("Generic extload must have a narrower memory type", MI);
1233       } else if (MI->getOpcode() == TargetOpcode::G_LOAD) {
1234         if (TypeSize::isKnownGT(MMO.getSize().getValue(),
1235                                 ValTy.getSizeInBytes()))
1236           report("load memory size cannot exceed result size", MI);
1237       } else if (MI->getOpcode() == TargetOpcode::G_STORE) {
1238         if (TypeSize::isKnownLT(ValTy.getSizeInBytes(),
1239                                 MMO.getSize().getValue()))
1240           report("store memory size cannot exceed value size", MI);
1241       }
1242 
1243       const AtomicOrdering Order = MMO.getSuccessOrdering();
1244       if (Opc == TargetOpcode::G_STORE) {
1245         if (Order == AtomicOrdering::Acquire ||
1246             Order == AtomicOrdering::AcquireRelease)
1247           report("atomic store cannot use acquire ordering", MI);
1248 
1249       } else {
1250         if (Order == AtomicOrdering::Release ||
1251             Order == AtomicOrdering::AcquireRelease)
1252           report("atomic load cannot use release ordering", MI);
1253       }
1254     }
1255 
1256     break;
1257   }
1258   case TargetOpcode::G_PHI: {
1259     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1260     if (!DstTy.isValid() || !all_of(drop_begin(MI->operands()),
1261                                     [this, &DstTy](const MachineOperand &MO) {
1262                                       if (!MO.isReg())
1263                                         return true;
1264                                       LLT Ty = MRI->getType(MO.getReg());
1265                                       if (!Ty.isValid() || (Ty != DstTy))
1266                                         return false;
1267                                       return true;
1268                                     }))
1269       report("Generic Instruction G_PHI has operands with incompatible/missing "
1270              "types",
1271              MI);
1272     break;
1273   }
1274   case TargetOpcode::G_BITCAST: {
1275     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1276     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1277     if (!DstTy.isValid() || !SrcTy.isValid())
1278       break;
1279 
1280     if (SrcTy.isPointer() != DstTy.isPointer())
1281       report("bitcast cannot convert between pointers and other types", MI);
1282 
1283     if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
1284       report("bitcast sizes must match", MI);
1285 
1286     if (SrcTy == DstTy)
1287       report("bitcast must change the type", MI);
1288 
1289     break;
1290   }
1291   case TargetOpcode::G_INTTOPTR:
1292   case TargetOpcode::G_PTRTOINT:
1293   case TargetOpcode::G_ADDRSPACE_CAST: {
1294     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1295     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1296     if (!DstTy.isValid() || !SrcTy.isValid())
1297       break;
1298 
1299     verifyVectorElementMatch(DstTy, SrcTy, MI);
1300 
1301     DstTy = DstTy.getScalarType();
1302     SrcTy = SrcTy.getScalarType();
1303 
1304     if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) {
1305       if (!DstTy.isPointer())
1306         report("inttoptr result type must be a pointer", MI);
1307       if (SrcTy.isPointer())
1308         report("inttoptr source type must not be a pointer", MI);
1309     } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) {
1310       if (!SrcTy.isPointer())
1311         report("ptrtoint source type must be a pointer", MI);
1312       if (DstTy.isPointer())
1313         report("ptrtoint result type must not be a pointer", MI);
1314     } else {
1315       assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST);
1316       if (!SrcTy.isPointer() || !DstTy.isPointer())
1317         report("addrspacecast types must be pointers", MI);
1318       else {
1319         if (SrcTy.getAddressSpace() == DstTy.getAddressSpace())
1320           report("addrspacecast must convert different address spaces", MI);
1321       }
1322     }
1323 
1324     break;
1325   }
1326   case TargetOpcode::G_PTR_ADD: {
1327     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1328     LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
1329     LLT OffsetTy = MRI->getType(MI->getOperand(2).getReg());
1330     if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid())
1331       break;
1332 
1333     if (!PtrTy.isPointerOrPointerVector())
1334       report("gep first operand must be a pointer", MI);
1335 
1336     if (OffsetTy.isPointerOrPointerVector())
1337       report("gep offset operand must not be a pointer", MI);
1338 
1339     if (PtrTy.isPointerOrPointerVector()) {
1340       const DataLayout &DL = MF->getDataLayout();
1341       unsigned AS = PtrTy.getAddressSpace();
1342       unsigned IndexSizeInBits = DL.getIndexSize(AS) * 8;
1343       if (OffsetTy.getScalarSizeInBits() != IndexSizeInBits) {
1344         report("gep offset operand must match index size for address space",
1345                MI);
1346       }
1347     }
1348 
1349     // TODO: Is the offset allowed to be a scalar with a vector?
1350     break;
1351   }
1352   case TargetOpcode::G_PTRMASK: {
1353     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1354     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1355     LLT MaskTy = MRI->getType(MI->getOperand(2).getReg());
1356     if (!DstTy.isValid() || !SrcTy.isValid() || !MaskTy.isValid())
1357       break;
1358 
1359     if (!DstTy.isPointerOrPointerVector())
1360       report("ptrmask result type must be a pointer", MI);
1361 
1362     if (!MaskTy.getScalarType().isScalar())
1363       report("ptrmask mask type must be an integer", MI);
1364 
1365     verifyVectorElementMatch(DstTy, MaskTy, MI);
1366     break;
1367   }
1368   case TargetOpcode::G_SEXT:
1369   case TargetOpcode::G_ZEXT:
1370   case TargetOpcode::G_ANYEXT:
1371   case TargetOpcode::G_TRUNC:
1372   case TargetOpcode::G_FPEXT:
1373   case TargetOpcode::G_FPTRUNC: {
1374     // Number of operands and presense of types is already checked (and
1375     // reported in case of any issues), so no need to report them again. As
1376     // we're trying to report as many issues as possible at once, however, the
1377     // instructions aren't guaranteed to have the right number of operands or
1378     // types attached to them at this point
1379     assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1380     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1381     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1382     if (!DstTy.isValid() || !SrcTy.isValid())
1383       break;
1384 
1385     if (DstTy.isPointerOrPointerVector() || SrcTy.isPointerOrPointerVector())
1386       report("Generic extend/truncate can not operate on pointers", MI);
1387 
1388     verifyVectorElementMatch(DstTy, SrcTy, MI);
1389 
1390     unsigned DstSize = DstTy.getScalarSizeInBits();
1391     unsigned SrcSize = SrcTy.getScalarSizeInBits();
1392     switch (MI->getOpcode()) {
1393     default:
1394       if (DstSize <= SrcSize)
1395         report("Generic extend has destination type no larger than source", MI);
1396       break;
1397     case TargetOpcode::G_TRUNC:
1398     case TargetOpcode::G_FPTRUNC:
1399       if (DstSize >= SrcSize)
1400         report("Generic truncate has destination type no smaller than source",
1401                MI);
1402       break;
1403     }
1404     break;
1405   }
1406   case TargetOpcode::G_SELECT: {
1407     LLT SelTy = MRI->getType(MI->getOperand(0).getReg());
1408     LLT CondTy = MRI->getType(MI->getOperand(1).getReg());
1409     if (!SelTy.isValid() || !CondTy.isValid())
1410       break;
1411 
1412     // Scalar condition select on a vector is valid.
1413     if (CondTy.isVector())
1414       verifyVectorElementMatch(SelTy, CondTy, MI);
1415     break;
1416   }
1417   case TargetOpcode::G_MERGE_VALUES: {
1418     // G_MERGE_VALUES should only be used to merge scalars into a larger scalar,
1419     // e.g. s2N = MERGE sN, sN
1420     // Merging multiple scalars into a vector is not allowed, should use
1421     // G_BUILD_VECTOR for that.
1422     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1423     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1424     if (DstTy.isVector() || SrcTy.isVector())
1425       report("G_MERGE_VALUES cannot operate on vectors", MI);
1426 
1427     const unsigned NumOps = MI->getNumOperands();
1428     if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1))
1429       report("G_MERGE_VALUES result size is inconsistent", MI);
1430 
1431     for (unsigned I = 2; I != NumOps; ++I) {
1432       if (MRI->getType(MI->getOperand(I).getReg()) != SrcTy)
1433         report("G_MERGE_VALUES source types do not match", MI);
1434     }
1435 
1436     break;
1437   }
1438   case TargetOpcode::G_UNMERGE_VALUES: {
1439     unsigned NumDsts = MI->getNumOperands() - 1;
1440     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1441     for (unsigned i = 1; i < NumDsts; ++i) {
1442       if (MRI->getType(MI->getOperand(i).getReg()) != DstTy) {
1443         report("G_UNMERGE_VALUES destination types do not match", MI);
1444         break;
1445       }
1446     }
1447 
1448     LLT SrcTy = MRI->getType(MI->getOperand(NumDsts).getReg());
1449     if (DstTy.isVector()) {
1450       // This case is the converse of G_CONCAT_VECTORS.
1451       if (!SrcTy.isVector() || SrcTy.getScalarType() != DstTy.getScalarType() ||
1452           SrcTy.isScalableVector() != DstTy.isScalableVector() ||
1453           SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1454         report("G_UNMERGE_VALUES source operand does not match vector "
1455                "destination operands",
1456                MI);
1457     } else if (SrcTy.isVector()) {
1458       // This case is the converse of G_BUILD_VECTOR, but relaxed to allow
1459       // mismatched types as long as the total size matches:
1460       //   %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<4 x s32>)
1461       if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1462         report("G_UNMERGE_VALUES vector source operand does not match scalar "
1463                "destination operands",
1464                MI);
1465     } else {
1466       // This case is the converse of G_MERGE_VALUES.
1467       if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits()) {
1468         report("G_UNMERGE_VALUES scalar source operand does not match scalar "
1469                "destination operands",
1470                MI);
1471       }
1472     }
1473     break;
1474   }
1475   case TargetOpcode::G_BUILD_VECTOR: {
1476     // Source types must be scalars, dest type a vector. Total size of scalars
1477     // must match the dest vector size.
1478     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1479     LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1480     if (!DstTy.isVector() || SrcEltTy.isVector()) {
1481       report("G_BUILD_VECTOR must produce a vector from scalar operands", MI);
1482       break;
1483     }
1484 
1485     if (DstTy.getElementType() != SrcEltTy)
1486       report("G_BUILD_VECTOR result element type must match source type", MI);
1487 
1488     if (DstTy.getNumElements() != MI->getNumOperands() - 1)
1489       report("G_BUILD_VECTOR must have an operand for each elemement", MI);
1490 
1491     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1492       if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1493         report("G_BUILD_VECTOR source operand types are not homogeneous", MI);
1494 
1495     break;
1496   }
1497   case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1498     // Source types must be scalars, dest type a vector. Scalar types must be
1499     // larger than the dest vector elt type, as this is a truncating operation.
1500     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1501     LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1502     if (!DstTy.isVector() || SrcEltTy.isVector())
1503       report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
1504              MI);
1505     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1506       if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1507         report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
1508                MI);
1509     if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits())
1510       report("G_BUILD_VECTOR_TRUNC source operand types are not larger than "
1511              "dest elt type",
1512              MI);
1513     break;
1514   }
1515   case TargetOpcode::G_CONCAT_VECTORS: {
1516     // Source types should be vectors, and total size should match the dest
1517     // vector size.
1518     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1519     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1520     if (!DstTy.isVector() || !SrcTy.isVector())
1521       report("G_CONCAT_VECTOR requires vector source and destination operands",
1522              MI);
1523 
1524     if (MI->getNumOperands() < 3)
1525       report("G_CONCAT_VECTOR requires at least 2 source operands", MI);
1526 
1527     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1528       if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1529         report("G_CONCAT_VECTOR source operand types are not homogeneous", MI);
1530     if (DstTy.getElementCount() !=
1531         SrcTy.getElementCount() * (MI->getNumOperands() - 1))
1532       report("G_CONCAT_VECTOR num dest and source elements should match", MI);
1533     break;
1534   }
1535   case TargetOpcode::G_ICMP:
1536   case TargetOpcode::G_FCMP: {
1537     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1538     LLT SrcTy = MRI->getType(MI->getOperand(2).getReg());
1539 
1540     if ((DstTy.isVector() != SrcTy.isVector()) ||
1541         (DstTy.isVector() &&
1542          DstTy.getElementCount() != SrcTy.getElementCount()))
1543       report("Generic vector icmp/fcmp must preserve number of lanes", MI);
1544 
1545     break;
1546   }
1547   case TargetOpcode::G_SCMP:
1548   case TargetOpcode::G_UCMP: {
1549     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1550     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1551     LLT SrcTy2 = MRI->getType(MI->getOperand(2).getReg());
1552 
1553     if (SrcTy.isPointerOrPointerVector() || SrcTy2.isPointerOrPointerVector()) {
1554       report("Generic scmp/ucmp does not support pointers as operands", MI);
1555       break;
1556     }
1557 
1558     if (DstTy.isPointerOrPointerVector()) {
1559       report("Generic scmp/ucmp does not support pointers as a result", MI);
1560       break;
1561     }
1562 
1563     if ((DstTy.isVector() != SrcTy.isVector()) ||
1564         (DstTy.isVector() &&
1565          DstTy.getElementCount() != SrcTy.getElementCount())) {
1566       report("Generic vector scmp/ucmp must preserve number of lanes", MI);
1567       break;
1568     }
1569 
1570     if (SrcTy != SrcTy2) {
1571       report("Generic scmp/ucmp must have same input types", MI);
1572       break;
1573     }
1574 
1575     break;
1576   }
1577   case TargetOpcode::G_EXTRACT: {
1578     const MachineOperand &SrcOp = MI->getOperand(1);
1579     if (!SrcOp.isReg()) {
1580       report("extract source must be a register", MI);
1581       break;
1582     }
1583 
1584     const MachineOperand &OffsetOp = MI->getOperand(2);
1585     if (!OffsetOp.isImm()) {
1586       report("extract offset must be a constant", MI);
1587       break;
1588     }
1589 
1590     unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1591     unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1592     if (SrcSize == DstSize)
1593       report("extract source must be larger than result", MI);
1594 
1595     if (DstSize + OffsetOp.getImm() > SrcSize)
1596       report("extract reads past end of register", MI);
1597     break;
1598   }
1599   case TargetOpcode::G_INSERT: {
1600     const MachineOperand &SrcOp = MI->getOperand(2);
1601     if (!SrcOp.isReg()) {
1602       report("insert source must be a register", MI);
1603       break;
1604     }
1605 
1606     const MachineOperand &OffsetOp = MI->getOperand(3);
1607     if (!OffsetOp.isImm()) {
1608       report("insert offset must be a constant", MI);
1609       break;
1610     }
1611 
1612     unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1613     unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1614 
1615     if (DstSize <= SrcSize)
1616       report("inserted size must be smaller than total register", MI);
1617 
1618     if (SrcSize + OffsetOp.getImm() > DstSize)
1619       report("insert writes past end of register", MI);
1620 
1621     break;
1622   }
1623   case TargetOpcode::G_JUMP_TABLE: {
1624     if (!MI->getOperand(1).isJTI())
1625       report("G_JUMP_TABLE source operand must be a jump table index", MI);
1626     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1627     if (!DstTy.isPointer())
1628       report("G_JUMP_TABLE dest operand must have a pointer type", MI);
1629     break;
1630   }
1631   case TargetOpcode::G_BRJT: {
1632     if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
1633       report("G_BRJT src operand 0 must be a pointer type", MI);
1634 
1635     if (!MI->getOperand(1).isJTI())
1636       report("G_BRJT src operand 1 must be a jump table index", MI);
1637 
1638     const auto &IdxOp = MI->getOperand(2);
1639     if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer())
1640       report("G_BRJT src operand 2 must be a scalar reg type", MI);
1641     break;
1642   }
1643   case TargetOpcode::G_INTRINSIC:
1644   case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
1645   case TargetOpcode::G_INTRINSIC_CONVERGENT:
1646   case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS: {
1647     // TODO: Should verify number of def and use operands, but the current
1648     // interface requires passing in IR types for mangling.
1649     const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs());
1650     if (!IntrIDOp.isIntrinsicID()) {
1651       report("G_INTRINSIC first src operand must be an intrinsic ID", MI);
1652       break;
1653     }
1654 
1655     if (!verifyGIntrinsicSideEffects(MI))
1656       break;
1657     if (!verifyGIntrinsicConvergence(MI))
1658       break;
1659 
1660     break;
1661   }
1662   case TargetOpcode::G_SEXT_INREG: {
1663     if (!MI->getOperand(2).isImm()) {
1664       report("G_SEXT_INREG expects an immediate operand #2", MI);
1665       break;
1666     }
1667 
1668     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1669     int64_t Imm = MI->getOperand(2).getImm();
1670     if (Imm <= 0)
1671       report("G_SEXT_INREG size must be >= 1", MI);
1672     if (Imm >= SrcTy.getScalarSizeInBits())
1673       report("G_SEXT_INREG size must be less than source bit width", MI);
1674     break;
1675   }
1676   case TargetOpcode::G_BSWAP: {
1677     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1678     if (DstTy.getScalarSizeInBits() % 16 != 0)
1679       report("G_BSWAP size must be a multiple of 16 bits", MI);
1680     break;
1681   }
1682   case TargetOpcode::G_VSCALE: {
1683     if (!MI->getOperand(1).isCImm()) {
1684       report("G_VSCALE operand must be cimm", MI);
1685       break;
1686     }
1687     if (MI->getOperand(1).getCImm()->isZero()) {
1688       report("G_VSCALE immediate cannot be zero", MI);
1689       break;
1690     }
1691     break;
1692   }
1693   case TargetOpcode::G_INSERT_SUBVECTOR: {
1694     const MachineOperand &Src0Op = MI->getOperand(1);
1695     if (!Src0Op.isReg()) {
1696       report("G_INSERT_SUBVECTOR first source must be a register", MI);
1697       break;
1698     }
1699 
1700     const MachineOperand &Src1Op = MI->getOperand(2);
1701     if (!Src1Op.isReg()) {
1702       report("G_INSERT_SUBVECTOR second source must be a register", MI);
1703       break;
1704     }
1705 
1706     const MachineOperand &IndexOp = MI->getOperand(3);
1707     if (!IndexOp.isImm()) {
1708       report("G_INSERT_SUBVECTOR index must be an immediate", MI);
1709       break;
1710     }
1711 
1712     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1713     LLT Src0Ty = MRI->getType(Src0Op.getReg());
1714     LLT Src1Ty = MRI->getType(Src1Op.getReg());
1715 
1716     if (!DstTy.isVector()) {
1717       report("Destination type must be a vector", MI);
1718       break;
1719     }
1720 
1721     if (!Src0Ty.isVector()) {
1722       report("First source must be a vector", MI);
1723       break;
1724     }
1725 
1726     if (!Src1Ty.isVector()) {
1727       report("Second source must be a vector", MI);
1728       break;
1729     }
1730 
1731     if (DstTy != Src0Ty) {
1732       report("Destination type must match the first source vector type", MI);
1733       break;
1734     }
1735 
1736     if (Src0Ty.getElementType() != Src1Ty.getElementType()) {
1737       report("Element type of source vectors must be the same", MI);
1738       break;
1739     }
1740 
1741     if (IndexOp.getImm() != 0 &&
1742         IndexOp.getImm() % Src1Ty.getElementCount().getKnownMinValue() != 0) {
1743       report("Index must be a multiple of the second source vector's "
1744              "minimum vector length",
1745              MI);
1746       break;
1747     }
1748     break;
1749   }
1750   case TargetOpcode::G_EXTRACT_SUBVECTOR: {
1751     const MachineOperand &SrcOp = MI->getOperand(1);
1752     if (!SrcOp.isReg()) {
1753       report("G_EXTRACT_SUBVECTOR first source must be a register", MI);
1754       break;
1755     }
1756 
1757     const MachineOperand &IndexOp = MI->getOperand(2);
1758     if (!IndexOp.isImm()) {
1759       report("G_EXTRACT_SUBVECTOR index must be an immediate", MI);
1760       break;
1761     }
1762 
1763     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1764     LLT SrcTy = MRI->getType(SrcOp.getReg());
1765 
1766     if (!DstTy.isVector()) {
1767       report("Destination type must be a vector", MI);
1768       break;
1769     }
1770 
1771     if (!SrcTy.isVector()) {
1772       report("Source must be a vector", MI);
1773       break;
1774     }
1775 
1776     if (DstTy.getElementType() != SrcTy.getElementType()) {
1777       report("Element type of vectors must be the same", MI);
1778       break;
1779     }
1780 
1781     if (SrcTy.isScalable() != DstTy.isScalable()) {
1782       report("Vector types must both be fixed or both be scalable", MI);
1783       break;
1784     }
1785 
1786     if (ElementCount::isKnownGT(DstTy.getElementCount(),
1787                                 SrcTy.getElementCount())) {
1788       report("Destination vector must be smaller than source vector", MI);
1789       break;
1790     }
1791 
1792     uint64_t Idx = IndexOp.getImm();
1793     uint64_t DstMinLen = DstTy.getElementCount().getKnownMinValue();
1794     if (Idx % DstMinLen != 0) {
1795       report("Index must be a multiple of the destination vector's minimum "
1796              "vector length",
1797              MI);
1798       break;
1799     }
1800 
1801     uint64_t SrcMinLen = SrcTy.getElementCount().getKnownMinValue();
1802     if (Idx >= SrcMinLen || Idx + DstMinLen > SrcMinLen) {
1803       report("Destination type and index must not cause extract to overrun the "
1804              "source vector",
1805              MI);
1806       break;
1807     }
1808 
1809     break;
1810   }
1811   case TargetOpcode::G_SHUFFLE_VECTOR: {
1812     const MachineOperand &MaskOp = MI->getOperand(3);
1813     if (!MaskOp.isShuffleMask()) {
1814       report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI);
1815       break;
1816     }
1817 
1818     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1819     LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg());
1820     LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg());
1821 
1822     if (Src0Ty != Src1Ty)
1823       report("Source operands must be the same type", MI);
1824 
1825     if (Src0Ty.getScalarType() != DstTy.getScalarType())
1826       report("G_SHUFFLE_VECTOR cannot change element type", MI);
1827 
1828     // Don't check that all operands are vector because scalars are used in
1829     // place of 1 element vectors.
1830     int SrcNumElts = Src0Ty.isVector() ? Src0Ty.getNumElements() : 1;
1831     int DstNumElts = DstTy.isVector() ? DstTy.getNumElements() : 1;
1832 
1833     ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask();
1834 
1835     if (static_cast<int>(MaskIdxes.size()) != DstNumElts)
1836       report("Wrong result type for shufflemask", MI);
1837 
1838     for (int Idx : MaskIdxes) {
1839       if (Idx < 0)
1840         continue;
1841 
1842       if (Idx >= 2 * SrcNumElts)
1843         report("Out of bounds shuffle index", MI);
1844     }
1845 
1846     break;
1847   }
1848 
1849   case TargetOpcode::G_SPLAT_VECTOR: {
1850     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1851     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1852 
1853     if (!DstTy.isScalableVector()) {
1854       report("Destination type must be a scalable vector", MI);
1855       break;
1856     }
1857 
1858     if (!SrcTy.isScalar() && !SrcTy.isPointer()) {
1859       report("Source type must be a scalar or pointer", MI);
1860       break;
1861     }
1862 
1863     if (TypeSize::isKnownGT(DstTy.getElementType().getSizeInBits(),
1864                             SrcTy.getSizeInBits())) {
1865       report("Element type of the destination must be the same size or smaller "
1866              "than the source type",
1867              MI);
1868       break;
1869     }
1870 
1871     break;
1872   }
1873   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
1874     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1875     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1876     LLT IdxTy = MRI->getType(MI->getOperand(2).getReg());
1877 
1878     if (!DstTy.isScalar() && !DstTy.isPointer()) {
1879       report("Destination type must be a scalar or pointer", MI);
1880       break;
1881     }
1882 
1883     if (!SrcTy.isVector()) {
1884       report("First source must be a vector", MI);
1885       break;
1886     }
1887 
1888     auto TLI = MF->getSubtarget().getTargetLowering();
1889     if (IdxTy.getSizeInBits() !=
1890         TLI->getVectorIdxTy(MF->getDataLayout()).getFixedSizeInBits()) {
1891       report("Index type must match VectorIdxTy", MI);
1892       break;
1893     }
1894 
1895     break;
1896   }
1897   case TargetOpcode::G_INSERT_VECTOR_ELT: {
1898     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1899     LLT VecTy = MRI->getType(MI->getOperand(1).getReg());
1900     LLT ScaTy = MRI->getType(MI->getOperand(2).getReg());
1901     LLT IdxTy = MRI->getType(MI->getOperand(3).getReg());
1902 
1903     if (!DstTy.isVector()) {
1904       report("Destination type must be a vector", MI);
1905       break;
1906     }
1907 
1908     if (VecTy != DstTy) {
1909       report("Destination type and vector type must match", MI);
1910       break;
1911     }
1912 
1913     if (!ScaTy.isScalar() && !ScaTy.isPointer()) {
1914       report("Inserted element must be a scalar or pointer", MI);
1915       break;
1916     }
1917 
1918     auto TLI = MF->getSubtarget().getTargetLowering();
1919     if (IdxTy.getSizeInBits() !=
1920         TLI->getVectorIdxTy(MF->getDataLayout()).getFixedSizeInBits()) {
1921       report("Index type must match VectorIdxTy", MI);
1922       break;
1923     }
1924 
1925     break;
1926   }
1927   case TargetOpcode::G_DYN_STACKALLOC: {
1928     const MachineOperand &DstOp = MI->getOperand(0);
1929     const MachineOperand &AllocOp = MI->getOperand(1);
1930     const MachineOperand &AlignOp = MI->getOperand(2);
1931 
1932     if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) {
1933       report("dst operand 0 must be a pointer type", MI);
1934       break;
1935     }
1936 
1937     if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) {
1938       report("src operand 1 must be a scalar reg type", MI);
1939       break;
1940     }
1941 
1942     if (!AlignOp.isImm()) {
1943       report("src operand 2 must be an immediate type", MI);
1944       break;
1945     }
1946     break;
1947   }
1948   case TargetOpcode::G_MEMCPY_INLINE:
1949   case TargetOpcode::G_MEMCPY:
1950   case TargetOpcode::G_MEMMOVE: {
1951     ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
1952     if (MMOs.size() != 2) {
1953       report("memcpy/memmove must have 2 memory operands", MI);
1954       break;
1955     }
1956 
1957     if ((!MMOs[0]->isStore() || MMOs[0]->isLoad()) ||
1958         (MMOs[1]->isStore() || !MMOs[1]->isLoad())) {
1959       report("wrong memory operand types", MI);
1960       break;
1961     }
1962 
1963     if (MMOs[0]->getSize() != MMOs[1]->getSize())
1964       report("inconsistent memory operand sizes", MI);
1965 
1966     LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
1967     LLT SrcPtrTy = MRI->getType(MI->getOperand(1).getReg());
1968 
1969     if (!DstPtrTy.isPointer() || !SrcPtrTy.isPointer()) {
1970       report("memory instruction operand must be a pointer", MI);
1971       break;
1972     }
1973 
1974     if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
1975       report("inconsistent store address space", MI);
1976     if (SrcPtrTy.getAddressSpace() != MMOs[1]->getAddrSpace())
1977       report("inconsistent load address space", MI);
1978 
1979     if (Opc != TargetOpcode::G_MEMCPY_INLINE)
1980       if (!MI->getOperand(3).isImm() || (MI->getOperand(3).getImm() & ~1LL))
1981         report("'tail' flag (operand 3) must be an immediate 0 or 1", MI);
1982 
1983     break;
1984   }
1985   case TargetOpcode::G_BZERO:
1986   case TargetOpcode::G_MEMSET: {
1987     ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
1988     std::string Name = Opc == TargetOpcode::G_MEMSET ? "memset" : "bzero";
1989     if (MMOs.size() != 1) {
1990       report(Twine(Name, " must have 1 memory operand"), MI);
1991       break;
1992     }
1993 
1994     if ((!MMOs[0]->isStore() || MMOs[0]->isLoad())) {
1995       report(Twine(Name, " memory operand must be a store"), MI);
1996       break;
1997     }
1998 
1999     LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
2000     if (!DstPtrTy.isPointer()) {
2001       report(Twine(Name, " operand must be a pointer"), MI);
2002       break;
2003     }
2004 
2005     if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
2006       report("inconsistent " + Twine(Name, " address space"), MI);
2007 
2008     if (!MI->getOperand(MI->getNumOperands() - 1).isImm() ||
2009         (MI->getOperand(MI->getNumOperands() - 1).getImm() & ~1LL))
2010       report("'tail' flag (last operand) must be an immediate 0 or 1", MI);
2011 
2012     break;
2013   }
2014   case TargetOpcode::G_UBSANTRAP: {
2015     const MachineOperand &KindOp = MI->getOperand(0);
2016     if (!MI->getOperand(0).isImm()) {
2017       report("Crash kind must be an immediate", &KindOp, 0);
2018       break;
2019     }
2020     int64_t Kind = MI->getOperand(0).getImm();
2021     if (!isInt<8>(Kind))
2022       report("Crash kind must be 8 bit wide", &KindOp, 0);
2023     break;
2024   }
2025   case TargetOpcode::G_VECREDUCE_SEQ_FADD:
2026   case TargetOpcode::G_VECREDUCE_SEQ_FMUL: {
2027     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2028     LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
2029     LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
2030     if (!DstTy.isScalar())
2031       report("Vector reduction requires a scalar destination type", MI);
2032     if (!Src1Ty.isScalar())
2033       report("Sequential FADD/FMUL vector reduction requires a scalar 1st operand", MI);
2034     if (!Src2Ty.isVector())
2035       report("Sequential FADD/FMUL vector reduction must have a vector 2nd operand", MI);
2036     break;
2037   }
2038   case TargetOpcode::G_VECREDUCE_FADD:
2039   case TargetOpcode::G_VECREDUCE_FMUL:
2040   case TargetOpcode::G_VECREDUCE_FMAX:
2041   case TargetOpcode::G_VECREDUCE_FMIN:
2042   case TargetOpcode::G_VECREDUCE_FMAXIMUM:
2043   case TargetOpcode::G_VECREDUCE_FMINIMUM:
2044   case TargetOpcode::G_VECREDUCE_ADD:
2045   case TargetOpcode::G_VECREDUCE_MUL:
2046   case TargetOpcode::G_VECREDUCE_AND:
2047   case TargetOpcode::G_VECREDUCE_OR:
2048   case TargetOpcode::G_VECREDUCE_XOR:
2049   case TargetOpcode::G_VECREDUCE_SMAX:
2050   case TargetOpcode::G_VECREDUCE_SMIN:
2051   case TargetOpcode::G_VECREDUCE_UMAX:
2052   case TargetOpcode::G_VECREDUCE_UMIN: {
2053     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2054     if (!DstTy.isScalar())
2055       report("Vector reduction requires a scalar destination type", MI);
2056     break;
2057   }
2058 
2059   case TargetOpcode::G_SBFX:
2060   case TargetOpcode::G_UBFX: {
2061     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2062     if (DstTy.isVector()) {
2063       report("Bitfield extraction is not supported on vectors", MI);
2064       break;
2065     }
2066     break;
2067   }
2068   case TargetOpcode::G_SHL:
2069   case TargetOpcode::G_LSHR:
2070   case TargetOpcode::G_ASHR:
2071   case TargetOpcode::G_ROTR:
2072   case TargetOpcode::G_ROTL: {
2073     LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
2074     LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
2075     if (Src1Ty.isVector() != Src2Ty.isVector()) {
2076       report("Shifts and rotates require operands to be either all scalars or "
2077              "all vectors",
2078              MI);
2079       break;
2080     }
2081     break;
2082   }
2083   case TargetOpcode::G_LLROUND:
2084   case TargetOpcode::G_LROUND: {
2085     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2086     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
2087     if (!DstTy.isValid() || !SrcTy.isValid())
2088       break;
2089     if (SrcTy.isPointer() || DstTy.isPointer()) {
2090       StringRef Op = SrcTy.isPointer() ? "Source" : "Destination";
2091       report(Twine(Op, " operand must not be a pointer type"), MI);
2092     } else if (SrcTy.isScalar()) {
2093       verifyAllRegOpsScalar(*MI, *MRI);
2094       break;
2095     } else if (SrcTy.isVector()) {
2096       verifyVectorElementMatch(SrcTy, DstTy, MI);
2097       break;
2098     }
2099     break;
2100   }
2101   case TargetOpcode::G_IS_FPCLASS: {
2102     LLT DestTy = MRI->getType(MI->getOperand(0).getReg());
2103     LLT DestEltTy = DestTy.getScalarType();
2104     if (!DestEltTy.isScalar()) {
2105       report("Destination must be a scalar or vector of scalars", MI);
2106       break;
2107     }
2108     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
2109     LLT SrcEltTy = SrcTy.getScalarType();
2110     if (!SrcEltTy.isScalar()) {
2111       report("Source must be a scalar or vector of scalars", MI);
2112       break;
2113     }
2114     if (!verifyVectorElementMatch(DestTy, SrcTy, MI))
2115       break;
2116     const MachineOperand &TestMO = MI->getOperand(2);
2117     if (!TestMO.isImm()) {
2118       report("floating-point class set (operand 2) must be an immediate", MI);
2119       break;
2120     }
2121     int64_t Test = TestMO.getImm();
2122     if (Test < 0 || Test > fcAllFlags) {
2123       report("Incorrect floating-point class set (operand 2)", MI);
2124       break;
2125     }
2126     break;
2127   }
2128   case TargetOpcode::G_PREFETCH: {
2129     const MachineOperand &AddrOp = MI->getOperand(0);
2130     if (!AddrOp.isReg() || !MRI->getType(AddrOp.getReg()).isPointer()) {
2131       report("addr operand must be a pointer", &AddrOp, 0);
2132       break;
2133     }
2134     const MachineOperand &RWOp = MI->getOperand(1);
2135     if (!RWOp.isImm() || (uint64_t)RWOp.getImm() >= 2) {
2136       report("rw operand must be an immediate 0-1", &RWOp, 1);
2137       break;
2138     }
2139     const MachineOperand &LocalityOp = MI->getOperand(2);
2140     if (!LocalityOp.isImm() || (uint64_t)LocalityOp.getImm() >= 4) {
2141       report("locality operand must be an immediate 0-3", &LocalityOp, 2);
2142       break;
2143     }
2144     const MachineOperand &CacheTypeOp = MI->getOperand(3);
2145     if (!CacheTypeOp.isImm() || (uint64_t)CacheTypeOp.getImm() >= 2) {
2146       report("cache type operand must be an immediate 0-1", &CacheTypeOp, 3);
2147       break;
2148     }
2149     break;
2150   }
2151   case TargetOpcode::G_ASSERT_ALIGN: {
2152     if (MI->getOperand(2).getImm() < 1)
2153       report("alignment immediate must be >= 1", MI);
2154     break;
2155   }
2156   case TargetOpcode::G_CONSTANT_POOL: {
2157     if (!MI->getOperand(1).isCPI())
2158       report("Src operand 1 must be a constant pool index", MI);
2159     if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
2160       report("Dst operand 0 must be a pointer", MI);
2161     break;
2162   }
2163   case TargetOpcode::G_PTRAUTH_GLOBAL_VALUE: {
2164     const MachineOperand &AddrOp = MI->getOperand(1);
2165     if (!AddrOp.isReg() || !MRI->getType(AddrOp.getReg()).isPointer())
2166       report("addr operand must be a pointer", &AddrOp, 1);
2167     break;
2168   }
2169   default:
2170     break;
2171   }
2172 }
2173 
2174 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
2175   const MCInstrDesc &MCID = MI->getDesc();
2176   if (MI->getNumOperands() < MCID.getNumOperands()) {
2177     report("Too few operands", MI);
2178     errs() << MCID.getNumOperands() << " operands expected, but "
2179            << MI->getNumOperands() << " given.\n";
2180   }
2181 
2182   if (MI->getFlag(MachineInstr::NoConvergent) && !MCID.isConvergent())
2183     report("NoConvergent flag expected only on convergent instructions.", MI);
2184 
2185   if (MI->isPHI()) {
2186     if (MF->getProperties().hasProperty(
2187             MachineFunctionProperties::Property::NoPHIs))
2188       report("Found PHI instruction with NoPHIs property set", MI);
2189 
2190     if (FirstNonPHI)
2191       report("Found PHI instruction after non-PHI", MI);
2192   } else if (FirstNonPHI == nullptr)
2193     FirstNonPHI = MI;
2194 
2195   // Check the tied operands.
2196   if (MI->isInlineAsm())
2197     verifyInlineAsm(MI);
2198 
2199   // Check that unspillable terminators define a reg and have at most one use.
2200   if (TII->isUnspillableTerminator(MI)) {
2201     if (!MI->getOperand(0).isReg() || !MI->getOperand(0).isDef())
2202       report("Unspillable Terminator does not define a reg", MI);
2203     Register Def = MI->getOperand(0).getReg();
2204     if (Def.isVirtual() &&
2205         !MF->getProperties().hasProperty(
2206             MachineFunctionProperties::Property::NoPHIs) &&
2207         std::distance(MRI->use_nodbg_begin(Def), MRI->use_nodbg_end()) > 1)
2208       report("Unspillable Terminator expected to have at most one use!", MI);
2209   }
2210 
2211   // A fully-formed DBG_VALUE must have a location. Ignore partially formed
2212   // DBG_VALUEs: these are convenient to use in tests, but should never get
2213   // generated.
2214   if (MI->isDebugValue() && MI->getNumOperands() == 4)
2215     if (!MI->getDebugLoc())
2216       report("Missing DebugLoc for debug instruction", MI);
2217 
2218   // Meta instructions should never be the subject of debug value tracking,
2219   // they don't create a value in the output program at all.
2220   if (MI->isMetaInstruction() && MI->peekDebugInstrNum())
2221     report("Metadata instruction should not have a value tracking number", MI);
2222 
2223   // Check the MachineMemOperands for basic consistency.
2224   for (MachineMemOperand *Op : MI->memoperands()) {
2225     if (Op->isLoad() && !MI->mayLoad())
2226       report("Missing mayLoad flag", MI);
2227     if (Op->isStore() && !MI->mayStore())
2228       report("Missing mayStore flag", MI);
2229   }
2230 
2231   // Debug values must not have a slot index.
2232   // Other instructions must have one, unless they are inside a bundle.
2233   if (LiveInts) {
2234     bool mapped = !LiveInts->isNotInMIMap(*MI);
2235     if (MI->isDebugOrPseudoInstr()) {
2236       if (mapped)
2237         report("Debug instruction has a slot index", MI);
2238     } else if (MI->isInsideBundle()) {
2239       if (mapped)
2240         report("Instruction inside bundle has a slot index", MI);
2241     } else {
2242       if (!mapped)
2243         report("Missing slot index", MI);
2244     }
2245   }
2246 
2247   unsigned Opc = MCID.getOpcode();
2248   if (isPreISelGenericOpcode(Opc) || isPreISelGenericOptimizationHint(Opc)) {
2249     verifyPreISelGenericInstruction(MI);
2250     return;
2251   }
2252 
2253   StringRef ErrorInfo;
2254   if (!TII->verifyInstruction(*MI, ErrorInfo))
2255     report(ErrorInfo.data(), MI);
2256 
2257   // Verify properties of various specific instruction types
2258   switch (MI->getOpcode()) {
2259   case TargetOpcode::COPY: {
2260     const MachineOperand &DstOp = MI->getOperand(0);
2261     const MachineOperand &SrcOp = MI->getOperand(1);
2262     const Register SrcReg = SrcOp.getReg();
2263     const Register DstReg = DstOp.getReg();
2264 
2265     LLT DstTy = MRI->getType(DstReg);
2266     LLT SrcTy = MRI->getType(SrcReg);
2267     if (SrcTy.isValid() && DstTy.isValid()) {
2268       // If both types are valid, check that the types are the same.
2269       if (SrcTy != DstTy) {
2270         report("Copy Instruction is illegal with mismatching types", MI);
2271         errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n";
2272       }
2273 
2274       break;
2275     }
2276 
2277     if (!SrcTy.isValid() && !DstTy.isValid())
2278       break;
2279 
2280     // If we have only one valid type, this is likely a copy between a virtual
2281     // and physical register.
2282     TypeSize SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI);
2283     TypeSize DstSize = TRI->getRegSizeInBits(DstReg, *MRI);
2284     if (SrcReg.isPhysical() && DstTy.isValid()) {
2285       const TargetRegisterClass *SrcRC =
2286           TRI->getMinimalPhysRegClassLLT(SrcReg, DstTy);
2287       if (SrcRC)
2288         SrcSize = TRI->getRegSizeInBits(*SrcRC);
2289     }
2290 
2291     if (DstReg.isPhysical() && SrcTy.isValid()) {
2292       const TargetRegisterClass *DstRC =
2293           TRI->getMinimalPhysRegClassLLT(DstReg, SrcTy);
2294       if (DstRC)
2295         DstSize = TRI->getRegSizeInBits(*DstRC);
2296     }
2297 
2298     // The next two checks allow COPY between physical and virtual registers,
2299     // when the virtual register has a scalable size and the physical register
2300     // has a fixed size. These checks allow COPY between *potentialy* mismatched
2301     // sizes. However, once RegisterBankSelection occurs, MachineVerifier should
2302     // be able to resolve a fixed size for the scalable vector, and at that
2303     // point this function will know for sure whether the sizes are mismatched
2304     // and correctly report a size mismatch.
2305     if (SrcReg.isPhysical() && DstReg.isVirtual() && DstSize.isScalable() &&
2306         !SrcSize.isScalable())
2307       break;
2308     if (SrcReg.isVirtual() && DstReg.isPhysical() && SrcSize.isScalable() &&
2309         !DstSize.isScalable())
2310       break;
2311 
2312     if (SrcSize.isNonZero() && DstSize.isNonZero() && SrcSize != DstSize) {
2313       if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
2314         report("Copy Instruction is illegal with mismatching sizes", MI);
2315         errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize
2316                << "\n";
2317       }
2318     }
2319     break;
2320   }
2321   case TargetOpcode::STATEPOINT: {
2322     StatepointOpers SO(MI);
2323     if (!MI->getOperand(SO.getIDPos()).isImm() ||
2324         !MI->getOperand(SO.getNBytesPos()).isImm() ||
2325         !MI->getOperand(SO.getNCallArgsPos()).isImm()) {
2326       report("meta operands to STATEPOINT not constant!", MI);
2327       break;
2328     }
2329 
2330     auto VerifyStackMapConstant = [&](unsigned Offset) {
2331       if (Offset >= MI->getNumOperands()) {
2332         report("stack map constant to STATEPOINT is out of range!", MI);
2333         return;
2334       }
2335       if (!MI->getOperand(Offset - 1).isImm() ||
2336           MI->getOperand(Offset - 1).getImm() != StackMaps::ConstantOp ||
2337           !MI->getOperand(Offset).isImm())
2338         report("stack map constant to STATEPOINT not well formed!", MI);
2339     };
2340     VerifyStackMapConstant(SO.getCCIdx());
2341     VerifyStackMapConstant(SO.getFlagsIdx());
2342     VerifyStackMapConstant(SO.getNumDeoptArgsIdx());
2343     VerifyStackMapConstant(SO.getNumGCPtrIdx());
2344     VerifyStackMapConstant(SO.getNumAllocaIdx());
2345     VerifyStackMapConstant(SO.getNumGcMapEntriesIdx());
2346 
2347     // Verify that all explicit statepoint defs are tied to gc operands as
2348     // they are expected to be a relocation of gc operands.
2349     unsigned FirstGCPtrIdx = SO.getFirstGCPtrIdx();
2350     unsigned LastGCPtrIdx = SO.getNumAllocaIdx() - 2;
2351     for (unsigned Idx = 0; Idx < MI->getNumDefs(); Idx++) {
2352       unsigned UseOpIdx;
2353       if (!MI->isRegTiedToUseOperand(Idx, &UseOpIdx)) {
2354         report("STATEPOINT defs expected to be tied", MI);
2355         break;
2356       }
2357       if (UseOpIdx < FirstGCPtrIdx || UseOpIdx > LastGCPtrIdx) {
2358         report("STATEPOINT def tied to non-gc operand", MI);
2359         break;
2360       }
2361     }
2362 
2363     // TODO: verify we have properly encoded deopt arguments
2364   } break;
2365   case TargetOpcode::INSERT_SUBREG: {
2366     unsigned InsertedSize;
2367     if (unsigned SubIdx = MI->getOperand(2).getSubReg())
2368       InsertedSize = TRI->getSubRegIdxSize(SubIdx);
2369     else
2370       InsertedSize = TRI->getRegSizeInBits(MI->getOperand(2).getReg(), *MRI);
2371     unsigned SubRegSize = TRI->getSubRegIdxSize(MI->getOperand(3).getImm());
2372     if (SubRegSize < InsertedSize) {
2373       report("INSERT_SUBREG expected inserted value to have equal or lesser "
2374              "size than the subreg it was inserted into", MI);
2375       break;
2376     }
2377   } break;
2378   case TargetOpcode::REG_SEQUENCE: {
2379     unsigned NumOps = MI->getNumOperands();
2380     if (!(NumOps & 1)) {
2381       report("Invalid number of operands for REG_SEQUENCE", MI);
2382       break;
2383     }
2384 
2385     for (unsigned I = 1; I != NumOps; I += 2) {
2386       const MachineOperand &RegOp = MI->getOperand(I);
2387       const MachineOperand &SubRegOp = MI->getOperand(I + 1);
2388 
2389       if (!RegOp.isReg())
2390         report("Invalid register operand for REG_SEQUENCE", &RegOp, I);
2391 
2392       if (!SubRegOp.isImm() || SubRegOp.getImm() == 0 ||
2393           SubRegOp.getImm() >= TRI->getNumSubRegIndices()) {
2394         report("Invalid subregister index operand for REG_SEQUENCE",
2395                &SubRegOp, I + 1);
2396       }
2397     }
2398 
2399     Register DstReg = MI->getOperand(0).getReg();
2400     if (DstReg.isPhysical())
2401       report("REG_SEQUENCE does not support physical register results", MI);
2402 
2403     if (MI->getOperand(0).getSubReg())
2404       report("Invalid subreg result for REG_SEQUENCE", MI);
2405 
2406     break;
2407   }
2408   }
2409 }
2410 
2411 void
2412 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
2413   const MachineInstr *MI = MO->getParent();
2414   const MCInstrDesc &MCID = MI->getDesc();
2415   unsigned NumDefs = MCID.getNumDefs();
2416   if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
2417     NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
2418 
2419   // The first MCID.NumDefs operands must be explicit register defines
2420   if (MONum < NumDefs) {
2421     const MCOperandInfo &MCOI = MCID.operands()[MONum];
2422     if (!MO->isReg())
2423       report("Explicit definition must be a register", MO, MONum);
2424     else if (!MO->isDef() && !MCOI.isOptionalDef())
2425       report("Explicit definition marked as use", MO, MONum);
2426     else if (MO->isImplicit())
2427       report("Explicit definition marked as implicit", MO, MONum);
2428   } else if (MONum < MCID.getNumOperands()) {
2429     const MCOperandInfo &MCOI = MCID.operands()[MONum];
2430     // Don't check if it's the last operand in a variadic instruction. See,
2431     // e.g., LDM_RET in the arm back end. Check non-variadic operands only.
2432     bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1;
2433     if (!IsOptional) {
2434       if (MO->isReg()) {
2435         if (MO->isDef() && !MCOI.isOptionalDef() && !MCID.variadicOpsAreDefs())
2436           report("Explicit operand marked as def", MO, MONum);
2437         if (MO->isImplicit())
2438           report("Explicit operand marked as implicit", MO, MONum);
2439       }
2440 
2441       // Check that an instruction has register operands only as expected.
2442       if (MCOI.OperandType == MCOI::OPERAND_REGISTER &&
2443           !MO->isReg() && !MO->isFI())
2444         report("Expected a register operand.", MO, MONum);
2445       if (MO->isReg()) {
2446         if (MCOI.OperandType == MCOI::OPERAND_IMMEDIATE ||
2447             (MCOI.OperandType == MCOI::OPERAND_PCREL &&
2448              !TII->isPCRelRegisterOperandLegal(*MO)))
2449           report("Expected a non-register operand.", MO, MONum);
2450       }
2451     }
2452 
2453     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
2454     if (TiedTo != -1) {
2455       if (!MO->isReg())
2456         report("Tied use must be a register", MO, MONum);
2457       else if (!MO->isTied())
2458         report("Operand should be tied", MO, MONum);
2459       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
2460         report("Tied def doesn't match MCInstrDesc", MO, MONum);
2461       else if (MO->getReg().isPhysical()) {
2462         const MachineOperand &MOTied = MI->getOperand(TiedTo);
2463         if (!MOTied.isReg())
2464           report("Tied counterpart must be a register", &MOTied, TiedTo);
2465         else if (MOTied.getReg().isPhysical() &&
2466                  MO->getReg() != MOTied.getReg())
2467           report("Tied physical registers must match.", &MOTied, TiedTo);
2468       }
2469     } else if (MO->isReg() && MO->isTied())
2470       report("Explicit operand should not be tied", MO, MONum);
2471   } else if (!MI->isVariadic()) {
2472     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
2473     if (!MO->isValidExcessOperand())
2474       report("Extra explicit operand on non-variadic instruction", MO, MONum);
2475   }
2476 
2477   switch (MO->getType()) {
2478   case MachineOperand::MO_Register: {
2479     // Verify debug flag on debug instructions. Check this first because reg0
2480     // indicates an undefined debug value.
2481     if (MI->isDebugInstr() && MO->isUse()) {
2482       if (!MO->isDebug())
2483         report("Register operand must be marked debug", MO, MONum);
2484     } else if (MO->isDebug()) {
2485       report("Register operand must not be marked debug", MO, MONum);
2486     }
2487 
2488     const Register Reg = MO->getReg();
2489     if (!Reg)
2490       return;
2491     if (MRI->tracksLiveness() && !MI->isDebugInstr())
2492       checkLiveness(MO, MONum);
2493 
2494     if (MO->isDef() && MO->isUndef() && !MO->getSubReg() &&
2495         MO->getReg().isVirtual()) // TODO: Apply to physregs too
2496       report("Undef virtual register def operands require a subregister", MO, MONum);
2497 
2498     // Verify the consistency of tied operands.
2499     if (MO->isTied()) {
2500       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
2501       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
2502       if (!OtherMO.isReg())
2503         report("Must be tied to a register", MO, MONum);
2504       if (!OtherMO.isTied())
2505         report("Missing tie flags on tied operand", MO, MONum);
2506       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
2507         report("Inconsistent tie links", MO, MONum);
2508       if (MONum < MCID.getNumDefs()) {
2509         if (OtherIdx < MCID.getNumOperands()) {
2510           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
2511             report("Explicit def tied to explicit use without tie constraint",
2512                    MO, MONum);
2513         } else {
2514           if (!OtherMO.isImplicit())
2515             report("Explicit def should be tied to implicit use", MO, MONum);
2516         }
2517       }
2518     }
2519 
2520     // Verify two-address constraints after the twoaddressinstruction pass.
2521     // Both twoaddressinstruction pass and phi-node-elimination pass call
2522     // MRI->leaveSSA() to set MF as not IsSSA, we should do the verification
2523     // after twoaddressinstruction pass not after phi-node-elimination pass. So
2524     // we shouldn't use the IsSSA as the condition, we should based on
2525     // TiedOpsRewritten property to verify two-address constraints, this
2526     // property will be set in twoaddressinstruction pass.
2527     unsigned DefIdx;
2528     if (MF->getProperties().hasProperty(
2529             MachineFunctionProperties::Property::TiedOpsRewritten) &&
2530         MO->isUse() && MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
2531         Reg != MI->getOperand(DefIdx).getReg())
2532       report("Two-address instruction operands must be identical", MO, MONum);
2533 
2534     // Check register classes.
2535     unsigned SubIdx = MO->getSubReg();
2536 
2537     if (Reg.isPhysical()) {
2538       if (SubIdx) {
2539         report("Illegal subregister index for physical register", MO, MONum);
2540         return;
2541       }
2542       if (MONum < MCID.getNumOperands()) {
2543         if (const TargetRegisterClass *DRC =
2544               TII->getRegClass(MCID, MONum, TRI, *MF)) {
2545           if (!DRC->contains(Reg)) {
2546             report("Illegal physical register for instruction", MO, MONum);
2547             errs() << printReg(Reg, TRI) << " is not a "
2548                    << TRI->getRegClassName(DRC) << " register.\n";
2549           }
2550         }
2551       }
2552       if (MO->isRenamable()) {
2553         if (MRI->isReserved(Reg)) {
2554           report("isRenamable set on reserved register", MO, MONum);
2555           return;
2556         }
2557       }
2558     } else {
2559       // Virtual register.
2560       const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
2561       if (!RC) {
2562         // This is a generic virtual register.
2563 
2564         // Do not allow undef uses for generic virtual registers. This ensures
2565         // getVRegDef can never fail and return null on a generic register.
2566         //
2567         // FIXME: This restriction should probably be broadened to all SSA
2568         // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still
2569         // run on the SSA function just before phi elimination.
2570         if (MO->isUndef())
2571           report("Generic virtual register use cannot be undef", MO, MONum);
2572 
2573         // Debug value instruction is permitted to use undefined vregs.
2574         // This is a performance measure to skip the overhead of immediately
2575         // pruning unused debug operands. The final undef substitution occurs
2576         // when debug values are allocated in LDVImpl::handleDebugValue, so
2577         // these verifications always apply after this pass.
2578         if (isFunctionTracksDebugUserValues || !MO->isUse() ||
2579             !MI->isDebugValue() || !MRI->def_empty(Reg)) {
2580           // If we're post-Select, we can't have gvregs anymore.
2581           if (isFunctionSelected) {
2582             report("Generic virtual register invalid in a Selected function",
2583                    MO, MONum);
2584             return;
2585           }
2586 
2587           // The gvreg must have a type and it must not have a SubIdx.
2588           LLT Ty = MRI->getType(Reg);
2589           if (!Ty.isValid()) {
2590             report("Generic virtual register must have a valid type", MO,
2591                    MONum);
2592             return;
2593           }
2594 
2595           const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
2596           const RegisterBankInfo *RBI = MF->getSubtarget().getRegBankInfo();
2597 
2598           // If we're post-RegBankSelect, the gvreg must have a bank.
2599           if (!RegBank && isFunctionRegBankSelected) {
2600             report("Generic virtual register must have a bank in a "
2601                    "RegBankSelected function",
2602                    MO, MONum);
2603             return;
2604           }
2605 
2606           // Make sure the register fits into its register bank if any.
2607           if (RegBank && Ty.isValid() && !Ty.isScalableVector() &&
2608               RBI->getMaximumSize(RegBank->getID()) < Ty.getSizeInBits()) {
2609             report("Register bank is too small for virtual register", MO,
2610                    MONum);
2611             errs() << "Register bank " << RegBank->getName() << " too small("
2612                    << RBI->getMaximumSize(RegBank->getID()) << ") to fit "
2613                    << Ty.getSizeInBits() << "-bits\n";
2614             return;
2615           }
2616         }
2617 
2618         if (SubIdx)  {
2619           report("Generic virtual register does not allow subregister index", MO,
2620                  MONum);
2621           return;
2622         }
2623 
2624         // If this is a target specific instruction and this operand
2625         // has register class constraint, the virtual register must
2626         // comply to it.
2627         if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
2628             MONum < MCID.getNumOperands() &&
2629             TII->getRegClass(MCID, MONum, TRI, *MF)) {
2630           report("Virtual register does not match instruction constraint", MO,
2631                  MONum);
2632           errs() << "Expect register class "
2633                  << TRI->getRegClassName(
2634                         TII->getRegClass(MCID, MONum, TRI, *MF))
2635                  << " but got nothing\n";
2636           return;
2637         }
2638 
2639         break;
2640       }
2641       if (SubIdx) {
2642         const TargetRegisterClass *SRC =
2643           TRI->getSubClassWithSubReg(RC, SubIdx);
2644         if (!SRC) {
2645           report("Invalid subregister index for virtual register", MO, MONum);
2646           errs() << "Register class " << TRI->getRegClassName(RC)
2647               << " does not support subreg index " << SubIdx << "\n";
2648           return;
2649         }
2650         if (RC != SRC) {
2651           report("Invalid register class for subregister index", MO, MONum);
2652           errs() << "Register class " << TRI->getRegClassName(RC)
2653               << " does not fully support subreg index " << SubIdx << "\n";
2654           return;
2655         }
2656       }
2657       if (MONum < MCID.getNumOperands()) {
2658         if (const TargetRegisterClass *DRC =
2659               TII->getRegClass(MCID, MONum, TRI, *MF)) {
2660           if (SubIdx) {
2661             const TargetRegisterClass *SuperRC =
2662                 TRI->getLargestLegalSuperClass(RC, *MF);
2663             if (!SuperRC) {
2664               report("No largest legal super class exists.", MO, MONum);
2665               return;
2666             }
2667             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
2668             if (!DRC) {
2669               report("No matching super-reg register class.", MO, MONum);
2670               return;
2671             }
2672           }
2673           if (!RC->hasSuperClassEq(DRC)) {
2674             report("Illegal virtual register for instruction", MO, MONum);
2675             errs() << "Expected a " << TRI->getRegClassName(DRC)
2676                 << " register, but got a " << TRI->getRegClassName(RC)
2677                 << " register\n";
2678           }
2679         }
2680       }
2681     }
2682     break;
2683   }
2684 
2685   case MachineOperand::MO_RegisterMask:
2686     regMasks.push_back(MO->getRegMask());
2687     break;
2688 
2689   case MachineOperand::MO_MachineBasicBlock:
2690     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
2691       report("PHI operand is not in the CFG", MO, MONum);
2692     break;
2693 
2694   case MachineOperand::MO_FrameIndex:
2695     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
2696         LiveInts && !LiveInts->isNotInMIMap(*MI)) {
2697       int FI = MO->getIndex();
2698       LiveInterval &LI = LiveStks->getInterval(FI);
2699       SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
2700 
2701       bool stores = MI->mayStore();
2702       bool loads = MI->mayLoad();
2703       // For a memory-to-memory move, we need to check if the frame
2704       // index is used for storing or loading, by inspecting the
2705       // memory operands.
2706       if (stores && loads) {
2707         for (auto *MMO : MI->memoperands()) {
2708           const PseudoSourceValue *PSV = MMO->getPseudoValue();
2709           if (PSV == nullptr) continue;
2710           const FixedStackPseudoSourceValue *Value =
2711             dyn_cast<FixedStackPseudoSourceValue>(PSV);
2712           if (Value == nullptr) continue;
2713           if (Value->getFrameIndex() != FI) continue;
2714 
2715           if (MMO->isStore())
2716             loads = false;
2717           else
2718             stores = false;
2719           break;
2720         }
2721         if (loads == stores)
2722           report("Missing fixed stack memoperand.", MI);
2723       }
2724       if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
2725         report("Instruction loads from dead spill slot", MO, MONum);
2726         errs() << "Live stack: " << LI << '\n';
2727       }
2728       if (stores && !LI.liveAt(Idx.getRegSlot())) {
2729         report("Instruction stores to dead spill slot", MO, MONum);
2730         errs() << "Live stack: " << LI << '\n';
2731       }
2732     }
2733     break;
2734 
2735   case MachineOperand::MO_CFIIndex:
2736     if (MO->getCFIIndex() >= MF->getFrameInstructions().size())
2737       report("CFI instruction has invalid index", MO, MONum);
2738     break;
2739 
2740   default:
2741     break;
2742   }
2743 }
2744 
2745 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
2746                                          unsigned MONum, SlotIndex UseIdx,
2747                                          const LiveRange &LR,
2748                                          Register VRegOrUnit,
2749                                          LaneBitmask LaneMask) {
2750   const MachineInstr *MI = MO->getParent();
2751   LiveQueryResult LRQ = LR.Query(UseIdx);
2752   bool HasValue = LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut());
2753   // Check if we have a segment at the use, note however that we only need one
2754   // live subregister range, the others may be dead.
2755   if (!HasValue && LaneMask.none()) {
2756     report("No live segment at use", MO, MONum);
2757     report_context_liverange(LR);
2758     report_context_vreg_regunit(VRegOrUnit);
2759     report_context(UseIdx);
2760   }
2761   if (MO->isKill() && !LRQ.isKill()) {
2762     report("Live range continues after kill flag", MO, MONum);
2763     report_context_liverange(LR);
2764     report_context_vreg_regunit(VRegOrUnit);
2765     if (LaneMask.any())
2766       report_context_lanemask(LaneMask);
2767     report_context(UseIdx);
2768   }
2769 }
2770 
2771 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
2772                                          unsigned MONum, SlotIndex DefIdx,
2773                                          const LiveRange &LR,
2774                                          Register VRegOrUnit,
2775                                          bool SubRangeCheck,
2776                                          LaneBitmask LaneMask) {
2777   if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
2778     // The LR can correspond to the whole reg and its def slot is not obliged
2779     // to be the same as the MO' def slot. E.g. when we check here "normal"
2780     // subreg MO but there is other EC subreg MO in the same instruction so the
2781     // whole reg has EC def slot and differs from the currently checked MO' def
2782     // slot. For example:
2783     // %0 [16e,32r:0) 0@16e  L..3 [16e,32r:0) 0@16e  L..C [16r,32r:0) 0@16r
2784     // Check that there is an early-clobber def of the same superregister
2785     // somewhere is performed in visitMachineFunctionAfter()
2786     if (((SubRangeCheck || MO->getSubReg() == 0) && VNI->def != DefIdx) ||
2787         !SlotIndex::isSameInstr(VNI->def, DefIdx) ||
2788         (VNI->def != DefIdx &&
2789          (!VNI->def.isEarlyClobber() || !DefIdx.isRegister()))) {
2790       report("Inconsistent valno->def", MO, MONum);
2791       report_context_liverange(LR);
2792       report_context_vreg_regunit(VRegOrUnit);
2793       if (LaneMask.any())
2794         report_context_lanemask(LaneMask);
2795       report_context(*VNI);
2796       report_context(DefIdx);
2797     }
2798   } else {
2799     report("No live segment at def", MO, MONum);
2800     report_context_liverange(LR);
2801     report_context_vreg_regunit(VRegOrUnit);
2802     if (LaneMask.any())
2803       report_context_lanemask(LaneMask);
2804     report_context(DefIdx);
2805   }
2806   // Check that, if the dead def flag is present, LiveInts agree.
2807   if (MO->isDead()) {
2808     LiveQueryResult LRQ = LR.Query(DefIdx);
2809     if (!LRQ.isDeadDef()) {
2810       assert(VRegOrUnit.isVirtual() && "Expecting a virtual register.");
2811       // A dead subreg def only tells us that the specific subreg is dead. There
2812       // could be other non-dead defs of other subregs, or we could have other
2813       // parts of the register being live through the instruction. So unless we
2814       // are checking liveness for a subrange it is ok for the live range to
2815       // continue, given that we have a dead def of a subregister.
2816       if (SubRangeCheck || MO->getSubReg() == 0) {
2817         report("Live range continues after dead def flag", MO, MONum);
2818         report_context_liverange(LR);
2819         report_context_vreg_regunit(VRegOrUnit);
2820         if (LaneMask.any())
2821           report_context_lanemask(LaneMask);
2822       }
2823     }
2824   }
2825 }
2826 
2827 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
2828   const MachineInstr *MI = MO->getParent();
2829   const Register Reg = MO->getReg();
2830   const unsigned SubRegIdx = MO->getSubReg();
2831 
2832   const LiveInterval *LI = nullptr;
2833   if (LiveInts && Reg.isVirtual()) {
2834     if (LiveInts->hasInterval(Reg)) {
2835       LI = &LiveInts->getInterval(Reg);
2836       if (SubRegIdx != 0 && (MO->isDef() || !MO->isUndef()) && !LI->empty() &&
2837           !LI->hasSubRanges() && MRI->shouldTrackSubRegLiveness(Reg))
2838         report("Live interval for subreg operand has no subranges", MO, MONum);
2839     } else {
2840       report("Virtual register has no live interval", MO, MONum);
2841     }
2842   }
2843 
2844   // Both use and def operands can read a register.
2845   if (MO->readsReg()) {
2846     if (MO->isKill())
2847       addRegWithSubRegs(regsKilled, Reg);
2848 
2849     // Check that LiveVars knows this kill (unless we are inside a bundle, in
2850     // which case we have already checked that LiveVars knows any kills on the
2851     // bundle header instead).
2852     if (LiveVars && Reg.isVirtual() && MO->isKill() &&
2853         !MI->isBundledWithPred()) {
2854       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
2855       if (!is_contained(VI.Kills, MI))
2856         report("Kill missing from LiveVariables", MO, MONum);
2857     }
2858 
2859     // Check LiveInts liveness and kill.
2860     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
2861       SlotIndex UseIdx;
2862       if (MI->isPHI()) {
2863         // PHI use occurs on the edge, so check for live out here instead.
2864         UseIdx = LiveInts->getMBBEndIdx(
2865           MI->getOperand(MONum + 1).getMBB()).getPrevSlot();
2866       } else {
2867         UseIdx = LiveInts->getInstructionIndex(*MI);
2868       }
2869       // Check the cached regunit intervals.
2870       if (Reg.isPhysical() && !isReserved(Reg)) {
2871         for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg())) {
2872           if (MRI->isReservedRegUnit(Unit))
2873             continue;
2874           if (const LiveRange *LR = LiveInts->getCachedRegUnit(Unit))
2875             checkLivenessAtUse(MO, MONum, UseIdx, *LR, Unit);
2876         }
2877       }
2878 
2879       if (Reg.isVirtual()) {
2880         // This is a virtual register interval.
2881         checkLivenessAtUse(MO, MONum, UseIdx, *LI, Reg);
2882 
2883         if (LI->hasSubRanges() && !MO->isDef()) {
2884           LaneBitmask MOMask = SubRegIdx != 0
2885                                    ? TRI->getSubRegIndexLaneMask(SubRegIdx)
2886                                    : MRI->getMaxLaneMaskForVReg(Reg);
2887           LaneBitmask LiveInMask;
2888           for (const LiveInterval::SubRange &SR : LI->subranges()) {
2889             if ((MOMask & SR.LaneMask).none())
2890               continue;
2891             checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
2892             LiveQueryResult LRQ = SR.Query(UseIdx);
2893             if (LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut()))
2894               LiveInMask |= SR.LaneMask;
2895           }
2896           // At least parts of the register has to be live at the use.
2897           if ((LiveInMask & MOMask).none()) {
2898             report("No live subrange at use", MO, MONum);
2899             report_context(*LI);
2900             report_context(UseIdx);
2901           }
2902           // For PHIs all lanes should be live
2903           if (MI->isPHI() && LiveInMask != MOMask) {
2904             report("Not all lanes of PHI source live at use", MO, MONum);
2905             report_context(*LI);
2906             report_context(UseIdx);
2907           }
2908         }
2909       }
2910     }
2911 
2912     // Use of a dead register.
2913     if (!regsLive.count(Reg)) {
2914       if (Reg.isPhysical()) {
2915         // Reserved registers may be used even when 'dead'.
2916         bool Bad = !isReserved(Reg);
2917         // We are fine if just any subregister has a defined value.
2918         if (Bad) {
2919 
2920           for (const MCPhysReg &SubReg : TRI->subregs(Reg)) {
2921             if (regsLive.count(SubReg)) {
2922               Bad = false;
2923               break;
2924             }
2925           }
2926         }
2927         // If there is an additional implicit-use of a super register we stop
2928         // here. By definition we are fine if the super register is not
2929         // (completely) dead, if the complete super register is dead we will
2930         // get a report for its operand.
2931         if (Bad) {
2932           for (const MachineOperand &MOP : MI->uses()) {
2933             if (!MOP.isReg() || !MOP.isImplicit())
2934               continue;
2935 
2936             if (!MOP.getReg().isPhysical())
2937               continue;
2938 
2939             if (llvm::is_contained(TRI->subregs(MOP.getReg()), Reg))
2940               Bad = false;
2941           }
2942         }
2943         if (Bad)
2944           report("Using an undefined physical register", MO, MONum);
2945       } else if (MRI->def_empty(Reg)) {
2946         report("Reading virtual register without a def", MO, MONum);
2947       } else {
2948         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
2949         // We don't know which virtual registers are live in, so only complain
2950         // if vreg was killed in this MBB. Otherwise keep track of vregs that
2951         // must be live in. PHI instructions are handled separately.
2952         if (MInfo.regsKilled.count(Reg))
2953           report("Using a killed virtual register", MO, MONum);
2954         else if (!MI->isPHI())
2955           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
2956       }
2957     }
2958   }
2959 
2960   if (MO->isDef()) {
2961     // Register defined.
2962     // TODO: verify that earlyclobber ops are not used.
2963     if (MO->isDead())
2964       addRegWithSubRegs(regsDead, Reg);
2965     else
2966       addRegWithSubRegs(regsDefined, Reg);
2967 
2968     // Verify SSA form.
2969     if (MRI->isSSA() && Reg.isVirtual() &&
2970         std::next(MRI->def_begin(Reg)) != MRI->def_end())
2971       report("Multiple virtual register defs in SSA form", MO, MONum);
2972 
2973     // Check LiveInts for a live segment, but only for virtual registers.
2974     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
2975       SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
2976       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
2977 
2978       if (Reg.isVirtual()) {
2979         checkLivenessAtDef(MO, MONum, DefIdx, *LI, Reg);
2980 
2981         if (LI->hasSubRanges()) {
2982           LaneBitmask MOMask = SubRegIdx != 0
2983                                    ? TRI->getSubRegIndexLaneMask(SubRegIdx)
2984                                    : MRI->getMaxLaneMaskForVReg(Reg);
2985           for (const LiveInterval::SubRange &SR : LI->subranges()) {
2986             if ((SR.LaneMask & MOMask).none())
2987               continue;
2988             checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask);
2989           }
2990         }
2991       }
2992     }
2993   }
2994 }
2995 
2996 // This function gets called after visiting all instructions in a bundle. The
2997 // argument points to the bundle header.
2998 // Normal stand-alone instructions are also considered 'bundles', and this
2999 // function is called for all of them.
3000 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
3001   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
3002   set_union(MInfo.regsKilled, regsKilled);
3003   set_subtract(regsLive, regsKilled); regsKilled.clear();
3004   // Kill any masked registers.
3005   while (!regMasks.empty()) {
3006     const uint32_t *Mask = regMasks.pop_back_val();
3007     for (Register Reg : regsLive)
3008       if (Reg.isPhysical() &&
3009           MachineOperand::clobbersPhysReg(Mask, Reg.asMCReg()))
3010         regsDead.push_back(Reg);
3011   }
3012   set_subtract(regsLive, regsDead);   regsDead.clear();
3013   set_union(regsLive, regsDefined);   regsDefined.clear();
3014 }
3015 
3016 void
3017 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
3018   MBBInfoMap[MBB].regsLiveOut = regsLive;
3019   regsLive.clear();
3020 
3021   if (Indexes) {
3022     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
3023     if (!(stop > lastIndex)) {
3024       report("Block ends before last instruction index", MBB);
3025       errs() << "Block ends at " << stop
3026           << " last instruction was at " << lastIndex << '\n';
3027     }
3028     lastIndex = stop;
3029   }
3030 }
3031 
3032 namespace {
3033 // This implements a set of registers that serves as a filter: can filter other
3034 // sets by passing through elements not in the filter and blocking those that
3035 // are. Any filter implicitly includes the full set of physical registers upon
3036 // creation, thus filtering them all out. The filter itself as a set only grows,
3037 // and needs to be as efficient as possible.
3038 struct VRegFilter {
3039   // Add elements to the filter itself. \pre Input set \p FromRegSet must have
3040   // no duplicates. Both virtual and physical registers are fine.
3041   template <typename RegSetT> void add(const RegSetT &FromRegSet) {
3042     SmallVector<Register, 0> VRegsBuffer;
3043     filterAndAdd(FromRegSet, VRegsBuffer);
3044   }
3045   // Filter \p FromRegSet through the filter and append passed elements into \p
3046   // ToVRegs. All elements appended are then added to the filter itself.
3047   // \returns true if anything changed.
3048   template <typename RegSetT>
3049   bool filterAndAdd(const RegSetT &FromRegSet,
3050                     SmallVectorImpl<Register> &ToVRegs) {
3051     unsigned SparseUniverse = Sparse.size();
3052     unsigned NewSparseUniverse = SparseUniverse;
3053     unsigned NewDenseSize = Dense.size();
3054     size_t Begin = ToVRegs.size();
3055     for (Register Reg : FromRegSet) {
3056       if (!Reg.isVirtual())
3057         continue;
3058       unsigned Index = Register::virtReg2Index(Reg);
3059       if (Index < SparseUniverseMax) {
3060         if (Index < SparseUniverse && Sparse.test(Index))
3061           continue;
3062         NewSparseUniverse = std::max(NewSparseUniverse, Index + 1);
3063       } else {
3064         if (Dense.count(Reg))
3065           continue;
3066         ++NewDenseSize;
3067       }
3068       ToVRegs.push_back(Reg);
3069     }
3070     size_t End = ToVRegs.size();
3071     if (Begin == End)
3072       return false;
3073     // Reserving space in sets once performs better than doing so continuously
3074     // and pays easily for double look-ups (even in Dense with SparseUniverseMax
3075     // tuned all the way down) and double iteration (the second one is over a
3076     // SmallVector, which is a lot cheaper compared to DenseSet or BitVector).
3077     Sparse.resize(NewSparseUniverse);
3078     Dense.reserve(NewDenseSize);
3079     for (unsigned I = Begin; I < End; ++I) {
3080       Register Reg = ToVRegs[I];
3081       unsigned Index = Register::virtReg2Index(Reg);
3082       if (Index < SparseUniverseMax)
3083         Sparse.set(Index);
3084       else
3085         Dense.insert(Reg);
3086     }
3087     return true;
3088   }
3089 
3090 private:
3091   static constexpr unsigned SparseUniverseMax = 10 * 1024 * 8;
3092   // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyound
3093   // are tracked by Dense. The only purpose of the threashold and the Dense set
3094   // is to have a reasonably growing memory usage in pathological cases (large
3095   // number of very sparse VRegFilter instances live at the same time). In
3096   // practice even in the worst-by-execution time cases having all elements
3097   // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more
3098   // space efficient than if tracked by Dense. The threashold is set to keep the
3099   // worst-case memory usage within 2x of figures determined empirically for
3100   // "all Dense" scenario in such worst-by-execution-time cases.
3101   BitVector Sparse;
3102   DenseSet<unsigned> Dense;
3103 };
3104 
3105 // Implements both a transfer function and a (binary, in-place) join operator
3106 // for a dataflow over register sets with set union join and filtering transfer
3107 // (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time.
3108 // Maintains out_b as its state, allowing for O(n) iteration over it at any
3109 // time, where n is the size of the set (as opposed to O(U) where U is the
3110 // universe). filter_b implicitly contains all physical registers at all times.
3111 class FilteringVRegSet {
3112   VRegFilter Filter;
3113   SmallVector<Register, 0> VRegs;
3114 
3115 public:
3116   // Set-up the filter_b. \pre Input register set \p RS must have no duplicates.
3117   // Both virtual and physical registers are fine.
3118   template <typename RegSetT> void addToFilter(const RegSetT &RS) {
3119     Filter.add(RS);
3120   }
3121   // Passes \p RS through the filter_b (transfer function) and adds what's left
3122   // to itself (out_b).
3123   template <typename RegSetT> bool add(const RegSetT &RS) {
3124     // Double-duty the Filter: to maintain VRegs a set (and the join operation
3125     // a set union) just add everything being added here to the Filter as well.
3126     return Filter.filterAndAdd(RS, VRegs);
3127   }
3128   using const_iterator = decltype(VRegs)::const_iterator;
3129   const_iterator begin() const { return VRegs.begin(); }
3130   const_iterator end() const { return VRegs.end(); }
3131   size_t size() const { return VRegs.size(); }
3132 };
3133 } // namespace
3134 
3135 // Calculate the largest possible vregsPassed sets. These are the registers that
3136 // can pass through an MBB live, but may not be live every time. It is assumed
3137 // that all vregsPassed sets are empty before the call.
3138 void MachineVerifier::calcRegsPassed() {
3139   if (MF->empty())
3140     // ReversePostOrderTraversal doesn't handle empty functions.
3141     return;
3142 
3143   for (const MachineBasicBlock *MB :
3144        ReversePostOrderTraversal<const MachineFunction *>(MF)) {
3145     FilteringVRegSet VRegs;
3146     BBInfo &Info = MBBInfoMap[MB];
3147     assert(Info.reachable);
3148 
3149     VRegs.addToFilter(Info.regsKilled);
3150     VRegs.addToFilter(Info.regsLiveOut);
3151     for (const MachineBasicBlock *Pred : MB->predecessors()) {
3152       const BBInfo &PredInfo = MBBInfoMap[Pred];
3153       if (!PredInfo.reachable)
3154         continue;
3155 
3156       VRegs.add(PredInfo.regsLiveOut);
3157       VRegs.add(PredInfo.vregsPassed);
3158     }
3159     Info.vregsPassed.reserve(VRegs.size());
3160     Info.vregsPassed.insert(VRegs.begin(), VRegs.end());
3161   }
3162 }
3163 
3164 // Calculate the set of virtual registers that must be passed through each basic
3165 // block in order to satisfy the requirements of successor blocks. This is very
3166 // similar to calcRegsPassed, only backwards.
3167 void MachineVerifier::calcRegsRequired() {
3168   // First push live-in regs to predecessors' vregsRequired.
3169   SmallPtrSet<const MachineBasicBlock*, 8> todo;
3170   for (const auto &MBB : *MF) {
3171     BBInfo &MInfo = MBBInfoMap[&MBB];
3172     for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3173       BBInfo &PInfo = MBBInfoMap[Pred];
3174       if (PInfo.addRequired(MInfo.vregsLiveIn))
3175         todo.insert(Pred);
3176     }
3177 
3178     // Handle the PHI node.
3179     for (const MachineInstr &MI : MBB.phis()) {
3180       for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
3181         // Skip those Operands which are undef regs or not regs.
3182         if (!MI.getOperand(i).isReg() || !MI.getOperand(i).readsReg())
3183           continue;
3184 
3185         // Get register and predecessor for one PHI edge.
3186         Register Reg = MI.getOperand(i).getReg();
3187         const MachineBasicBlock *Pred = MI.getOperand(i + 1).getMBB();
3188 
3189         BBInfo &PInfo = MBBInfoMap[Pred];
3190         if (PInfo.addRequired(Reg))
3191           todo.insert(Pred);
3192       }
3193     }
3194   }
3195 
3196   // Iteratively push vregsRequired to predecessors. This will converge to the
3197   // same final state regardless of DenseSet iteration order.
3198   while (!todo.empty()) {
3199     const MachineBasicBlock *MBB = *todo.begin();
3200     todo.erase(MBB);
3201     BBInfo &MInfo = MBBInfoMap[MBB];
3202     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
3203       if (Pred == MBB)
3204         continue;
3205       BBInfo &SInfo = MBBInfoMap[Pred];
3206       if (SInfo.addRequired(MInfo.vregsRequired))
3207         todo.insert(Pred);
3208     }
3209   }
3210 }
3211 
3212 // Check PHI instructions at the beginning of MBB. It is assumed that
3213 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
3214 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
3215   BBInfo &MInfo = MBBInfoMap[&MBB];
3216 
3217   SmallPtrSet<const MachineBasicBlock*, 8> seen;
3218   for (const MachineInstr &Phi : MBB) {
3219     if (!Phi.isPHI())
3220       break;
3221     seen.clear();
3222 
3223     const MachineOperand &MODef = Phi.getOperand(0);
3224     if (!MODef.isReg() || !MODef.isDef()) {
3225       report("Expected first PHI operand to be a register def", &MODef, 0);
3226       continue;
3227     }
3228     if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
3229         MODef.isEarlyClobber() || MODef.isDebug())
3230       report("Unexpected flag on PHI operand", &MODef, 0);
3231     Register DefReg = MODef.getReg();
3232     if (!DefReg.isVirtual())
3233       report("Expected first PHI operand to be a virtual register", &MODef, 0);
3234 
3235     for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
3236       const MachineOperand &MO0 = Phi.getOperand(I);
3237       if (!MO0.isReg()) {
3238         report("Expected PHI operand to be a register", &MO0, I);
3239         continue;
3240       }
3241       if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
3242           MO0.isDebug() || MO0.isTied())
3243         report("Unexpected flag on PHI operand", &MO0, I);
3244 
3245       const MachineOperand &MO1 = Phi.getOperand(I + 1);
3246       if (!MO1.isMBB()) {
3247         report("Expected PHI operand to be a basic block", &MO1, I + 1);
3248         continue;
3249       }
3250 
3251       const MachineBasicBlock &Pre = *MO1.getMBB();
3252       if (!Pre.isSuccessor(&MBB)) {
3253         report("PHI input is not a predecessor block", &MO1, I + 1);
3254         continue;
3255       }
3256 
3257       if (MInfo.reachable) {
3258         seen.insert(&Pre);
3259         BBInfo &PrInfo = MBBInfoMap[&Pre];
3260         if (!MO0.isUndef() && PrInfo.reachable &&
3261             !PrInfo.isLiveOut(MO0.getReg()))
3262           report("PHI operand is not live-out from predecessor", &MO0, I);
3263       }
3264     }
3265 
3266     // Did we see all predecessors?
3267     if (MInfo.reachable) {
3268       for (MachineBasicBlock *Pred : MBB.predecessors()) {
3269         if (!seen.count(Pred)) {
3270           report("Missing PHI operand", &Phi);
3271           errs() << printMBBReference(*Pred)
3272                  << " is a predecessor according to the CFG.\n";
3273         }
3274       }
3275     }
3276   }
3277 }
3278 
3279 static void
3280 verifyConvergenceControl(const MachineFunction &MF, MachineDominatorTree &DT,
3281                          std::function<void(const Twine &Message)> FailureCB) {
3282   MachineConvergenceVerifier CV;
3283   CV.initialize(&errs(), FailureCB, MF);
3284 
3285   for (const auto &MBB : MF) {
3286     CV.visit(MBB);
3287     for (const auto &MI : MBB.instrs())
3288       CV.visit(MI);
3289   }
3290 
3291   if (CV.sawTokens()) {
3292     DT.recalculate(const_cast<MachineFunction &>(MF));
3293     CV.verify(DT);
3294   }
3295 }
3296 
3297 void MachineVerifier::visitMachineFunctionAfter() {
3298   auto FailureCB = [this](const Twine &Message) {
3299     report(Message.str().c_str(), MF);
3300   };
3301   verifyConvergenceControl(*MF, DT, FailureCB);
3302 
3303   calcRegsPassed();
3304 
3305   for (const MachineBasicBlock &MBB : *MF)
3306     checkPHIOps(MBB);
3307 
3308   // Now check liveness info if available
3309   calcRegsRequired();
3310 
3311   // Check for killed virtual registers that should be live out.
3312   for (const auto &MBB : *MF) {
3313     BBInfo &MInfo = MBBInfoMap[&MBB];
3314     for (Register VReg : MInfo.vregsRequired)
3315       if (MInfo.regsKilled.count(VReg)) {
3316         report("Virtual register killed in block, but needed live out.", &MBB);
3317         errs() << "Virtual register " << printReg(VReg)
3318                << " is used after the block.\n";
3319       }
3320   }
3321 
3322   if (!MF->empty()) {
3323     BBInfo &MInfo = MBBInfoMap[&MF->front()];
3324     for (Register VReg : MInfo.vregsRequired) {
3325       report("Virtual register defs don't dominate all uses.", MF);
3326       report_context_vreg(VReg);
3327     }
3328   }
3329 
3330   if (LiveVars)
3331     verifyLiveVariables();
3332   if (LiveInts)
3333     verifyLiveIntervals();
3334 
3335   // Check live-in list of each MBB. If a register is live into MBB, check
3336   // that the register is in regsLiveOut of each predecessor block. Since
3337   // this must come from a definition in the predecesssor or its live-in
3338   // list, this will catch a live-through case where the predecessor does not
3339   // have the register in its live-in list.  This currently only checks
3340   // registers that have no aliases, are not allocatable and are not
3341   // reserved, which could mean a condition code register for instance.
3342   if (MRI->tracksLiveness())
3343     for (const auto &MBB : *MF)
3344       for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
3345         MCPhysReg LiveInReg = P.PhysReg;
3346         bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid();
3347         if (hasAliases || isAllocatable(LiveInReg) || isReserved(LiveInReg))
3348           continue;
3349         for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3350           BBInfo &PInfo = MBBInfoMap[Pred];
3351           if (!PInfo.regsLiveOut.count(LiveInReg)) {
3352             report("Live in register not found to be live out from predecessor.",
3353                    &MBB);
3354             errs() << TRI->getName(LiveInReg)
3355                    << " not found to be live out from "
3356                    << printMBBReference(*Pred) << "\n";
3357           }
3358         }
3359       }
3360 
3361   for (auto CSInfo : MF->getCallSitesInfo())
3362     if (!CSInfo.first->isCall())
3363       report("Call site info referencing instruction that is not call", MF);
3364 
3365   // If there's debug-info, check that we don't have any duplicate value
3366   // tracking numbers.
3367   if (MF->getFunction().getSubprogram()) {
3368     DenseSet<unsigned> SeenNumbers;
3369     for (const auto &MBB : *MF) {
3370       for (const auto &MI : MBB) {
3371         if (auto Num = MI.peekDebugInstrNum()) {
3372           auto Result = SeenNumbers.insert((unsigned)Num);
3373           if (!Result.second)
3374             report("Instruction has a duplicated value tracking number", &MI);
3375         }
3376       }
3377     }
3378   }
3379 }
3380 
3381 void MachineVerifier::verifyLiveVariables() {
3382   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
3383   for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
3384     Register Reg = Register::index2VirtReg(I);
3385     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
3386     for (const auto &MBB : *MF) {
3387       BBInfo &MInfo = MBBInfoMap[&MBB];
3388 
3389       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
3390       if (MInfo.vregsRequired.count(Reg)) {
3391         if (!VI.AliveBlocks.test(MBB.getNumber())) {
3392           report("LiveVariables: Block missing from AliveBlocks", &MBB);
3393           errs() << "Virtual register " << printReg(Reg)
3394                  << " must be live through the block.\n";
3395         }
3396       } else {
3397         if (VI.AliveBlocks.test(MBB.getNumber())) {
3398           report("LiveVariables: Block should not be in AliveBlocks", &MBB);
3399           errs() << "Virtual register " << printReg(Reg)
3400                  << " is not needed live through the block.\n";
3401         }
3402       }
3403     }
3404   }
3405 }
3406 
3407 void MachineVerifier::verifyLiveIntervals() {
3408   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
3409   for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
3410     Register Reg = Register::index2VirtReg(I);
3411 
3412     // Spilling and splitting may leave unused registers around. Skip them.
3413     if (MRI->reg_nodbg_empty(Reg))
3414       continue;
3415 
3416     if (!LiveInts->hasInterval(Reg)) {
3417       report("Missing live interval for virtual register", MF);
3418       errs() << printReg(Reg, TRI) << " still has defs or uses\n";
3419       continue;
3420     }
3421 
3422     const LiveInterval &LI = LiveInts->getInterval(Reg);
3423     assert(Reg == LI.reg() && "Invalid reg to interval mapping");
3424     verifyLiveInterval(LI);
3425   }
3426 
3427   // Verify all the cached regunit intervals.
3428   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
3429     if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
3430       verifyLiveRange(*LR, i);
3431 }
3432 
3433 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
3434                                            const VNInfo *VNI, Register Reg,
3435                                            LaneBitmask LaneMask) {
3436   if (VNI->isUnused())
3437     return;
3438 
3439   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
3440 
3441   if (!DefVNI) {
3442     report("Value not live at VNInfo def and not marked unused", MF);
3443     report_context(LR, Reg, LaneMask);
3444     report_context(*VNI);
3445     return;
3446   }
3447 
3448   if (DefVNI != VNI) {
3449     report("Live segment at def has different VNInfo", MF);
3450     report_context(LR, Reg, LaneMask);
3451     report_context(*VNI);
3452     return;
3453   }
3454 
3455   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
3456   if (!MBB) {
3457     report("Invalid VNInfo definition index", MF);
3458     report_context(LR, Reg, LaneMask);
3459     report_context(*VNI);
3460     return;
3461   }
3462 
3463   if (VNI->isPHIDef()) {
3464     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
3465       report("PHIDef VNInfo is not defined at MBB start", MBB);
3466       report_context(LR, Reg, LaneMask);
3467       report_context(*VNI);
3468     }
3469     return;
3470   }
3471 
3472   // Non-PHI def.
3473   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
3474   if (!MI) {
3475     report("No instruction at VNInfo def index", MBB);
3476     report_context(LR, Reg, LaneMask);
3477     report_context(*VNI);
3478     return;
3479   }
3480 
3481   if (Reg != 0) {
3482     bool hasDef = false;
3483     bool isEarlyClobber = false;
3484     for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3485       if (!MOI->isReg() || !MOI->isDef())
3486         continue;
3487       if (Reg.isVirtual()) {
3488         if (MOI->getReg() != Reg)
3489           continue;
3490       } else {
3491         if (!MOI->getReg().isPhysical() || !TRI->hasRegUnit(MOI->getReg(), Reg))
3492           continue;
3493       }
3494       if (LaneMask.any() &&
3495           (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
3496         continue;
3497       hasDef = true;
3498       if (MOI->isEarlyClobber())
3499         isEarlyClobber = true;
3500     }
3501 
3502     if (!hasDef) {
3503       report("Defining instruction does not modify register", MI);
3504       report_context(LR, Reg, LaneMask);
3505       report_context(*VNI);
3506     }
3507 
3508     // Early clobber defs begin at USE slots, but other defs must begin at
3509     // DEF slots.
3510     if (isEarlyClobber) {
3511       if (!VNI->def.isEarlyClobber()) {
3512         report("Early clobber def must be at an early-clobber slot", MBB);
3513         report_context(LR, Reg, LaneMask);
3514         report_context(*VNI);
3515       }
3516     } else if (!VNI->def.isRegister()) {
3517       report("Non-PHI, non-early clobber def must be at a register slot", MBB);
3518       report_context(LR, Reg, LaneMask);
3519       report_context(*VNI);
3520     }
3521   }
3522 }
3523 
3524 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
3525                                              const LiveRange::const_iterator I,
3526                                              Register Reg,
3527                                              LaneBitmask LaneMask) {
3528   const LiveRange::Segment &S = *I;
3529   const VNInfo *VNI = S.valno;
3530   assert(VNI && "Live segment has no valno");
3531 
3532   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
3533     report("Foreign valno in live segment", MF);
3534     report_context(LR, Reg, LaneMask);
3535     report_context(S);
3536     report_context(*VNI);
3537   }
3538 
3539   if (VNI->isUnused()) {
3540     report("Live segment valno is marked unused", MF);
3541     report_context(LR, Reg, LaneMask);
3542     report_context(S);
3543   }
3544 
3545   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
3546   if (!MBB) {
3547     report("Bad start of live segment, no basic block", MF);
3548     report_context(LR, Reg, LaneMask);
3549     report_context(S);
3550     return;
3551   }
3552   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
3553   if (S.start != MBBStartIdx && S.start != VNI->def) {
3554     report("Live segment must begin at MBB entry or valno def", MBB);
3555     report_context(LR, Reg, LaneMask);
3556     report_context(S);
3557   }
3558 
3559   const MachineBasicBlock *EndMBB =
3560     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
3561   if (!EndMBB) {
3562     report("Bad end of live segment, no basic block", MF);
3563     report_context(LR, Reg, LaneMask);
3564     report_context(S);
3565     return;
3566   }
3567 
3568   // Checks for non-live-out segments.
3569   if (S.end != LiveInts->getMBBEndIdx(EndMBB)) {
3570     // RegUnit intervals are allowed dead phis.
3571     if (!Reg.isVirtual() && VNI->isPHIDef() && S.start == VNI->def &&
3572         S.end == VNI->def.getDeadSlot())
3573       return;
3574 
3575     // The live segment is ending inside EndMBB
3576     const MachineInstr *MI =
3577         LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
3578     if (!MI) {
3579       report("Live segment doesn't end at a valid instruction", EndMBB);
3580       report_context(LR, Reg, LaneMask);
3581       report_context(S);
3582       return;
3583     }
3584 
3585     // The block slot must refer to a basic block boundary.
3586     if (S.end.isBlock()) {
3587       report("Live segment ends at B slot of an instruction", EndMBB);
3588       report_context(LR, Reg, LaneMask);
3589       report_context(S);
3590     }
3591 
3592     if (S.end.isDead()) {
3593       // Segment ends on the dead slot.
3594       // That means there must be a dead def.
3595       if (!SlotIndex::isSameInstr(S.start, S.end)) {
3596         report("Live segment ending at dead slot spans instructions", EndMBB);
3597         report_context(LR, Reg, LaneMask);
3598         report_context(S);
3599       }
3600     }
3601 
3602     // After tied operands are rewritten, a live segment can only end at an
3603     // early-clobber slot if it is being redefined by an early-clobber def.
3604     // TODO: Before tied operands are rewritten, a live segment can only end at
3605     // an early-clobber slot if the last use is tied to an early-clobber def.
3606     if (MF->getProperties().hasProperty(
3607             MachineFunctionProperties::Property::TiedOpsRewritten) &&
3608         S.end.isEarlyClobber()) {
3609       if (I + 1 == LR.end() || (I + 1)->start != S.end) {
3610         report("Live segment ending at early clobber slot must be "
3611                "redefined by an EC def in the same instruction",
3612                EndMBB);
3613         report_context(LR, Reg, LaneMask);
3614         report_context(S);
3615       }
3616     }
3617 
3618     // The following checks only apply to virtual registers. Physreg liveness
3619     // is too weird to check.
3620     if (Reg.isVirtual()) {
3621       // A live segment can end with either a redefinition, a kill flag on a
3622       // use, or a dead flag on a def.
3623       bool hasRead = false;
3624       bool hasSubRegDef = false;
3625       bool hasDeadDef = false;
3626       for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3627         if (!MOI->isReg() || MOI->getReg() != Reg)
3628           continue;
3629         unsigned Sub = MOI->getSubReg();
3630         LaneBitmask SLM =
3631             Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub) : LaneBitmask::getAll();
3632         if (MOI->isDef()) {
3633           if (Sub != 0) {
3634             hasSubRegDef = true;
3635             // An operand %0:sub0 reads %0:sub1..n. Invert the lane
3636             // mask for subregister defs. Read-undef defs will be handled by
3637             // readsReg below.
3638             SLM = ~SLM;
3639           }
3640           if (MOI->isDead())
3641             hasDeadDef = true;
3642         }
3643         if (LaneMask.any() && (LaneMask & SLM).none())
3644           continue;
3645         if (MOI->readsReg())
3646           hasRead = true;
3647       }
3648       if (S.end.isDead()) {
3649         // Make sure that the corresponding machine operand for a "dead" live
3650         // range has the dead flag. We cannot perform this check for subregister
3651         // liveranges as partially dead values are allowed.
3652         if (LaneMask.none() && !hasDeadDef) {
3653           report(
3654               "Instruction ending live segment on dead slot has no dead flag",
3655               MI);
3656           report_context(LR, Reg, LaneMask);
3657           report_context(S);
3658         }
3659       } else {
3660         if (!hasRead) {
3661           // When tracking subregister liveness, the main range must start new
3662           // values on partial register writes, even if there is no read.
3663           if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
3664               !hasSubRegDef) {
3665             report("Instruction ending live segment doesn't read the register",
3666                    MI);
3667             report_context(LR, Reg, LaneMask);
3668             report_context(S);
3669           }
3670         }
3671       }
3672     }
3673   }
3674 
3675   // Now check all the basic blocks in this live segment.
3676   MachineFunction::const_iterator MFI = MBB->getIterator();
3677   // Is this live segment the beginning of a non-PHIDef VN?
3678   if (S.start == VNI->def && !VNI->isPHIDef()) {
3679     // Not live-in to any blocks.
3680     if (MBB == EndMBB)
3681       return;
3682     // Skip this block.
3683     ++MFI;
3684   }
3685 
3686   SmallVector<SlotIndex, 4> Undefs;
3687   if (LaneMask.any()) {
3688     LiveInterval &OwnerLI = LiveInts->getInterval(Reg);
3689     OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
3690   }
3691 
3692   while (true) {
3693     assert(LiveInts->isLiveInToMBB(LR, &*MFI));
3694     // We don't know how to track physregs into a landing pad.
3695     if (!Reg.isVirtual() && MFI->isEHPad()) {
3696       if (&*MFI == EndMBB)
3697         break;
3698       ++MFI;
3699       continue;
3700     }
3701 
3702     // Is VNI a PHI-def in the current block?
3703     bool IsPHI = VNI->isPHIDef() &&
3704       VNI->def == LiveInts->getMBBStartIdx(&*MFI);
3705 
3706     // Check that VNI is live-out of all predecessors.
3707     for (const MachineBasicBlock *Pred : MFI->predecessors()) {
3708       SlotIndex PEnd = LiveInts->getMBBEndIdx(Pred);
3709       // Predecessor of landing pad live-out on last call.
3710       if (MFI->isEHPad()) {
3711         for (const MachineInstr &MI : llvm::reverse(*Pred)) {
3712           if (MI.isCall()) {
3713             PEnd = Indexes->getInstructionIndex(MI).getBoundaryIndex();
3714             break;
3715           }
3716         }
3717       }
3718       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
3719 
3720       // All predecessors must have a live-out value. However for a phi
3721       // instruction with subregister intervals
3722       // only one of the subregisters (not necessarily the current one) needs to
3723       // be defined.
3724       if (!PVNI && (LaneMask.none() || !IsPHI)) {
3725         if (LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes))
3726           continue;
3727         report("Register not marked live out of predecessor", Pred);
3728         report_context(LR, Reg, LaneMask);
3729         report_context(*VNI);
3730         errs() << " live into " << printMBBReference(*MFI) << '@'
3731                << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
3732                << PEnd << '\n';
3733         continue;
3734       }
3735 
3736       // Only PHI-defs can take different predecessor values.
3737       if (!IsPHI && PVNI != VNI) {
3738         report("Different value live out of predecessor", Pred);
3739         report_context(LR, Reg, LaneMask);
3740         errs() << "Valno #" << PVNI->id << " live out of "
3741                << printMBBReference(*Pred) << '@' << PEnd << "\nValno #"
3742                << VNI->id << " live into " << printMBBReference(*MFI) << '@'
3743                << LiveInts->getMBBStartIdx(&*MFI) << '\n';
3744       }
3745     }
3746     if (&*MFI == EndMBB)
3747       break;
3748     ++MFI;
3749   }
3750 }
3751 
3752 void MachineVerifier::verifyLiveRange(const LiveRange &LR, Register Reg,
3753                                       LaneBitmask LaneMask) {
3754   for (const VNInfo *VNI : LR.valnos)
3755     verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
3756 
3757   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
3758     verifyLiveRangeSegment(LR, I, Reg, LaneMask);
3759 }
3760 
3761 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
3762   Register Reg = LI.reg();
3763   assert(Reg.isVirtual());
3764   verifyLiveRange(LI, Reg);
3765 
3766   if (LI.hasSubRanges()) {
3767     LaneBitmask Mask;
3768     LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
3769     for (const LiveInterval::SubRange &SR : LI.subranges()) {
3770       if ((Mask & SR.LaneMask).any()) {
3771         report("Lane masks of sub ranges overlap in live interval", MF);
3772         report_context(LI);
3773       }
3774       if ((SR.LaneMask & ~MaxMask).any()) {
3775         report("Subrange lanemask is invalid", MF);
3776         report_context(LI);
3777       }
3778       if (SR.empty()) {
3779         report("Subrange must not be empty", MF);
3780         report_context(SR, LI.reg(), SR.LaneMask);
3781       }
3782       Mask |= SR.LaneMask;
3783       verifyLiveRange(SR, LI.reg(), SR.LaneMask);
3784       if (!LI.covers(SR)) {
3785         report("A Subrange is not covered by the main range", MF);
3786         report_context(LI);
3787       }
3788     }
3789   }
3790 
3791   // Check the LI only has one connected component.
3792   ConnectedVNInfoEqClasses ConEQ(*LiveInts);
3793   unsigned NumComp = ConEQ.Classify(LI);
3794   if (NumComp > 1) {
3795     report("Multiple connected components in live interval", MF);
3796     report_context(LI);
3797     for (unsigned comp = 0; comp != NumComp; ++comp) {
3798       errs() << comp << ": valnos";
3799       for (const VNInfo *I : LI.valnos)
3800         if (comp == ConEQ.getEqClass(I))
3801           errs() << ' ' << I->id;
3802       errs() << '\n';
3803     }
3804   }
3805 }
3806 
3807 namespace {
3808 
3809   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
3810   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
3811   // value is zero.
3812   // We use a bool plus an integer to capture the stack state.
3813   struct StackStateOfBB {
3814     StackStateOfBB() = default;
3815     StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
3816       EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
3817       ExitIsSetup(ExitSetup) {}
3818 
3819     // Can be negative, which means we are setting up a frame.
3820     int EntryValue = 0;
3821     int ExitValue = 0;
3822     bool EntryIsSetup = false;
3823     bool ExitIsSetup = false;
3824   };
3825 
3826 } // end anonymous namespace
3827 
3828 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
3829 /// by a FrameDestroy <n>, stack adjustments are identical on all
3830 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
3831 void MachineVerifier::verifyStackFrame() {
3832   unsigned FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
3833   unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
3834   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
3835     return;
3836 
3837   SmallVector<StackStateOfBB, 8> SPState;
3838   SPState.resize(MF->getNumBlockIDs());
3839   df_iterator_default_set<const MachineBasicBlock*> Reachable;
3840 
3841   // Visit the MBBs in DFS order.
3842   for (df_ext_iterator<const MachineFunction *,
3843                        df_iterator_default_set<const MachineBasicBlock *>>
3844        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
3845        DFI != DFE; ++DFI) {
3846     const MachineBasicBlock *MBB = *DFI;
3847 
3848     StackStateOfBB BBState;
3849     // Check the exit state of the DFS stack predecessor.
3850     if (DFI.getPathLength() >= 2) {
3851       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
3852       assert(Reachable.count(StackPred) &&
3853              "DFS stack predecessor is already visited.\n");
3854       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
3855       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
3856       BBState.ExitValue = BBState.EntryValue;
3857       BBState.ExitIsSetup = BBState.EntryIsSetup;
3858     }
3859 
3860     if ((int)MBB->getCallFrameSize() != -BBState.EntryValue) {
3861       report("Call frame size on entry does not match value computed from "
3862              "predecessor",
3863              MBB);
3864       errs() << "Call frame size on entry " << MBB->getCallFrameSize()
3865              << " does not match value computed from predecessor "
3866              << -BBState.EntryValue << '\n';
3867     }
3868 
3869     // Update stack state by checking contents of MBB.
3870     for (const auto &I : *MBB) {
3871       if (I.getOpcode() == FrameSetupOpcode) {
3872         if (BBState.ExitIsSetup)
3873           report("FrameSetup is after another FrameSetup", &I);
3874         if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
3875           report("AdjustsStack not set in presence of a frame pseudo "
3876                  "instruction.", &I);
3877         BBState.ExitValue -= TII->getFrameTotalSize(I);
3878         BBState.ExitIsSetup = true;
3879       }
3880 
3881       if (I.getOpcode() == FrameDestroyOpcode) {
3882         int Size = TII->getFrameTotalSize(I);
3883         if (!BBState.ExitIsSetup)
3884           report("FrameDestroy is not after a FrameSetup", &I);
3885         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
3886                                                BBState.ExitValue;
3887         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
3888           report("FrameDestroy <n> is after FrameSetup <m>", &I);
3889           errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
3890               << AbsSPAdj << ">.\n";
3891         }
3892         if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
3893           report("AdjustsStack not set in presence of a frame pseudo "
3894                  "instruction.", &I);
3895         BBState.ExitValue += Size;
3896         BBState.ExitIsSetup = false;
3897       }
3898     }
3899     SPState[MBB->getNumber()] = BBState;
3900 
3901     // Make sure the exit state of any predecessor is consistent with the entry
3902     // state.
3903     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
3904       if (Reachable.count(Pred) &&
3905           (SPState[Pred->getNumber()].ExitValue != BBState.EntryValue ||
3906            SPState[Pred->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
3907         report("The exit stack state of a predecessor is inconsistent.", MBB);
3908         errs() << "Predecessor " << printMBBReference(*Pred)
3909                << " has exit state (" << SPState[Pred->getNumber()].ExitValue
3910                << ", " << SPState[Pred->getNumber()].ExitIsSetup << "), while "
3911                << printMBBReference(*MBB) << " has entry state ("
3912                << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
3913       }
3914     }
3915 
3916     // Make sure the entry state of any successor is consistent with the exit
3917     // state.
3918     for (const MachineBasicBlock *Succ : MBB->successors()) {
3919       if (Reachable.count(Succ) &&
3920           (SPState[Succ->getNumber()].EntryValue != BBState.ExitValue ||
3921            SPState[Succ->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
3922         report("The entry stack state of a successor is inconsistent.", MBB);
3923         errs() << "Successor " << printMBBReference(*Succ)
3924                << " has entry state (" << SPState[Succ->getNumber()].EntryValue
3925                << ", " << SPState[Succ->getNumber()].EntryIsSetup << "), while "
3926                << printMBBReference(*MBB) << " has exit state ("
3927                << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
3928       }
3929     }
3930 
3931     // Make sure a basic block with return ends with zero stack adjustment.
3932     if (!MBB->empty() && MBB->back().isReturn()) {
3933       if (BBState.ExitIsSetup)
3934         report("A return block ends with a FrameSetup.", MBB);
3935       if (BBState.ExitValue)
3936         report("A return block ends with a nonzero stack adjustment.", MBB);
3937     }
3938   }
3939 }
3940