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