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