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