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