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