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