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