e291ea52aa4d14411484bb2850deb1db6a564481
[oota-llvm.git] / lib / CodeGen / MachineVerifier.cpp
1 //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Pass to verify generated machine code. The following is checked:
11 //
12 // Operand counts: All explicit operands must be present.
13 //
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
16 //
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
19 //
20 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
21 // command-line option -verify-machineinstrs, or by defining the environment
22 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
23 // the verifier errors.
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/SetOperations.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Analysis/LibCallSemantics.h"
32 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
33 #include "llvm/CodeGen/LiveStackAnalysis.h"
34 #include "llvm/CodeGen/LiveVariables.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunctionPass.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/InlineAsm.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
50 #include "llvm/Target/TargetSubtargetInfo.h"
51 using namespace llvm;
52
53 namespace {
54   struct MachineVerifier {
55
56     MachineVerifier(Pass *pass, const char *b) :
57       PASS(pass),
58       Banner(b)
59       {}
60
61     bool runOnMachineFunction(MachineFunction &MF);
62
63     Pass *const PASS;
64     const char *Banner;
65     const MachineFunction *MF;
66     const TargetMachine *TM;
67     const TargetInstrInfo *TII;
68     const TargetRegisterInfo *TRI;
69     const MachineRegisterInfo *MRI;
70
71     unsigned foundErrors;
72
73     typedef SmallVector<unsigned, 16> RegVector;
74     typedef SmallVector<const uint32_t*, 4> RegMaskVector;
75     typedef DenseSet<unsigned> RegSet;
76     typedef DenseMap<unsigned, const MachineInstr*> RegMap;
77     typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet;
78
79     const MachineInstr *FirstTerminator;
80     BlockSet FunctionBlocks;
81
82     BitVector regsReserved;
83     RegSet regsLive;
84     RegVector regsDefined, regsDead, regsKilled;
85     RegMaskVector regMasks;
86     RegSet regsLiveInButUnused;
87
88     SlotIndex lastIndex;
89
90     // Add Reg and any sub-registers to RV
91     void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
92       RV.push_back(Reg);
93       if (TargetRegisterInfo::isPhysicalRegister(Reg))
94         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
95           RV.push_back(*SubRegs);
96     }
97
98     struct BBInfo {
99       // Is this MBB reachable from the MF entry point?
100       bool reachable;
101
102       // Vregs that must be live in because they are used without being
103       // defined. Map value is the user.
104       RegMap vregsLiveIn;
105
106       // Regs killed in MBB. They may be defined again, and will then be in both
107       // regsKilled and regsLiveOut.
108       RegSet regsKilled;
109
110       // Regs defined in MBB and live out. Note that vregs passing through may
111       // be live out without being mentioned here.
112       RegSet regsLiveOut;
113
114       // Vregs that pass through MBB untouched. This set is disjoint from
115       // regsKilled and regsLiveOut.
116       RegSet vregsPassed;
117
118       // Vregs that must pass through MBB because they are needed by a successor
119       // block. This set is disjoint from regsLiveOut.
120       RegSet vregsRequired;
121
122       // Set versions of block's predecessor and successor lists.
123       BlockSet Preds, Succs;
124
125       BBInfo() : reachable(false) {}
126
127       // Add register to vregsPassed if it belongs there. Return true if
128       // anything changed.
129       bool addPassed(unsigned Reg) {
130         if (!TargetRegisterInfo::isVirtualRegister(Reg))
131           return false;
132         if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
133           return false;
134         return vregsPassed.insert(Reg).second;
135       }
136
137       // Same for a full set.
138       bool addPassed(const RegSet &RS) {
139         bool changed = false;
140         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
141           if (addPassed(*I))
142             changed = true;
143         return changed;
144       }
145
146       // Add register to vregsRequired if it belongs there. Return true if
147       // anything changed.
148       bool addRequired(unsigned Reg) {
149         if (!TargetRegisterInfo::isVirtualRegister(Reg))
150           return false;
151         if (regsLiveOut.count(Reg))
152           return false;
153         return vregsRequired.insert(Reg).second;
154       }
155
156       // Same for a full set.
157       bool addRequired(const RegSet &RS) {
158         bool changed = false;
159         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
160           if (addRequired(*I))
161             changed = true;
162         return changed;
163       }
164
165       // Same for a full map.
166       bool addRequired(const RegMap &RM) {
167         bool changed = false;
168         for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
169           if (addRequired(I->first))
170             changed = true;
171         return changed;
172       }
173
174       // Live-out registers are either in regsLiveOut or vregsPassed.
175       bool isLiveOut(unsigned Reg) const {
176         return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
177       }
178     };
179
180     // Extra register info per MBB.
181     DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
182
183     bool isReserved(unsigned Reg) {
184       return Reg < regsReserved.size() && regsReserved.test(Reg);
185     }
186
187     bool isAllocatable(unsigned Reg) {
188       return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg);
189     }
190
191     // Analysis information if available
192     LiveVariables *LiveVars;
193     LiveIntervals *LiveInts;
194     LiveStacks *LiveStks;
195     SlotIndexes *Indexes;
196
197     void visitMachineFunctionBefore();
198     void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
199     void visitMachineBundleBefore(const MachineInstr *MI);
200     void visitMachineInstrBefore(const MachineInstr *MI);
201     void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
202     void visitMachineInstrAfter(const MachineInstr *MI);
203     void visitMachineBundleAfter(const MachineInstr *MI);
204     void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
205     void visitMachineFunctionAfter();
206
207     template <typename T> void report(const char *msg, ilist_iterator<T> I) {
208       report(msg, &*I);
209     }
210     void report(const char *msg, const MachineFunction *MF);
211     void report(const char *msg, const MachineBasicBlock *MBB);
212     void report(const char *msg, const MachineInstr *MI);
213     void report(const char *msg, const MachineOperand *MO, unsigned MONum);
214     void report(const char *msg, const MachineFunction *MF,
215                 const LiveInterval &LI);
216     void report(const char *msg, const MachineBasicBlock *MBB,
217                 const LiveInterval &LI);
218     void report(const char *msg, const MachineFunction *MF,
219                 const LiveRange &LR, unsigned Reg, LaneBitmask LaneMask);
220     void report(const char *msg, const MachineBasicBlock *MBB,
221                 const LiveRange &LR, unsigned Reg, LaneBitmask LaneMask);
222
223     void verifyInlineAsm(const MachineInstr *MI);
224
225     void checkLiveness(const MachineOperand *MO, unsigned MONum);
226     void markReachable(const MachineBasicBlock *MBB);
227     void calcRegsPassed();
228     void checkPHIOps(const MachineBasicBlock *MBB);
229
230     void calcRegsRequired();
231     void verifyLiveVariables();
232     void verifyLiveIntervals();
233     void verifyLiveInterval(const LiveInterval&);
234     void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned,
235                               unsigned);
236     void verifyLiveRangeSegment(const LiveRange&,
237                                 const LiveRange::const_iterator I, unsigned,
238                                 unsigned);
239     void verifyLiveRange(const LiveRange&, unsigned, LaneBitmask LaneMask = 0);
240
241     void verifyStackFrame();
242
243     void verifySlotIndexes() const;
244   };
245
246   struct MachineVerifierPass : public MachineFunctionPass {
247     static char ID; // Pass ID, replacement for typeid
248     const std::string Banner;
249
250     MachineVerifierPass(const std::string &banner = nullptr)
251       : MachineFunctionPass(ID), Banner(banner) {
252         initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
253       }
254
255     void getAnalysisUsage(AnalysisUsage &AU) const override {
256       AU.setPreservesAll();
257       MachineFunctionPass::getAnalysisUsage(AU);
258     }
259
260     bool runOnMachineFunction(MachineFunction &MF) override {
261       MF.verify(this, Banner.c_str());
262       return false;
263     }
264   };
265
266 }
267
268 char MachineVerifierPass::ID = 0;
269 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
270                 "Verify generated machine code", false, false)
271
272 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
273   return new MachineVerifierPass(Banner);
274 }
275
276 void MachineFunction::verify(Pass *p, const char *Banner) const {
277   MachineVerifier(p, Banner)
278     .runOnMachineFunction(const_cast<MachineFunction&>(*this));
279 }
280
281 void MachineVerifier::verifySlotIndexes() const {
282   if (Indexes == nullptr)
283     return;
284
285   // Ensure the IdxMBB list is sorted by slot indexes.
286   SlotIndex Last;
287   for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
288        E = Indexes->MBBIndexEnd(); I != E; ++I) {
289     assert(!Last.isValid() || I->first > Last);
290     Last = I->first;
291   }
292 }
293
294 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
295   foundErrors = 0;
296
297   this->MF = &MF;
298   TM = &MF.getTarget();
299   TII = MF.getSubtarget().getInstrInfo();
300   TRI = MF.getSubtarget().getRegisterInfo();
301   MRI = &MF.getRegInfo();
302
303   LiveVars = nullptr;
304   LiveInts = nullptr;
305   LiveStks = nullptr;
306   Indexes = nullptr;
307   if (PASS) {
308     LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
309     // We don't want to verify LiveVariables if LiveIntervals is available.
310     if (!LiveInts)
311       LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
312     LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
313     Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
314   }
315
316   verifySlotIndexes();
317
318   visitMachineFunctionBefore();
319   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
320        MFI!=MFE; ++MFI) {
321     visitMachineBasicBlockBefore(&*MFI);
322     // Keep track of the current bundle header.
323     const MachineInstr *CurBundle = nullptr;
324     // Do we expect the next instruction to be part of the same bundle?
325     bool InBundle = false;
326
327     for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
328            MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
329       if (MBBI->getParent() != &*MFI) {
330         report("Bad instruction parent pointer", MFI);
331         errs() << "Instruction: " << *MBBI;
332         continue;
333       }
334
335       // Check for consistent bundle flags.
336       if (InBundle && !MBBI->isBundledWithPred())
337         report("Missing BundledPred flag, "
338                "BundledSucc was set on predecessor",
339                &*MBBI);
340       if (!InBundle && MBBI->isBundledWithPred())
341         report("BundledPred flag is set, "
342                "but BundledSucc not set on predecessor",
343                &*MBBI);
344
345       // Is this a bundle header?
346       if (!MBBI->isInsideBundle()) {
347         if (CurBundle)
348           visitMachineBundleAfter(CurBundle);
349         CurBundle = &*MBBI;
350         visitMachineBundleBefore(CurBundle);
351       } else if (!CurBundle)
352         report("No bundle header", MBBI);
353       visitMachineInstrBefore(&*MBBI);
354       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
355         const MachineInstr &MI = *MBBI;
356         const MachineOperand &Op = MI.getOperand(I);
357         if (Op.getParent() != &MI) {
358           // Make sure to use correct addOperand / RemoveOperand / ChangeTo
359           // functions when replacing operands of a MachineInstr.
360           report("Instruction has operand with wrong parent set", &MI);
361         }
362
363         visitMachineOperand(&Op, I);
364       }
365
366       visitMachineInstrAfter(&*MBBI);
367
368       // Was this the last bundled instruction?
369       InBundle = MBBI->isBundledWithSucc();
370     }
371     if (CurBundle)
372       visitMachineBundleAfter(CurBundle);
373     if (InBundle)
374       report("BundledSucc flag set on last instruction in block", &MFI->back());
375     visitMachineBasicBlockAfter(&*MFI);
376   }
377   visitMachineFunctionAfter();
378
379   if (foundErrors)
380     report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
381
382   // Clean up.
383   regsLive.clear();
384   regsDefined.clear();
385   regsDead.clear();
386   regsKilled.clear();
387   regMasks.clear();
388   regsLiveInButUnused.clear();
389   MBBInfoMap.clear();
390
391   return false;                 // no changes
392 }
393
394 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
395   assert(MF);
396   errs() << '\n';
397   if (!foundErrors++) {
398     if (Banner)
399       errs() << "# " << Banner << '\n';
400     if (LiveInts != nullptr)
401       LiveInts->print(errs());
402     else
403       MF->print(errs(), Indexes);
404   }
405   errs() << "*** Bad machine code: " << msg << " ***\n"
406       << "- function:    " << MF->getName() << "\n";
407 }
408
409 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
410   assert(MBB);
411   report(msg, MBB->getParent());
412   errs() << "- basic block: BB#" << MBB->getNumber()
413       << ' ' << MBB->getName()
414       << " (" << (const void*)MBB << ')';
415   if (Indexes)
416     errs() << " [" << Indexes->getMBBStartIdx(MBB)
417         << ';' <<  Indexes->getMBBEndIdx(MBB) << ')';
418   errs() << '\n';
419 }
420
421 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
422   assert(MI);
423   report(msg, MI->getParent());
424   errs() << "- instruction: ";
425   if (Indexes && Indexes->hasIndex(MI))
426     errs() << Indexes->getInstructionIndex(MI) << '\t';
427   MI->print(errs(), TM);
428 }
429
430 void MachineVerifier::report(const char *msg,
431                              const MachineOperand *MO, unsigned MONum) {
432   assert(MO);
433   report(msg, MO->getParent());
434   errs() << "- operand " << MONum << ":   ";
435   MO->print(errs(), TRI);
436   errs() << "\n";
437 }
438
439 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
440                              const LiveInterval &LI) {
441   report(msg, MF);
442   errs() << "- interval:    " << LI << '\n';
443 }
444
445 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
446                              const LiveInterval &LI) {
447   report(msg, MBB);
448   errs() << "- interval:    " << LI << '\n';
449 }
450
451 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
452                              const LiveRange &LR, unsigned Reg,
453                              LaneBitmask LaneMask) {
454   report(msg, MBB);
455   errs() << "- liverange:   " << LR << '\n';
456   errs() << "- register:    " << PrintReg(Reg, TRI) << '\n';
457   if (LaneMask != 0)
458     errs() << "- lanemask:    " << PrintLaneMask(LaneMask) << '\n';
459 }
460
461 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
462                              const LiveRange &LR, unsigned Reg,
463                              LaneBitmask LaneMask) {
464   report(msg, MF);
465   errs() << "- liverange:   " << LR << '\n';
466   errs() << "- register:    " << PrintReg(Reg, TRI) << '\n';
467   if (LaneMask != 0)
468     errs() << "- lanemask:    " << PrintLaneMask(LaneMask) << '\n';
469 }
470
471 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
472   BBInfo &MInfo = MBBInfoMap[MBB];
473   if (!MInfo.reachable) {
474     MInfo.reachable = true;
475     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
476            SuE = MBB->succ_end(); SuI != SuE; ++SuI)
477       markReachable(*SuI);
478   }
479 }
480
481 void MachineVerifier::visitMachineFunctionBefore() {
482   lastIndex = SlotIndex();
483   regsReserved = MRI->getReservedRegs();
484
485   // A sub-register of a reserved register is also reserved
486   for (int Reg = regsReserved.find_first(); Reg>=0;
487        Reg = regsReserved.find_next(Reg)) {
488     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
489       // FIXME: This should probably be:
490       // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register");
491       regsReserved.set(*SubRegs);
492     }
493   }
494
495   markReachable(&MF->front());
496
497   // Build a set of the basic blocks in the function.
498   FunctionBlocks.clear();
499   for (const auto &MBB : *MF) {
500     FunctionBlocks.insert(&MBB);
501     BBInfo &MInfo = MBBInfoMap[&MBB];
502
503     MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
504     if (MInfo.Preds.size() != MBB.pred_size())
505       report("MBB has duplicate entries in its predecessor list.", &MBB);
506
507     MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
508     if (MInfo.Succs.size() != MBB.succ_size())
509       report("MBB has duplicate entries in its successor list.", &MBB);
510   }
511
512   // Check that the register use lists are sane.
513   MRI->verifyUseLists();
514
515   verifyStackFrame();
516 }
517
518 // Does iterator point to a and b as the first two elements?
519 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
520                       const MachineBasicBlock *a, const MachineBasicBlock *b) {
521   if (*i == a)
522     return *++i == b;
523   if (*i == b)
524     return *++i == a;
525   return false;
526 }
527
528 void
529 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
530   FirstTerminator = nullptr;
531
532   if (MRI->isSSA()) {
533     // If this block has allocatable physical registers live-in, check that
534     // it is an entry block or landing pad.
535     for (const auto &LI : MBB->liveins()) {
536       if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
537           MBB != MBB->getParent()->begin()) {
538         report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
539       }
540     }
541   }
542
543   // Count the number of landing pad successors.
544   SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
545   for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
546        E = MBB->succ_end(); I != E; ++I) {
547     if ((*I)->isEHPad())
548       LandingPadSuccs.insert(*I);
549     if (!FunctionBlocks.count(*I))
550       report("MBB has successor that isn't part of the function.", MBB);
551     if (!MBBInfoMap[*I].Preds.count(MBB)) {
552       report("Inconsistent CFG", MBB);
553       errs() << "MBB is not in the predecessor list of the successor BB#"
554           << (*I)->getNumber() << ".\n";
555     }
556   }
557
558   // Check the predecessor list.
559   for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
560        E = MBB->pred_end(); I != E; ++I) {
561     if (!FunctionBlocks.count(*I))
562       report("MBB has predecessor that isn't part of the function.", MBB);
563     if (!MBBInfoMap[*I].Succs.count(MBB)) {
564       report("Inconsistent CFG", MBB);
565       errs() << "MBB is not in the successor list of the predecessor BB#"
566           << (*I)->getNumber() << ".\n";
567     }
568   }
569
570   const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
571   const BasicBlock *BB = MBB->getBasicBlock();
572   const Function *Fn = MF->getFunction();
573   if (LandingPadSuccs.size() > 1 &&
574       !(AsmInfo &&
575         AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
576         BB && isa<SwitchInst>(BB->getTerminator())) &&
577       !isFuncletEHPersonality(classifyEHPersonality(Fn->getPersonalityFn())))
578     report("MBB has more than one landing pad successor", MBB);
579
580   // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
581   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
582   SmallVector<MachineOperand, 4> Cond;
583   if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
584                           TBB, FBB, Cond)) {
585     // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
586     // check whether its answers match up with reality.
587     if (!TBB && !FBB) {
588       // Block falls through to its successor.
589       MachineFunction::const_iterator MBBI = MBB->getIterator();
590       ++MBBI;
591       if (MBBI == MF->end()) {
592         // It's possible that the block legitimately ends with a noreturn
593         // call or an unreachable, in which case it won't actually fall
594         // out the bottom of the function.
595       } else if (MBB->succ_size() == LandingPadSuccs.size()) {
596         // It's possible that the block legitimately ends with a noreturn
597         // call or an unreachable, in which case it won't actuall fall
598         // out of the block.
599       } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
600         report("MBB exits via unconditional fall-through but doesn't have "
601                "exactly one CFG successor!", MBB);
602       } else if (!MBB->isSuccessor(&*MBBI)) {
603         report("MBB exits via unconditional fall-through but its successor "
604                "differs from its CFG successor!", MBB);
605       }
606       if (!MBB->empty() && MBB->back().isBarrier() &&
607           !TII->isPredicated(&MBB->back())) {
608         report("MBB exits via unconditional fall-through but ends with a "
609                "barrier instruction!", MBB);
610       }
611       if (!Cond.empty()) {
612         report("MBB exits via unconditional fall-through but has a condition!",
613                MBB);
614       }
615     } else if (TBB && !FBB && Cond.empty()) {
616       // Block unconditionally branches somewhere.
617       // If the block has exactly one successor, that happens to be a
618       // landingpad, accept it as valid control flow.
619       if (MBB->succ_size() != 1+LandingPadSuccs.size() &&
620           (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 ||
621            *MBB->succ_begin() != *LandingPadSuccs.begin())) {
622         report("MBB exits via unconditional branch but doesn't have "
623                "exactly one CFG successor!", MBB);
624       } else if (!MBB->isSuccessor(TBB)) {
625         report("MBB exits via unconditional branch but the CFG "
626                "successor doesn't match the actual successor!", MBB);
627       }
628       if (MBB->empty()) {
629         report("MBB exits via unconditional branch but doesn't contain "
630                "any instructions!", MBB);
631       } else if (!MBB->back().isBarrier()) {
632         report("MBB exits via unconditional branch but doesn't end with a "
633                "barrier instruction!", MBB);
634       } else if (!MBB->back().isTerminator()) {
635         report("MBB exits via unconditional branch but the branch isn't a "
636                "terminator instruction!", MBB);
637       }
638     } else if (TBB && !FBB && !Cond.empty()) {
639       // Block conditionally branches somewhere, otherwise falls through.
640       MachineFunction::const_iterator MBBI = MBB->getIterator();
641       ++MBBI;
642       if (MBBI == MF->end()) {
643         report("MBB conditionally falls through out of function!", MBB);
644       } else if (MBB->succ_size() == 1) {
645         // A conditional branch with only one successor is weird, but allowed.
646         if (&*MBBI != TBB)
647           report("MBB exits via conditional branch/fall-through but only has "
648                  "one CFG successor!", MBB);
649         else if (TBB != *MBB->succ_begin())
650           report("MBB exits via conditional branch/fall-through but the CFG "
651                  "successor don't match the actual successor!", MBB);
652       } else if (MBB->succ_size() != 2) {
653         report("MBB exits via conditional branch/fall-through but doesn't have "
654                "exactly two CFG successors!", MBB);
655       } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
656         report("MBB exits via conditional branch/fall-through but the CFG "
657                "successors don't match the actual successors!", MBB);
658       }
659       if (MBB->empty()) {
660         report("MBB exits via conditional branch/fall-through but doesn't "
661                "contain any instructions!", MBB);
662       } else if (MBB->back().isBarrier()) {
663         report("MBB exits via conditional branch/fall-through but ends with a "
664                "barrier instruction!", MBB);
665       } else if (!MBB->back().isTerminator()) {
666         report("MBB exits via conditional branch/fall-through but the branch "
667                "isn't a terminator instruction!", MBB);
668       }
669     } else if (TBB && FBB) {
670       // Block conditionally branches somewhere, otherwise branches
671       // somewhere else.
672       if (MBB->succ_size() == 1) {
673         // A conditional branch with only one successor is weird, but allowed.
674         if (FBB != TBB)
675           report("MBB exits via conditional branch/branch through but only has "
676                  "one CFG successor!", MBB);
677         else if (TBB != *MBB->succ_begin())
678           report("MBB exits via conditional branch/branch through but the CFG "
679                  "successor don't match the actual successor!", MBB);
680       } else if (MBB->succ_size() != 2) {
681         report("MBB exits via conditional branch/branch but doesn't have "
682                "exactly two CFG successors!", MBB);
683       } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
684         report("MBB exits via conditional branch/branch but the CFG "
685                "successors don't match the actual successors!", MBB);
686       }
687       if (MBB->empty()) {
688         report("MBB exits via conditional branch/branch but doesn't "
689                "contain any instructions!", MBB);
690       } else if (!MBB->back().isBarrier()) {
691         report("MBB exits via conditional branch/branch but doesn't end with a "
692                "barrier instruction!", MBB);
693       } else if (!MBB->back().isTerminator()) {
694         report("MBB exits via conditional branch/branch but the branch "
695                "isn't a terminator instruction!", MBB);
696       }
697       if (Cond.empty()) {
698         report("MBB exits via conditinal branch/branch but there's no "
699                "condition!", MBB);
700       }
701     } else {
702       report("AnalyzeBranch returned invalid data!", MBB);
703     }
704   }
705
706   regsLive.clear();
707   for (const auto &LI : MBB->liveins()) {
708     if (!TargetRegisterInfo::isPhysicalRegister(LI.PhysReg)) {
709       report("MBB live-in list contains non-physical register", MBB);
710       continue;
711     }
712     for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
713          SubRegs.isValid(); ++SubRegs)
714       regsLive.insert(*SubRegs);
715   }
716   regsLiveInButUnused = regsLive;
717
718   const MachineFrameInfo *MFI = MF->getFrameInfo();
719   assert(MFI && "Function has no frame info");
720   BitVector PR = MFI->getPristineRegs(*MF);
721   for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
722     for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
723          SubRegs.isValid(); ++SubRegs)
724       regsLive.insert(*SubRegs);
725   }
726
727   regsKilled.clear();
728   regsDefined.clear();
729
730   if (Indexes)
731     lastIndex = Indexes->getMBBStartIdx(MBB);
732 }
733
734 // This function gets called for all bundle headers, including normal
735 // stand-alone unbundled instructions.
736 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
737   if (Indexes && Indexes->hasIndex(MI)) {
738     SlotIndex idx = Indexes->getInstructionIndex(MI);
739     if (!(idx > lastIndex)) {
740       report("Instruction index out of order", MI);
741       errs() << "Last instruction was at " << lastIndex << '\n';
742     }
743     lastIndex = idx;
744   }
745
746   // Ensure non-terminators don't follow terminators.
747   // Ignore predicated terminators formed by if conversion.
748   // FIXME: If conversion shouldn't need to violate this rule.
749   if (MI->isTerminator() && !TII->isPredicated(MI)) {
750     if (!FirstTerminator)
751       FirstTerminator = MI;
752   } else if (FirstTerminator) {
753     report("Non-terminator instruction after the first terminator", MI);
754     errs() << "First terminator was:\t" << *FirstTerminator;
755   }
756 }
757
758 // The operands on an INLINEASM instruction must follow a template.
759 // Verify that the flag operands make sense.
760 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
761   // The first two operands on INLINEASM are the asm string and global flags.
762   if (MI->getNumOperands() < 2) {
763     report("Too few operands on inline asm", MI);
764     return;
765   }
766   if (!MI->getOperand(0).isSymbol())
767     report("Asm string must be an external symbol", MI);
768   if (!MI->getOperand(1).isImm())
769     report("Asm flags must be an immediate", MI);
770   // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
771   // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16.
772   if (!isUInt<5>(MI->getOperand(1).getImm()))
773     report("Unknown asm flags", &MI->getOperand(1), 1);
774
775   static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
776
777   unsigned OpNo = InlineAsm::MIOp_FirstOperand;
778   unsigned NumOps;
779   for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
780     const MachineOperand &MO = MI->getOperand(OpNo);
781     // There may be implicit ops after the fixed operands.
782     if (!MO.isImm())
783       break;
784     NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
785   }
786
787   if (OpNo > MI->getNumOperands())
788     report("Missing operands in last group", MI);
789
790   // An optional MDNode follows the groups.
791   if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
792     ++OpNo;
793
794   // All trailing operands must be implicit registers.
795   for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
796     const MachineOperand &MO = MI->getOperand(OpNo);
797     if (!MO.isReg() || !MO.isImplicit())
798       report("Expected implicit register after groups", &MO, OpNo);
799   }
800 }
801
802 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
803   const MCInstrDesc &MCID = MI->getDesc();
804   if (MI->getNumOperands() < MCID.getNumOperands()) {
805     report("Too few operands", MI);
806     errs() << MCID.getNumOperands() << " operands expected, but "
807         << MI->getNumOperands() << " given.\n";
808   }
809
810   // Check the tied operands.
811   if (MI->isInlineAsm())
812     verifyInlineAsm(MI);
813
814   // Check the MachineMemOperands for basic consistency.
815   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
816        E = MI->memoperands_end(); I != E; ++I) {
817     if ((*I)->isLoad() && !MI->mayLoad())
818       report("Missing mayLoad flag", MI);
819     if ((*I)->isStore() && !MI->mayStore())
820       report("Missing mayStore flag", MI);
821   }
822
823   // Debug values must not have a slot index.
824   // Other instructions must have one, unless they are inside a bundle.
825   if (LiveInts) {
826     bool mapped = !LiveInts->isNotInMIMap(MI);
827     if (MI->isDebugValue()) {
828       if (mapped)
829         report("Debug instruction has a slot index", MI);
830     } else if (MI->isInsideBundle()) {
831       if (mapped)
832         report("Instruction inside bundle has a slot index", MI);
833     } else {
834       if (!mapped)
835         report("Missing slot index", MI);
836     }
837   }
838
839   StringRef ErrorInfo;
840   if (!TII->verifyInstruction(MI, ErrorInfo))
841     report(ErrorInfo.data(), MI);
842 }
843
844 void
845 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
846   const MachineInstr *MI = MO->getParent();
847   const MCInstrDesc &MCID = MI->getDesc();
848   unsigned NumDefs = MCID.getNumDefs();
849   if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
850     NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
851
852   // The first MCID.NumDefs operands must be explicit register defines
853   if (MONum < NumDefs) {
854     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
855     if (!MO->isReg())
856       report("Explicit definition must be a register", MO, MONum);
857     else if (!MO->isDef() && !MCOI.isOptionalDef())
858       report("Explicit definition marked as use", MO, MONum);
859     else if (MO->isImplicit())
860       report("Explicit definition marked as implicit", MO, MONum);
861   } else if (MONum < MCID.getNumOperands()) {
862     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
863     // Don't check if it's the last operand in a variadic instruction. See,
864     // e.g., LDM_RET in the arm back end.
865     if (MO->isReg() &&
866         !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
867       if (MO->isDef() && !MCOI.isOptionalDef())
868         report("Explicit operand marked as def", MO, MONum);
869       if (MO->isImplicit())
870         report("Explicit operand marked as implicit", MO, MONum);
871     }
872
873     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
874     if (TiedTo != -1) {
875       if (!MO->isReg())
876         report("Tied use must be a register", MO, MONum);
877       else if (!MO->isTied())
878         report("Operand should be tied", MO, MONum);
879       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
880         report("Tied def doesn't match MCInstrDesc", MO, MONum);
881     } else if (MO->isReg() && MO->isTied())
882       report("Explicit operand should not be tied", MO, MONum);
883   } else {
884     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
885     if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
886       report("Extra explicit operand on non-variadic instruction", MO, MONum);
887   }
888
889   switch (MO->getType()) {
890   case MachineOperand::MO_Register: {
891     const unsigned Reg = MO->getReg();
892     if (!Reg)
893       return;
894     if (MRI->tracksLiveness() && !MI->isDebugValue())
895       checkLiveness(MO, MONum);
896
897     // Verify the consistency of tied operands.
898     if (MO->isTied()) {
899       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
900       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
901       if (!OtherMO.isReg())
902         report("Must be tied to a register", MO, MONum);
903       if (!OtherMO.isTied())
904         report("Missing tie flags on tied operand", MO, MONum);
905       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
906         report("Inconsistent tie links", MO, MONum);
907       if (MONum < MCID.getNumDefs()) {
908         if (OtherIdx < MCID.getNumOperands()) {
909           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
910             report("Explicit def tied to explicit use without tie constraint",
911                    MO, MONum);
912         } else {
913           if (!OtherMO.isImplicit())
914             report("Explicit def should be tied to implicit use", MO, MONum);
915         }
916       }
917     }
918
919     // Verify two-address constraints after leaving SSA form.
920     unsigned DefIdx;
921     if (!MRI->isSSA() && MO->isUse() &&
922         MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
923         Reg != MI->getOperand(DefIdx).getReg())
924       report("Two-address instruction operands must be identical", MO, MONum);
925
926     // Check register classes.
927     if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
928       unsigned SubIdx = MO->getSubReg();
929
930       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
931         if (SubIdx) {
932           report("Illegal subregister index for physical register", MO, MONum);
933           return;
934         }
935         if (const TargetRegisterClass *DRC =
936               TII->getRegClass(MCID, MONum, TRI, *MF)) {
937           if (!DRC->contains(Reg)) {
938             report("Illegal physical register for instruction", MO, MONum);
939             errs() << TRI->getName(Reg) << " is not a "
940                 << TRI->getRegClassName(DRC) << " register.\n";
941           }
942         }
943       } else {
944         // Virtual register.
945         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
946         if (SubIdx) {
947           const TargetRegisterClass *SRC =
948             TRI->getSubClassWithSubReg(RC, SubIdx);
949           if (!SRC) {
950             report("Invalid subregister index for virtual register", MO, MONum);
951             errs() << "Register class " << TRI->getRegClassName(RC)
952                 << " does not support subreg index " << SubIdx << "\n";
953             return;
954           }
955           if (RC != SRC) {
956             report("Invalid register class for subregister index", MO, MONum);
957             errs() << "Register class " << TRI->getRegClassName(RC)
958                 << " does not fully support subreg index " << SubIdx << "\n";
959             return;
960           }
961         }
962         if (const TargetRegisterClass *DRC =
963               TII->getRegClass(MCID, MONum, TRI, *MF)) {
964           if (SubIdx) {
965             const TargetRegisterClass *SuperRC =
966                 TRI->getLargestLegalSuperClass(RC, *MF);
967             if (!SuperRC) {
968               report("No largest legal super class exists.", MO, MONum);
969               return;
970             }
971             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
972             if (!DRC) {
973               report("No matching super-reg register class.", MO, MONum);
974               return;
975             }
976           }
977           if (!RC->hasSuperClassEq(DRC)) {
978             report("Illegal virtual register for instruction", MO, MONum);
979             errs() << "Expected a " << TRI->getRegClassName(DRC)
980                 << " register, but got a " << TRI->getRegClassName(RC)
981                 << " register\n";
982           }
983         }
984       }
985     }
986     break;
987   }
988
989   case MachineOperand::MO_RegisterMask:
990     regMasks.push_back(MO->getRegMask());
991     break;
992
993   case MachineOperand::MO_MachineBasicBlock:
994     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
995       report("PHI operand is not in the CFG", MO, MONum);
996     break;
997
998   case MachineOperand::MO_FrameIndex:
999     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
1000         LiveInts && !LiveInts->isNotInMIMap(MI)) {
1001       int FI = MO->getIndex();
1002       LiveInterval &LI = LiveStks->getInterval(FI);
1003       SlotIndex Idx = LiveInts->getInstructionIndex(MI);
1004
1005       bool stores = MI->mayStore();
1006       bool loads = MI->mayLoad();
1007       // For a memory-to-memory move, we need to check if the frame
1008       // index is used for storing or loading, by inspecting the
1009       // memory operands.
1010       if (stores && loads) {
1011         for (auto *MMO : MI->memoperands()) {
1012           const PseudoSourceValue *PSV = MMO->getPseudoValue();
1013           if (PSV == nullptr) continue;
1014           const FixedStackPseudoSourceValue *Value =
1015             dyn_cast<FixedStackPseudoSourceValue>(PSV);
1016           if (Value == nullptr) continue;
1017           if (Value->getFrameIndex() != FI) continue;
1018
1019           if (MMO->isStore())
1020             loads = false;
1021           else
1022             stores = false;
1023           break;
1024         }
1025         if (loads == stores)
1026           report("Missing fixed stack memoperand.", MI);
1027       }
1028       if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
1029         report("Instruction loads from dead spill slot", MO, MONum);
1030         errs() << "Live stack: " << LI << '\n';
1031       }
1032       if (stores && !LI.liveAt(Idx.getRegSlot())) {
1033         report("Instruction stores to dead spill slot", MO, MONum);
1034         errs() << "Live stack: " << LI << '\n';
1035       }
1036     }
1037     break;
1038
1039   default:
1040     break;
1041   }
1042 }
1043
1044 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
1045   const MachineInstr *MI = MO->getParent();
1046   const unsigned Reg = MO->getReg();
1047
1048   // Both use and def operands can read a register.
1049   if (MO->readsReg()) {
1050     regsLiveInButUnused.erase(Reg);
1051
1052     if (MO->isKill())
1053       addRegWithSubRegs(regsKilled, Reg);
1054
1055     // Check that LiveVars knows this kill.
1056     if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1057         MO->isKill()) {
1058       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1059       if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end())
1060         report("Kill missing from LiveVariables", MO, MONum);
1061     }
1062
1063     // Check LiveInts liveness and kill.
1064     if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
1065       SlotIndex UseIdx = LiveInts->getInstructionIndex(MI);
1066       // Check the cached regunit intervals.
1067       if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1068         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1069           if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) {
1070             LiveQueryResult LRQ = LR->Query(UseIdx);
1071             if (!LRQ.valueIn()) {
1072               report("No live segment at use", MO, MONum);
1073               errs() << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI)
1074                   << ' ' << *LR << '\n';
1075             }
1076             if (MO->isKill() && !LRQ.isKill()) {
1077               report("Live range continues after kill flag", MO, MONum);
1078               errs() << PrintRegUnit(*Units, TRI) << ' ' << *LR << '\n';
1079             }
1080           }
1081         }
1082       }
1083
1084       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1085         if (LiveInts->hasInterval(Reg)) {
1086           // This is a virtual register interval.
1087           const LiveInterval &LI = LiveInts->getInterval(Reg);
1088           LiveQueryResult LRQ = LI.Query(UseIdx);
1089           if (!LRQ.valueIn()) {
1090             report("No live segment at use", MO, MONum);
1091             errs() << UseIdx << " is not live in " << LI << '\n';
1092           }
1093           // Check for extra kill flags.
1094           // Note that we allow missing kill flags for now.
1095           if (MO->isKill() && !LRQ.isKill()) {
1096             report("Live range continues after kill flag", MO, MONum);
1097             errs() << "Live range: " << LI << '\n';
1098           }
1099         } else {
1100           report("Virtual register has no live interval", MO, MONum);
1101         }
1102       }
1103     }
1104
1105     // Use of a dead register.
1106     if (!regsLive.count(Reg)) {
1107       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1108         // Reserved registers may be used even when 'dead'.
1109         bool Bad = !isReserved(Reg);
1110         // We are fine if just any subregister has a defined value.
1111         if (Bad) {
1112           for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid();
1113                ++SubRegs) {
1114             if (regsLive.count(*SubRegs)) {
1115               Bad = false;
1116               break;
1117             }
1118           }
1119         }
1120         // If there is an additional implicit-use of a super register we stop
1121         // here. By definition we are fine if the super register is not
1122         // (completely) dead, if the complete super register is dead we will
1123         // get a report for its operand.
1124         if (Bad) {
1125           for (const MachineOperand &MOP : MI->uses()) {
1126             if (!MOP.isReg())
1127               continue;
1128             if (!MOP.isImplicit())
1129               continue;
1130             for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid();
1131                  ++SubRegs) {
1132               if (*SubRegs == Reg) {
1133                 Bad = false;
1134                 break;
1135               }
1136             }
1137           }
1138         }
1139         if (Bad)
1140           report("Using an undefined physical register", MO, MONum);
1141       } else if (MRI->def_empty(Reg)) {
1142         report("Reading virtual register without a def", MO, MONum);
1143       } else {
1144         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1145         // We don't know which virtual registers are live in, so only complain
1146         // if vreg was killed in this MBB. Otherwise keep track of vregs that
1147         // must be live in. PHI instructions are handled separately.
1148         if (MInfo.regsKilled.count(Reg))
1149           report("Using a killed virtual register", MO, MONum);
1150         else if (!MI->isPHI())
1151           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1152       }
1153     }
1154   }
1155
1156   if (MO->isDef()) {
1157     // Register defined.
1158     // TODO: verify that earlyclobber ops are not used.
1159     if (MO->isDead())
1160       addRegWithSubRegs(regsDead, Reg);
1161     else
1162       addRegWithSubRegs(regsDefined, Reg);
1163
1164     // Verify SSA form.
1165     if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1166         std::next(MRI->def_begin(Reg)) != MRI->def_end())
1167       report("Multiple virtual register defs in SSA form", MO, MONum);
1168
1169     // Check LiveInts for a live segment, but only for virtual registers.
1170     if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
1171         !LiveInts->isNotInMIMap(MI)) {
1172       SlotIndex DefIdx = LiveInts->getInstructionIndex(MI);
1173       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1174       if (LiveInts->hasInterval(Reg)) {
1175         const LiveInterval &LI = LiveInts->getInterval(Reg);
1176         if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
1177           assert(VNI && "NULL valno is not allowed");
1178           if (VNI->def != DefIdx) {
1179             report("Inconsistent valno->def", MO, MONum);
1180             errs() << "Valno " << VNI->id << " is not defined at "
1181               << DefIdx << " in " << LI << '\n';
1182           }
1183         } else {
1184           report("No live segment at def", MO, MONum);
1185           errs() << DefIdx << " is not live in " << LI << '\n';
1186         }
1187         // Check that, if the dead def flag is present, LiveInts agree.
1188         if (MO->isDead()) {
1189           LiveQueryResult LRQ = LI.Query(DefIdx);
1190           if (!LRQ.isDeadDef()) {
1191             report("Live range continues after dead def flag", MO, MONum);
1192             errs() << "Live range: " << LI << '\n';
1193           }
1194         }
1195       } else {
1196         report("Virtual register has no Live interval", MO, MONum);
1197       }
1198     }
1199   }
1200 }
1201
1202 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
1203 }
1204
1205 // This function gets called after visiting all instructions in a bundle. The
1206 // argument points to the bundle header.
1207 // Normal stand-alone instructions are also considered 'bundles', and this
1208 // function is called for all of them.
1209 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1210   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1211   set_union(MInfo.regsKilled, regsKilled);
1212   set_subtract(regsLive, regsKilled); regsKilled.clear();
1213   // Kill any masked registers.
1214   while (!regMasks.empty()) {
1215     const uint32_t *Mask = regMasks.pop_back_val();
1216     for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1217       if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1218           MachineOperand::clobbersPhysReg(Mask, *I))
1219         regsDead.push_back(*I);
1220   }
1221   set_subtract(regsLive, regsDead);   regsDead.clear();
1222   set_union(regsLive, regsDefined);   regsDefined.clear();
1223 }
1224
1225 void
1226 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1227   MBBInfoMap[MBB].regsLiveOut = regsLive;
1228   regsLive.clear();
1229
1230   if (Indexes) {
1231     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1232     if (!(stop > lastIndex)) {
1233       report("Block ends before last instruction index", MBB);
1234       errs() << "Block ends at " << stop
1235           << " last instruction was at " << lastIndex << '\n';
1236     }
1237     lastIndex = stop;
1238   }
1239 }
1240
1241 // Calculate the largest possible vregsPassed sets. These are the registers that
1242 // can pass through an MBB live, but may not be live every time. It is assumed
1243 // that all vregsPassed sets are empty before the call.
1244 void MachineVerifier::calcRegsPassed() {
1245   // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1246   // have any vregsPassed.
1247   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1248   for (const auto &MBB : *MF) {
1249     BBInfo &MInfo = MBBInfoMap[&MBB];
1250     if (!MInfo.reachable)
1251       continue;
1252     for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1253            SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1254       BBInfo &SInfo = MBBInfoMap[*SuI];
1255       if (SInfo.addPassed(MInfo.regsLiveOut))
1256         todo.insert(*SuI);
1257     }
1258   }
1259
1260   // Iteratively push vregsPassed to successors. This will converge to the same
1261   // final state regardless of DenseSet iteration order.
1262   while (!todo.empty()) {
1263     const MachineBasicBlock *MBB = *todo.begin();
1264     todo.erase(MBB);
1265     BBInfo &MInfo = MBBInfoMap[MBB];
1266     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1267            SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1268       if (*SuI == MBB)
1269         continue;
1270       BBInfo &SInfo = MBBInfoMap[*SuI];
1271       if (SInfo.addPassed(MInfo.vregsPassed))
1272         todo.insert(*SuI);
1273     }
1274   }
1275 }
1276
1277 // Calculate the set of virtual registers that must be passed through each basic
1278 // block in order to satisfy the requirements of successor blocks. This is very
1279 // similar to calcRegsPassed, only backwards.
1280 void MachineVerifier::calcRegsRequired() {
1281   // First push live-in regs to predecessors' vregsRequired.
1282   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1283   for (const auto &MBB : *MF) {
1284     BBInfo &MInfo = MBBInfoMap[&MBB];
1285     for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1286            PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1287       BBInfo &PInfo = MBBInfoMap[*PrI];
1288       if (PInfo.addRequired(MInfo.vregsLiveIn))
1289         todo.insert(*PrI);
1290     }
1291   }
1292
1293   // Iteratively push vregsRequired to predecessors. This will converge to the
1294   // same final state regardless of DenseSet iteration order.
1295   while (!todo.empty()) {
1296     const MachineBasicBlock *MBB = *todo.begin();
1297     todo.erase(MBB);
1298     BBInfo &MInfo = MBBInfoMap[MBB];
1299     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1300            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1301       if (*PrI == MBB)
1302         continue;
1303       BBInfo &SInfo = MBBInfoMap[*PrI];
1304       if (SInfo.addRequired(MInfo.vregsRequired))
1305         todo.insert(*PrI);
1306     }
1307   }
1308 }
1309
1310 // Check PHI instructions at the beginning of MBB. It is assumed that
1311 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1312 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
1313   SmallPtrSet<const MachineBasicBlock*, 8> seen;
1314   for (const auto &BBI : *MBB) {
1315     if (!BBI.isPHI())
1316       break;
1317     seen.clear();
1318
1319     for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
1320       unsigned Reg = BBI.getOperand(i).getReg();
1321       const MachineBasicBlock *Pre = BBI.getOperand(i + 1).getMBB();
1322       if (!Pre->isSuccessor(MBB))
1323         continue;
1324       seen.insert(Pre);
1325       BBInfo &PrInfo = MBBInfoMap[Pre];
1326       if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
1327         report("PHI operand is not live-out from predecessor",
1328                &BBI.getOperand(i), i);
1329     }
1330
1331     // Did we see all predecessors?
1332     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1333            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1334       if (!seen.count(*PrI)) {
1335         report("Missing PHI operand", &BBI);
1336         errs() << "BB#" << (*PrI)->getNumber()
1337             << " is a predecessor according to the CFG.\n";
1338       }
1339     }
1340   }
1341 }
1342
1343 void MachineVerifier::visitMachineFunctionAfter() {
1344   calcRegsPassed();
1345
1346   for (const auto &MBB : *MF) {
1347     BBInfo &MInfo = MBBInfoMap[&MBB];
1348
1349     // Skip unreachable MBBs.
1350     if (!MInfo.reachable)
1351       continue;
1352
1353     checkPHIOps(&MBB);
1354   }
1355
1356   // Now check liveness info if available
1357   calcRegsRequired();
1358
1359   // Check for killed virtual registers that should be live out.
1360   for (const auto &MBB : *MF) {
1361     BBInfo &MInfo = MBBInfoMap[&MBB];
1362     for (RegSet::iterator
1363          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1364          ++I)
1365       if (MInfo.regsKilled.count(*I)) {
1366         report("Virtual register killed in block, but needed live out.", &MBB);
1367         errs() << "Virtual register " << PrintReg(*I)
1368             << " is used after the block.\n";
1369       }
1370   }
1371
1372   if (!MF->empty()) {
1373     BBInfo &MInfo = MBBInfoMap[&MF->front()];
1374     for (RegSet::iterator
1375          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1376          ++I)
1377       report("Virtual register def doesn't dominate all uses.",
1378              MRI->getVRegDef(*I));
1379   }
1380
1381   if (LiveVars)
1382     verifyLiveVariables();
1383   if (LiveInts)
1384     verifyLiveIntervals();
1385 }
1386
1387 void MachineVerifier::verifyLiveVariables() {
1388   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1389   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1390     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1391     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1392     for (const auto &MBB : *MF) {
1393       BBInfo &MInfo = MBBInfoMap[&MBB];
1394
1395       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1396       if (MInfo.vregsRequired.count(Reg)) {
1397         if (!VI.AliveBlocks.test(MBB.getNumber())) {
1398           report("LiveVariables: Block missing from AliveBlocks", &MBB);
1399           errs() << "Virtual register " << PrintReg(Reg)
1400               << " must be live through the block.\n";
1401         }
1402       } else {
1403         if (VI.AliveBlocks.test(MBB.getNumber())) {
1404           report("LiveVariables: Block should not be in AliveBlocks", &MBB);
1405           errs() << "Virtual register " << PrintReg(Reg)
1406               << " is not needed live through the block.\n";
1407         }
1408       }
1409     }
1410   }
1411 }
1412
1413 void MachineVerifier::verifyLiveIntervals() {
1414   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1415   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1416     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1417
1418     // Spilling and splitting may leave unused registers around. Skip them.
1419     if (MRI->reg_nodbg_empty(Reg))
1420       continue;
1421
1422     if (!LiveInts->hasInterval(Reg)) {
1423       report("Missing live interval for virtual register", MF);
1424       errs() << PrintReg(Reg, TRI) << " still has defs or uses\n";
1425       continue;
1426     }
1427
1428     const LiveInterval &LI = LiveInts->getInterval(Reg);
1429     assert(Reg == LI.reg && "Invalid reg to interval mapping");
1430     verifyLiveInterval(LI);
1431   }
1432
1433   // Verify all the cached regunit intervals.
1434   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1435     if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1436       verifyLiveRange(*LR, i);
1437 }
1438
1439 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1440                                            const VNInfo *VNI, unsigned Reg,
1441                                            LaneBitmask LaneMask) {
1442   if (VNI->isUnused())
1443     return;
1444
1445   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1446
1447   if (!DefVNI) {
1448     report("Valno not live at def and not marked unused", MF, LR, Reg,
1449            LaneMask);
1450     errs() << "Valno #" << VNI->id << '\n';
1451     return;
1452   }
1453
1454   if (DefVNI != VNI) {
1455     report("Live segment at def has different valno", MF, LR, Reg, LaneMask);
1456     errs() << "Valno #" << VNI->id << " is defined at " << VNI->def
1457         << " where valno #" << DefVNI->id << " is live\n";
1458     return;
1459   }
1460
1461   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1462   if (!MBB) {
1463     report("Invalid definition index", MF, LR, Reg, LaneMask);
1464     errs() << "Valno #" << VNI->id << " is defined at " << VNI->def
1465         << " in " << LR << '\n';
1466     return;
1467   }
1468
1469   if (VNI->isPHIDef()) {
1470     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1471       report("PHIDef value is not defined at MBB start", MBB, LR, Reg,
1472              LaneMask);
1473       errs() << "Valno #" << VNI->id << " is defined at " << VNI->def
1474           << ", not at the beginning of BB#" << MBB->getNumber() << '\n';
1475     }
1476     return;
1477   }
1478
1479   // Non-PHI def.
1480   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1481   if (!MI) {
1482     report("No instruction at def index", MBB, LR, Reg, LaneMask);
1483     errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1484     return;
1485   }
1486
1487   if (Reg != 0) {
1488     bool hasDef = false;
1489     bool isEarlyClobber = false;
1490     for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1491       if (!MOI->isReg() || !MOI->isDef())
1492         continue;
1493       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1494         if (MOI->getReg() != Reg)
1495           continue;
1496       } else {
1497         if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1498             !TRI->hasRegUnit(MOI->getReg(), Reg))
1499           continue;
1500       }
1501       if (LaneMask != 0 &&
1502           (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask) == 0)
1503         continue;
1504       hasDef = true;
1505       if (MOI->isEarlyClobber())
1506         isEarlyClobber = true;
1507     }
1508
1509     if (!hasDef) {
1510       report("Defining instruction does not modify register", MI);
1511       errs() << "Valno #" << VNI->id << " in " << LR << '\n';
1512     }
1513
1514     // Early clobber defs begin at USE slots, but other defs must begin at
1515     // DEF slots.
1516     if (isEarlyClobber) {
1517       if (!VNI->def.isEarlyClobber()) {
1518         report("Early clobber def must be at an early-clobber slot", MBB, LR,
1519                Reg, LaneMask);
1520         errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1521       }
1522     } else if (!VNI->def.isRegister()) {
1523       report("Non-PHI, non-early clobber def must be at a register slot",
1524              MBB, LR, Reg, LaneMask);
1525       errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1526     }
1527   }
1528 }
1529
1530 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1531                                              const LiveRange::const_iterator I,
1532                                              unsigned Reg, LaneBitmask LaneMask)
1533 {
1534   const LiveRange::Segment &S = *I;
1535   const VNInfo *VNI = S.valno;
1536   assert(VNI && "Live segment has no valno");
1537
1538   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1539     report("Foreign valno in live segment", MF, LR, Reg, LaneMask);
1540     errs() << S << " has a bad valno\n";
1541   }
1542
1543   if (VNI->isUnused()) {
1544     report("Live segment valno is marked unused", MF, LR, Reg, LaneMask);
1545     errs() << S << '\n';
1546   }
1547
1548   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1549   if (!MBB) {
1550     report("Bad start of live segment, no basic block", MF, LR, Reg, LaneMask);
1551     errs() << S << '\n';
1552     return;
1553   }
1554   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1555   if (S.start != MBBStartIdx && S.start != VNI->def) {
1556     report("Live segment must begin at MBB entry or valno def", MBB, LR, Reg,
1557            LaneMask);
1558     errs() << S << '\n';
1559   }
1560
1561   const MachineBasicBlock *EndMBB =
1562     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
1563   if (!EndMBB) {
1564     report("Bad end of live segment, no basic block", MF, LR, Reg, LaneMask);
1565     errs() << S << '\n';
1566     return;
1567   }
1568
1569   // No more checks for live-out segments.
1570   if (S.end == LiveInts->getMBBEndIdx(EndMBB))
1571     return;
1572
1573   // RegUnit intervals are allowed dead phis.
1574   if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
1575       S.start == VNI->def && S.end == VNI->def.getDeadSlot())
1576     return;
1577
1578   // The live segment is ending inside EndMBB
1579   const MachineInstr *MI =
1580     LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
1581   if (!MI) {
1582     report("Live segment doesn't end at a valid instruction", EndMBB, LR, Reg,
1583            LaneMask);
1584     errs() << S << '\n';
1585     return;
1586   }
1587
1588   // The block slot must refer to a basic block boundary.
1589   if (S.end.isBlock()) {
1590     report("Live segment ends at B slot of an instruction", EndMBB, LR, Reg,
1591            LaneMask);
1592     errs() << S << '\n';
1593   }
1594
1595   if (S.end.isDead()) {
1596     // Segment ends on the dead slot.
1597     // That means there must be a dead def.
1598     if (!SlotIndex::isSameInstr(S.start, S.end)) {
1599       report("Live segment ending at dead slot spans instructions", EndMBB, LR,
1600              Reg, LaneMask);
1601       errs() << S << '\n';
1602     }
1603   }
1604
1605   // A live segment can only end at an early-clobber slot if it is being
1606   // redefined by an early-clobber def.
1607   if (S.end.isEarlyClobber()) {
1608     if (I+1 == LR.end() || (I+1)->start != S.end) {
1609       report("Live segment ending at early clobber slot must be "
1610              "redefined by an EC def in the same instruction", EndMBB, LR, Reg,
1611              LaneMask);
1612       errs() << S << '\n';
1613     }
1614   }
1615
1616   // The following checks only apply to virtual registers. Physreg liveness
1617   // is too weird to check.
1618   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1619     // A live segment can end with either a redefinition, a kill flag on a
1620     // use, or a dead flag on a def.
1621     bool hasRead = false;
1622     bool hasSubRegDef = false;
1623     for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1624       if (!MOI->isReg() || MOI->getReg() != Reg)
1625         continue;
1626       if (LaneMask != 0 &&
1627           (LaneMask & TRI->getSubRegIndexLaneMask(MOI->getSubReg())) == 0)
1628         continue;
1629       if (MOI->isDef() && MOI->getSubReg() != 0)
1630         hasSubRegDef = true;
1631       if (MOI->readsReg())
1632         hasRead = true;
1633     }
1634     if (!S.end.isDead()) {
1635       if (!hasRead) {
1636         // When tracking subregister liveness, the main range must start new
1637         // values on partial register writes, even if there is no read.
1638         if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask != 0 ||
1639             !hasSubRegDef) {
1640           report("Instruction ending live segment doesn't read the register",
1641                  MI);
1642           errs() << S << " in " << LR << '\n';
1643         }
1644       }
1645     }
1646   }
1647
1648   // Now check all the basic blocks in this live segment.
1649   MachineFunction::const_iterator MFI = MBB->getIterator();
1650   // Is this live segment the beginning of a non-PHIDef VN?
1651   if (S.start == VNI->def && !VNI->isPHIDef()) {
1652     // Not live-in to any blocks.
1653     if (MBB == EndMBB)
1654       return;
1655     // Skip this block.
1656     ++MFI;
1657   }
1658   for (;;) {
1659     assert(LiveInts->isLiveInToMBB(LR, &*MFI));
1660     // We don't know how to track physregs into a landing pad.
1661     if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
1662         MFI->isEHPad()) {
1663       if (&*MFI == EndMBB)
1664         break;
1665       ++MFI;
1666       continue;
1667     }
1668
1669     // Is VNI a PHI-def in the current block?
1670     bool IsPHI = VNI->isPHIDef() &&
1671       VNI->def == LiveInts->getMBBStartIdx(&*MFI);
1672
1673     // Check that VNI is live-out of all predecessors.
1674     for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1675          PE = MFI->pred_end(); PI != PE; ++PI) {
1676       SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1677       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
1678
1679       // All predecessors must have a live-out value.
1680       if (!PVNI) {
1681         report("Register not marked live out of predecessor", *PI, LR, Reg,
1682                LaneMask);
1683         errs() << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1684                << '@' << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
1685                << PEnd << '\n';
1686         continue;
1687       }
1688
1689       // Only PHI-defs can take different predecessor values.
1690       if (!IsPHI && PVNI != VNI) {
1691         report("Different value live out of predecessor", *PI, LR, Reg,
1692                LaneMask);
1693         errs() << "Valno #" << PVNI->id << " live out of BB#"
1694                << (*PI)->getNumber() << '@' << PEnd << "\nValno #" << VNI->id
1695                << " live into BB#" << MFI->getNumber() << '@'
1696                << LiveInts->getMBBStartIdx(&*MFI) << '\n';
1697       }
1698     }
1699     if (&*MFI == EndMBB)
1700       break;
1701     ++MFI;
1702   }
1703 }
1704
1705 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg,
1706                                       LaneBitmask LaneMask) {
1707   for (const VNInfo *VNI : LR.valnos)
1708     verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
1709
1710   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
1711     verifyLiveRangeSegment(LR, I, Reg, LaneMask);
1712 }
1713
1714 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
1715   unsigned Reg = LI.reg;
1716   assert(TargetRegisterInfo::isVirtualRegister(Reg));
1717   verifyLiveRange(LI, Reg);
1718
1719   LaneBitmask Mask = 0;
1720   LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
1721   for (const LiveInterval::SubRange &SR : LI.subranges()) {
1722     if ((Mask & SR.LaneMask) != 0)
1723       report("Lane masks of sub ranges overlap in live interval", MF, LI);
1724     if ((SR.LaneMask & ~MaxMask) != 0)
1725       report("Subrange lanemask is invalid", MF, LI);
1726     if (SR.empty())
1727       report("Subrange must not be empty", MF, SR, LI.reg, SR.LaneMask);
1728     Mask |= SR.LaneMask;
1729     verifyLiveRange(SR, LI.reg, SR.LaneMask);
1730     if (!LI.covers(SR))
1731       report("A Subrange is not covered by the main range", MF, LI);
1732   }
1733
1734   // Check the LI only has one connected component.
1735   ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1736   unsigned NumComp = ConEQ.Classify(&LI);
1737   if (NumComp > 1) {
1738     report("Multiple connected components in live interval", MF, LI);
1739     for (unsigned comp = 0; comp != NumComp; ++comp) {
1740       errs() << comp << ": valnos";
1741       for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1742            E = LI.vni_end(); I!=E; ++I)
1743         if (comp == ConEQ.getEqClass(*I))
1744           errs() << ' ' << (*I)->id;
1745       errs() << '\n';
1746     }
1747   }
1748 }
1749
1750 namespace {
1751   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
1752   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
1753   // value is zero.
1754   // We use a bool plus an integer to capture the stack state.
1755   struct StackStateOfBB {
1756     StackStateOfBB() : EntryValue(0), ExitValue(0), EntryIsSetup(false),
1757       ExitIsSetup(false) { }
1758     StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
1759       EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
1760       ExitIsSetup(ExitSetup) { }
1761     // Can be negative, which means we are setting up a frame.
1762     int EntryValue;
1763     int ExitValue;
1764     bool EntryIsSetup;
1765     bool ExitIsSetup;
1766   };
1767 }
1768
1769 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
1770 /// by a FrameDestroy <n>, stack adjustments are identical on all
1771 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
1772 void MachineVerifier::verifyStackFrame() {
1773   unsigned FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
1774   unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
1775
1776   SmallVector<StackStateOfBB, 8> SPState;
1777   SPState.resize(MF->getNumBlockIDs());
1778   SmallPtrSet<const MachineBasicBlock*, 8> Reachable;
1779
1780   // Visit the MBBs in DFS order.
1781   for (df_ext_iterator<const MachineFunction*,
1782                        SmallPtrSet<const MachineBasicBlock*, 8> >
1783        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
1784        DFI != DFE; ++DFI) {
1785     const MachineBasicBlock *MBB = *DFI;
1786
1787     StackStateOfBB BBState;
1788     // Check the exit state of the DFS stack predecessor.
1789     if (DFI.getPathLength() >= 2) {
1790       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1791       assert(Reachable.count(StackPred) &&
1792              "DFS stack predecessor is already visited.\n");
1793       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
1794       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
1795       BBState.ExitValue = BBState.EntryValue;
1796       BBState.ExitIsSetup = BBState.EntryIsSetup;
1797     }
1798
1799     // Update stack state by checking contents of MBB.
1800     for (const auto &I : *MBB) {
1801       if (I.getOpcode() == FrameSetupOpcode) {
1802         // The first operand of a FrameOpcode should be i32.
1803         int Size = I.getOperand(0).getImm();
1804         assert(Size >= 0 &&
1805           "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1806
1807         if (BBState.ExitIsSetup)
1808           report("FrameSetup is after another FrameSetup", &I);
1809         BBState.ExitValue -= Size;
1810         BBState.ExitIsSetup = true;
1811       }
1812
1813       if (I.getOpcode() == FrameDestroyOpcode) {
1814         // The first operand of a FrameOpcode should be i32.
1815         int Size = I.getOperand(0).getImm();
1816         assert(Size >= 0 &&
1817           "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1818
1819         if (!BBState.ExitIsSetup)
1820           report("FrameDestroy is not after a FrameSetup", &I);
1821         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
1822                                                BBState.ExitValue;
1823         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
1824           report("FrameDestroy <n> is after FrameSetup <m>", &I);
1825           errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
1826               << AbsSPAdj << ">.\n";
1827         }
1828         BBState.ExitValue += Size;
1829         BBState.ExitIsSetup = false;
1830       }
1831     }
1832     SPState[MBB->getNumber()] = BBState;
1833
1834     // Make sure the exit state of any predecessor is consistent with the entry
1835     // state.
1836     for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
1837          E = MBB->pred_end(); I != E; ++I) {
1838       if (Reachable.count(*I) &&
1839           (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
1840            SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
1841         report("The exit stack state of a predecessor is inconsistent.", MBB);
1842         errs() << "Predecessor BB#" << (*I)->getNumber() << " has exit state ("
1843             << SPState[(*I)->getNumber()].ExitValue << ", "
1844             << SPState[(*I)->getNumber()].ExitIsSetup
1845             << "), while BB#" << MBB->getNumber() << " has entry state ("
1846             << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
1847       }
1848     }
1849
1850     // Make sure the entry state of any successor is consistent with the exit
1851     // state.
1852     for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
1853          E = MBB->succ_end(); I != E; ++I) {
1854       if (Reachable.count(*I) &&
1855           (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
1856            SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
1857         report("The entry stack state of a successor is inconsistent.", MBB);
1858         errs() << "Successor BB#" << (*I)->getNumber() << " has entry state ("
1859             << SPState[(*I)->getNumber()].EntryValue << ", "
1860             << SPState[(*I)->getNumber()].EntryIsSetup
1861             << "), while BB#" << MBB->getNumber() << " has exit state ("
1862             << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
1863       }
1864     }
1865
1866     // Make sure a basic block with return ends with zero stack adjustment.
1867     if (!MBB->empty() && MBB->back().isReturn()) {
1868       if (BBState.ExitIsSetup)
1869         report("A return block ends with a FrameSetup.", MBB);
1870       if (BBState.ExitValue)
1871         report("A return block ends with a nonzero stack adjustment.", MBB);
1872     }
1873   }
1874 }