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