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