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