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