MachineVerifier.cpp revision 0d0598f6281c0b1ae107b2fa2fabd69ec21263c4
1//===-- MachineVerifier.cpp - Machine Code Verifier -------------*- C++ -*-===//
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/Function.h"
27#include "llvm/CodeGen/LiveVariables.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetRegisterInfo.h"
34#include "llvm/Target/TargetInstrInfo.h"
35#include "llvm/ADT/DenseSet.h"
36#include "llvm/ADT/SetOperations.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/raw_ostream.h"
42using namespace llvm;
43
44namespace {
45  struct VISIBILITY_HIDDEN MachineVerifier : public MachineFunctionPass {
46    static char ID; // Pass ID, replacement for typeid
47
48    MachineVerifier(bool allowDoubleDefs = false) :
49      MachineFunctionPass(&ID),
50      allowVirtDoubleDefs(allowDoubleDefs),
51      allowPhysDoubleDefs(allowDoubleDefs),
52      OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
53        {}
54
55    void getAnalysisUsage(AnalysisUsage &AU) const {
56      AU.setPreservesAll();
57      MachineFunctionPass::getAnalysisUsage(AU);
58    }
59
60    bool runOnMachineFunction(MachineFunction &MF);
61
62    const bool allowVirtDoubleDefs;
63    const bool allowPhysDoubleDefs;
64
65    const char *const OutFileName;
66    raw_ostream *OS;
67    const MachineFunction *MF;
68    const TargetMachine *TM;
69    const TargetRegisterInfo *TRI;
70    const MachineRegisterInfo *MRI;
71
72    unsigned foundErrors;
73
74    typedef SmallVector<unsigned, 16> RegVector;
75    typedef DenseSet<unsigned> RegSet;
76    typedef DenseMap<unsigned, const MachineInstr*> RegMap;
77
78    BitVector regsReserved;
79    RegSet regsLive;
80    RegVector regsDefined, regsDead, regsKilled;
81    RegSet regsLiveInButUnused;
82
83    // Add Reg and any sub-registers to RV
84    void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
85      RV.push_back(Reg);
86      if (TargetRegisterInfo::isPhysicalRegister(Reg))
87        for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
88          RV.push_back(*R);
89    }
90
91    struct BBInfo {
92      // Is this MBB reachable from the MF entry point?
93      bool reachable;
94
95      // Vregs that must be live in because they are used without being
96      // defined. Map value is the user.
97      RegMap vregsLiveIn;
98
99      // Vregs that must be dead in because they are defined without being
100      // killed first. Map value is the defining instruction.
101      RegMap vregsDeadIn;
102
103      // Regs killed in MBB. They may be defined again, and will then be in both
104      // regsKilled and regsLiveOut.
105      RegSet regsKilled;
106
107      // Regs defined in MBB and live out. Note that vregs passing through may
108      // be live out without being mentioned here.
109      RegSet regsLiveOut;
110
111      // Vregs that pass through MBB untouched. This set is disjoint from
112      // regsKilled and regsLiveOut.
113      RegSet vregsPassed;
114
115      BBInfo() : reachable(false) {}
116
117      // Add register to vregsPassed if it belongs there. Return true if
118      // anything changed.
119      bool addPassed(unsigned Reg) {
120        if (!TargetRegisterInfo::isVirtualRegister(Reg))
121          return false;
122        if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
123          return false;
124        return vregsPassed.insert(Reg).second;
125      }
126
127      // Same for a full set.
128      bool addPassed(const RegSet &RS) {
129        bool changed = false;
130        for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
131          if (addPassed(*I))
132            changed = true;
133        return changed;
134      }
135
136      // Live-out registers are either in regsLiveOut or vregsPassed.
137      bool isLiveOut(unsigned Reg) const {
138        return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
139      }
140    };
141
142    // Extra register info per MBB.
143    DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
144
145    bool isReserved(unsigned Reg) {
146      return Reg < regsReserved.size() && regsReserved.test(Reg);
147    }
148
149    void visitMachineFunctionBefore();
150    void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
151    void visitMachineInstrBefore(const MachineInstr *MI);
152    void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
153    void visitMachineInstrAfter(const MachineInstr *MI);
154    void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
155    void visitMachineFunctionAfter();
156
157    void report(const char *msg, const MachineFunction *MF);
158    void report(const char *msg, const MachineBasicBlock *MBB);
159    void report(const char *msg, const MachineInstr *MI);
160    void report(const char *msg, const MachineOperand *MO, unsigned MONum);
161
162    void markReachable(const MachineBasicBlock *MBB);
163    void calcMaxRegsPassed();
164    void calcMinRegsPassed();
165    void checkPHIOps(const MachineBasicBlock *MBB);
166  };
167}
168
169char MachineVerifier::ID = 0;
170static RegisterPass<MachineVerifier>
171MachineVer("machineverifier", "Verify generated machine code");
172static const PassInfo *const MachineVerifyID = &MachineVer;
173
174FunctionPass *llvm::createMachineVerifierPass(bool allowPhysDoubleDefs) {
175  return new MachineVerifier(allowPhysDoubleDefs);
176}
177
178bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
179  raw_ostream *OutFile = 0;
180  if (OutFileName) {
181    std::string ErrorInfo;
182    OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
183                                 raw_fd_ostream::F_Append);
184    if (!ErrorInfo.empty()) {
185      errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
186      exit(1);
187    }
188
189    OS = OutFile;
190  } else {
191    OS = &errs();
192  }
193
194  foundErrors = 0;
195
196  this->MF = &MF;
197  TM = &MF.getTarget();
198  TRI = TM->getRegisterInfo();
199  MRI = &MF.getRegInfo();
200
201  visitMachineFunctionBefore();
202  for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
203       MFI!=MFE; ++MFI) {
204    visitMachineBasicBlockBefore(MFI);
205    for (MachineBasicBlock::const_iterator MBBI = MFI->begin(),
206           MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
207      visitMachineInstrBefore(MBBI);
208      for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
209        visitMachineOperand(&MBBI->getOperand(I), I);
210      visitMachineInstrAfter(MBBI);
211    }
212    visitMachineBasicBlockAfter(MFI);
213  }
214  visitMachineFunctionAfter();
215
216  if (OutFile)
217    delete OutFile;
218  else if (foundErrors)
219    llvm_report_error("Found "+Twine(foundErrors)+" machine code errors.");
220
221  // Clean up.
222  regsLive.clear();
223  regsDefined.clear();
224  regsDead.clear();
225  regsKilled.clear();
226  regsLiveInButUnused.clear();
227  MBBInfoMap.clear();
228
229  return false;                 // no changes
230}
231
232void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
233  assert(MF);
234  *OS << '\n';
235  if (!foundErrors++)
236    MF->print(*OS);
237  *OS << "*** Bad machine code: " << msg << " ***\n"
238      << "- function:    " << MF->getFunction()->getNameStr() << "\n";
239}
240
241void
242MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB)
243{
244  assert(MBB);
245  report(msg, MBB->getParent());
246  *OS << "- basic block: " << MBB->getBasicBlock()->getNameStr()
247      << " " << (void*)MBB
248      << " (#" << MBB->getNumber() << ")\n";
249}
250
251void
252MachineVerifier::report(const char *msg, const MachineInstr *MI)
253{
254  assert(MI);
255  report(msg, MI->getParent());
256  *OS << "- instruction: ";
257  MI->print(*OS, TM);
258}
259
260void
261MachineVerifier::report(const char *msg,
262                        const MachineOperand *MO, unsigned MONum)
263{
264  assert(MO);
265  report(msg, MO->getParent());
266  *OS << "- operand " << MONum << ":   ";
267  MO->print(*OS, TM);
268  *OS << "\n";
269}
270
271void
272MachineVerifier::markReachable(const MachineBasicBlock *MBB)
273{
274  BBInfo &MInfo = MBBInfoMap[MBB];
275  if (!MInfo.reachable) {
276    MInfo.reachable = true;
277    for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
278           SuE = MBB->succ_end(); SuI != SuE; ++SuI)
279      markReachable(*SuI);
280  }
281}
282
283void
284MachineVerifier::visitMachineFunctionBefore()
285{
286  regsReserved = TRI->getReservedRegs(*MF);
287
288  // A sub-register of a reserved register is also reserved
289  for (int Reg = regsReserved.find_first(); Reg>=0;
290       Reg = regsReserved.find_next(Reg)) {
291    for (const unsigned *Sub = TRI->getSubRegisters(Reg); *Sub; ++Sub) {
292      // FIXME: This should probably be:
293      // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
294      regsReserved.set(*Sub);
295    }
296  }
297  markReachable(&MF->front());
298}
299
300void
301MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB)
302{
303  const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
304
305  // Start with minimal CFG sanity checks.
306  MachineFunction::const_iterator MBBI = MBB;
307  ++MBBI;
308  if (MBBI != MF->end()) {
309    // Block is not last in function.
310    if (!MBB->isSuccessor(MBBI)) {
311      // Block does not fall through.
312      if (MBB->empty()) {
313        report("MBB doesn't fall through but is empty!", MBB);
314      }
315    } else {
316      // Block falls through.
317      if (!MBB->empty() && MBB->back().getDesc().isBarrier()) {
318        report("MBB falls through but ends with a barrier instruction!", MBB);
319      }
320      if (TII->BlockHasNoFallThrough(*MBB)) {
321        report("TargetInstrInfo says the block has no fall through, but the "
322               "CFG has a fall-through edge!", MBB);
323      }
324    }
325  } else {
326    // Block is last in function.
327    if (MBB->empty()) {
328      report("MBB is last in function but is empty!", MBB);
329    }
330  }
331
332  // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
333  MachineBasicBlock *TBB = 0, *FBB = 0;
334  SmallVector<MachineOperand, 4> Cond;
335  if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
336                          TBB, FBB, Cond)) {
337    // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
338    // check whether its answers match up with reality.
339    if (!TBB && !FBB) {
340      // Block falls through to its successor.
341      MachineFunction::const_iterator MBBI = MBB;
342      ++MBBI;
343      if (MBBI == MF->end()) {
344        // TODO: This condition is sometimes reached for functions which
345        // make noreturn calls or contain unreachable. Should AnalyzeBranch
346        // be changed to handle such cases differently?
347        report("MBB falls through out of function!", MBB);
348      } else if (MBB->succ_size() != 1) {
349        report("MBB exits via unconditional fall-through but doesn't have "
350               "exactly one CFG successor!", MBB);
351      } else if (MBB->succ_begin()[0] != MBBI) {
352        report("MBB exits via unconditional fall-through but its successor "
353               "differs from its CFG successor!", MBB);
354      }
355      if (!MBB->empty() && MBB->back().getDesc().isBarrier()) {
356        report("MBB exits via unconditional fall-through but ends with a "
357               "barrier instruction!", MBB);
358      }
359      if (!Cond.empty()) {
360        report("MBB exits via unconditional fall-through but has a condition!",
361               MBB);
362      }
363    } else if (TBB && !FBB && Cond.empty()) {
364      // Block unconditionally branches somewhere.
365      if (MBB->succ_size() != 1) {
366        report("MBB exits via unconditional branch but doesn't have "
367               "exactly one CFG successor!", MBB);
368      } else if (MBB->succ_begin()[0] != TBB) {
369        report("MBB exits via unconditional branch but the CFG "
370               "successor doesn't match the actual successor!", MBB);
371      }
372      if (MBB->empty()) {
373        report("MBB exits via unconditional branch but doesn't contain "
374               "any instructions!", MBB);
375      } else if (!MBB->back().getDesc().isBarrier()) {
376        report("MBB exits via unconditional branch but doesn't end with a "
377               "barrier instruction!", MBB);
378      } else if (!MBB->back().getDesc().isTerminator()) {
379        report("MBB exits via unconditional branch but the branch isn't a "
380               "terminator instruction!", MBB);
381      }
382    } else if (TBB && !FBB && !Cond.empty()) {
383      // Block conditionally branches somewhere, otherwise falls through.
384      MachineFunction::const_iterator MBBI = MBB;
385      ++MBBI;
386      if (MBBI == MF->end()) {
387        report("MBB conditionally falls through out of function!", MBB);
388      } if (MBB->succ_size() != 2) {
389        report("MBB exits via conditional branch/fall-through but doesn't have "
390               "exactly two CFG successors!", MBB);
391      } else if ((MBB->succ_begin()[0] == TBB && MBB->succ_end()[1] == MBBI) ||
392                 (MBB->succ_begin()[1] == TBB && MBB->succ_end()[0] == MBBI)) {
393        report("MBB exits via conditional branch/fall-through but the CFG "
394               "successors don't match the actual successors!", MBB);
395      }
396      if (MBB->empty()) {
397        report("MBB exits via conditional branch/fall-through but doesn't "
398               "contain any instructions!", MBB);
399      } else if (MBB->back().getDesc().isBarrier()) {
400        report("MBB exits via conditional branch/fall-through but ends with a "
401               "barrier instruction!", MBB);
402      } else if (!MBB->back().getDesc().isTerminator()) {
403        report("MBB exits via conditional branch/fall-through but the branch "
404               "isn't a terminator instruction!", MBB);
405      }
406    } else if (TBB && FBB) {
407      // Block conditionally branches somewhere, otherwise branches
408      // somewhere else.
409      if (MBB->succ_size() != 2) {
410        report("MBB exits via conditional branch/branch but doesn't have "
411               "exactly two CFG successors!", MBB);
412      } else if ((MBB->succ_begin()[0] == TBB && MBB->succ_end()[1] == FBB) ||
413                 (MBB->succ_begin()[1] == TBB && MBB->succ_end()[0] == FBB)) {
414        report("MBB exits via conditional branch/branch but the CFG "
415               "successors don't match the actual successors!", MBB);
416      }
417      if (MBB->empty()) {
418        report("MBB exits via conditional branch/branch but doesn't "
419               "contain any instructions!", MBB);
420      } else if (!MBB->back().getDesc().isBarrier()) {
421        report("MBB exits via conditional branch/branch but doesn't end with a "
422               "barrier instruction!", MBB);
423      } else if (!MBB->back().getDesc().isTerminator()) {
424        report("MBB exits via conditional branch/branch but the branch "
425               "isn't a terminator instruction!", MBB);
426      }
427      if (Cond.empty()) {
428        report("MBB exits via conditinal branch/branch but there's no "
429               "condition!", MBB);
430      }
431    } else {
432      report("AnalyzeBranch returned invalid data!", MBB);
433    }
434  }
435
436  regsLive.clear();
437  for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
438         E = MBB->livein_end(); I != E; ++I) {
439    if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
440      report("MBB live-in list contains non-physical register", MBB);
441      continue;
442    }
443    regsLive.insert(*I);
444    for (const unsigned *R = TRI->getSubRegisters(*I); *R; R++)
445      regsLive.insert(*R);
446  }
447  regsLiveInButUnused = regsLive;
448
449  const MachineFrameInfo *MFI = MF->getFrameInfo();
450  assert(MFI && "Function has no frame info");
451  BitVector PR = MFI->getPristineRegs(MBB);
452  for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
453    regsLive.insert(I);
454    for (const unsigned *R = TRI->getSubRegisters(I); *R; R++)
455      regsLive.insert(*R);
456  }
457
458  regsKilled.clear();
459  regsDefined.clear();
460}
461
462void
463MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI)
464{
465  const TargetInstrDesc &TI = MI->getDesc();
466  if (MI->getNumExplicitOperands() < TI.getNumOperands()) {
467    report("Too few operands", MI);
468    *OS << TI.getNumOperands() << " operands expected, but "
469        << MI->getNumExplicitOperands() << " given.\n";
470  }
471  if (!TI.isVariadic()) {
472    if (MI->getNumExplicitOperands() > TI.getNumOperands()) {
473      report("Too many operands", MI);
474      *OS << TI.getNumOperands() << " operands expected, but "
475          << MI->getNumExplicitOperands() << " given.\n";
476    }
477  }
478}
479
480void
481MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum)
482{
483  const MachineInstr *MI = MO->getParent();
484  const TargetInstrDesc &TI = MI->getDesc();
485
486  // The first TI.NumDefs operands must be explicit register defines
487  if (MONum < TI.getNumDefs()) {
488    if (!MO->isReg())
489      report("Explicit definition must be a register", MO, MONum);
490    else if (!MO->isDef())
491      report("Explicit definition marked as use", MO, MONum);
492    else if (MO->isImplicit())
493      report("Explicit definition marked as implicit", MO, MONum);
494  }
495
496  switch (MO->getType()) {
497  case MachineOperand::MO_Register: {
498    const unsigned Reg = MO->getReg();
499    if (!Reg)
500      return;
501
502    // Check Live Variables.
503    if (MO->isUndef()) {
504      // An <undef> doesn't refer to any register, so just skip it.
505    } else if (MO->isUse()) {
506      regsLiveInButUnused.erase(Reg);
507
508      if (MO->isKill()) {
509        addRegWithSubRegs(regsKilled, Reg);
510        // Tied operands on two-address instuctions MUST NOT have a <kill> flag.
511        if (MI->isRegTiedToDefOperand(MONum))
512            report("Illegal kill flag on two-address instruction operand",
513                   MO, MONum);
514      } else {
515        // TwoAddress instr modifying a reg is treated as kill+def.
516        unsigned defIdx;
517        if (MI->isRegTiedToDefOperand(MONum, &defIdx) &&
518            MI->getOperand(defIdx).getReg() == Reg)
519          addRegWithSubRegs(regsKilled, Reg);
520      }
521      // Use of a dead register.
522      if (!regsLive.count(Reg)) {
523        if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
524          // Reserved registers may be used even when 'dead'.
525          if (!isReserved(Reg))
526            report("Using an undefined physical register", MO, MONum);
527        } else {
528          BBInfo &MInfo = MBBInfoMap[MI->getParent()];
529          // We don't know which virtual registers are live in, so only complain
530          // if vreg was killed in this MBB. Otherwise keep track of vregs that
531          // must be live in. PHI instructions are handled separately.
532          if (MInfo.regsKilled.count(Reg))
533            report("Using a killed virtual register", MO, MONum);
534          else if (MI->getOpcode() != TargetInstrInfo::PHI)
535            MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
536        }
537      }
538    } else {
539      assert(MO->isDef());
540      // Register defined.
541      // TODO: verify that earlyclobber ops are not used.
542      if (MO->isDead())
543        addRegWithSubRegs(regsDead, Reg);
544      else
545        addRegWithSubRegs(regsDefined, Reg);
546    }
547
548    // Check register classes.
549    if (MONum < TI.getNumOperands() && !MO->isImplicit()) {
550      const TargetOperandInfo &TOI = TI.OpInfo[MONum];
551      unsigned SubIdx = MO->getSubReg();
552
553      if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
554        unsigned sr = Reg;
555        if (SubIdx) {
556          unsigned s = TRI->getSubReg(Reg, SubIdx);
557          if (!s) {
558            report("Invalid subregister index for physical register",
559                   MO, MONum);
560            return;
561          }
562          sr = s;
563        }
564        if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
565          if (!DRC->contains(sr)) {
566            report("Illegal physical register for instruction", MO, MONum);
567            *OS << TRI->getName(sr) << " is not a "
568                << DRC->getName() << " register.\n";
569          }
570        }
571      } else {
572        // Virtual register.
573        const TargetRegisterClass *RC = MRI->getRegClass(Reg);
574        if (SubIdx) {
575          if (RC->subregclasses_begin()+SubIdx >= RC->subregclasses_end()) {
576            report("Invalid subregister index for virtual register", MO, MONum);
577            return;
578          }
579          RC = *(RC->subregclasses_begin()+SubIdx);
580        }
581        if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
582          if (RC != DRC && !RC->hasSuperClass(DRC)) {
583            report("Illegal virtual register for instruction", MO, MONum);
584            *OS << "Expected a " << DRC->getName() << " register, but got a "
585                << RC->getName() << " register\n";
586          }
587        }
588      }
589    }
590    break;
591  }
592    // Can PHI instrs refer to MBBs not in the CFG? X86 and ARM do.
593    // case MachineOperand::MO_MachineBasicBlock:
594    //   if (MI->getOpcode() == TargetInstrInfo::PHI) {
595    //     if (!MO->getMBB()->isSuccessor(MI->getParent()))
596    //       report("PHI operand is not in the CFG", MO, MONum);
597    //   }
598    //   break;
599  default:
600    break;
601  }
602}
603
604void
605MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI)
606{
607  BBInfo &MInfo = MBBInfoMap[MI->getParent()];
608  set_union(MInfo.regsKilled, regsKilled);
609  set_subtract(regsLive, regsKilled);
610  regsKilled.clear();
611
612  // Verify that both <def> and <def,dead> operands refer to dead registers.
613  RegVector defs(regsDefined);
614  defs.append(regsDead.begin(), regsDead.end());
615
616  for (RegVector::const_iterator I = defs.begin(), E = defs.end();
617       I != E; ++I) {
618    if (regsLive.count(*I)) {
619      if (TargetRegisterInfo::isPhysicalRegister(*I)) {
620        if (!allowPhysDoubleDefs && !isReserved(*I) &&
621            !regsLiveInButUnused.count(*I)) {
622          report("Redefining a live physical register", MI);
623          *OS << "Register " << TRI->getName(*I)
624              << " was defined but already live.\n";
625        }
626      } else {
627        if (!allowVirtDoubleDefs) {
628          report("Redefining a live virtual register", MI);
629          *OS << "Virtual register %reg" << *I
630              << " was defined but already live.\n";
631        }
632      }
633    } else if (TargetRegisterInfo::isVirtualRegister(*I) &&
634               !MInfo.regsKilled.count(*I)) {
635      // Virtual register defined without being killed first must be dead on
636      // entry.
637      MInfo.vregsDeadIn.insert(std::make_pair(*I, MI));
638    }
639  }
640
641  set_subtract(regsLive, regsDead); regsDead.clear();
642  set_union(regsLive, regsDefined); regsDefined.clear();
643}
644
645void
646MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB)
647{
648  MBBInfoMap[MBB].regsLiveOut = regsLive;
649  regsLive.clear();
650}
651
652// Calculate the largest possible vregsPassed sets. These are the registers that
653// can pass through an MBB live, but may not be live every time. It is assumed
654// that all vregsPassed sets are empty before the call.
655void
656MachineVerifier::calcMaxRegsPassed()
657{
658  // First push live-out regs to successors' vregsPassed. Remember the MBBs that
659  // have any vregsPassed.
660  DenseSet<const MachineBasicBlock*> todo;
661  for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
662       MFI != MFE; ++MFI) {
663    const MachineBasicBlock &MBB(*MFI);
664    BBInfo &MInfo = MBBInfoMap[&MBB];
665    if (!MInfo.reachable)
666      continue;
667    for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
668           SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
669      BBInfo &SInfo = MBBInfoMap[*SuI];
670      if (SInfo.addPassed(MInfo.regsLiveOut))
671        todo.insert(*SuI);
672    }
673  }
674
675  // Iteratively push vregsPassed to successors. This will converge to the same
676  // final state regardless of DenseSet iteration order.
677  while (!todo.empty()) {
678    const MachineBasicBlock *MBB = *todo.begin();
679    todo.erase(MBB);
680    BBInfo &MInfo = MBBInfoMap[MBB];
681    for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
682           SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
683      if (*SuI == MBB)
684        continue;
685      BBInfo &SInfo = MBBInfoMap[*SuI];
686      if (SInfo.addPassed(MInfo.vregsPassed))
687        todo.insert(*SuI);
688    }
689  }
690}
691
692// Calculate the minimum vregsPassed set. These are the registers that always
693// pass live through an MBB. The calculation assumes that calcMaxRegsPassed has
694// been called earlier.
695void
696MachineVerifier::calcMinRegsPassed()
697{
698  DenseSet<const MachineBasicBlock*> todo;
699  for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
700       MFI != MFE; ++MFI)
701    todo.insert(MFI);
702
703  while (!todo.empty()) {
704    const MachineBasicBlock *MBB = *todo.begin();
705    todo.erase(MBB);
706    BBInfo &MInfo = MBBInfoMap[MBB];
707
708    // Remove entries from vRegsPassed that are not live out from all
709    // reachable predecessors.
710    RegSet dead;
711    for (RegSet::iterator I = MInfo.vregsPassed.begin(),
712           E = MInfo.vregsPassed.end(); I != E; ++I) {
713      for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
714             PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
715        BBInfo &PrInfo = MBBInfoMap[*PrI];
716        if (PrInfo.reachable && !PrInfo.isLiveOut(*I)) {
717          dead.insert(*I);
718          break;
719        }
720      }
721    }
722    // If any regs removed, we need to recheck successors.
723    if (!dead.empty()) {
724      set_subtract(MInfo.vregsPassed, dead);
725      todo.insert(MBB->succ_begin(), MBB->succ_end());
726    }
727  }
728}
729
730// Check PHI instructions at the beginning of MBB. It is assumed that
731// calcMinRegsPassed has been run so BBInfo::isLiveOut is valid.
732void
733MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB)
734{
735  for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
736       BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI) {
737    DenseSet<const MachineBasicBlock*> seen;
738
739    for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
740      unsigned Reg = BBI->getOperand(i).getReg();
741      const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
742      if (!Pre->isSuccessor(MBB))
743        continue;
744      seen.insert(Pre);
745      BBInfo &PrInfo = MBBInfoMap[Pre];
746      if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
747        report("PHI operand is not live-out from predecessor",
748               &BBI->getOperand(i), i);
749    }
750
751    // Did we see all predecessors?
752    for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
753           PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
754      if (!seen.count(*PrI)) {
755        report("Missing PHI operand", BBI);
756        *OS << "MBB #" << (*PrI)->getNumber()
757            << " is a predecessor according to the CFG.\n";
758      }
759    }
760  }
761}
762
763void
764MachineVerifier::visitMachineFunctionAfter()
765{
766  calcMaxRegsPassed();
767
768  // With the maximal set of vregsPassed we can verify dead-in registers.
769  for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
770       MFI != MFE; ++MFI) {
771    BBInfo &MInfo = MBBInfoMap[MFI];
772
773    // Skip unreachable MBBs.
774    if (!MInfo.reachable)
775      continue;
776
777    for (MachineBasicBlock::const_pred_iterator PrI = MFI->pred_begin(),
778           PrE = MFI->pred_end(); PrI != PrE; ++PrI) {
779      BBInfo &PrInfo = MBBInfoMap[*PrI];
780      if (!PrInfo.reachable)
781        continue;
782
783      // Verify physical live-ins. EH landing pads have magic live-ins so we
784      // ignore them.
785      if (!MFI->isLandingPad()) {
786        for (MachineBasicBlock::const_livein_iterator I = MFI->livein_begin(),
787               E = MFI->livein_end(); I != E; ++I) {
788          if (TargetRegisterInfo::isPhysicalRegister(*I) &&
789              !isReserved (*I) && !PrInfo.isLiveOut(*I)) {
790            report("Live-in physical register is not live-out from predecessor",
791                   MFI);
792            *OS << "Register " << TRI->getName(*I)
793                << " is not live-out from MBB #" << (*PrI)->getNumber()
794                << ".\n";
795          }
796        }
797      }
798
799
800      // Verify dead-in virtual registers.
801      if (!allowVirtDoubleDefs) {
802        for (RegMap::iterator I = MInfo.vregsDeadIn.begin(),
803               E = MInfo.vregsDeadIn.end(); I != E; ++I) {
804          // DeadIn register must be in neither regsLiveOut or vregsPassed of
805          // any predecessor.
806          if (PrInfo.isLiveOut(I->first)) {
807            report("Live-in virtual register redefined", I->second);
808            *OS << "Register %reg" << I->first
809                << " was live-out from predecessor MBB #"
810                << (*PrI)->getNumber() << ".\n";
811          }
812        }
813      }
814    }
815  }
816
817  calcMinRegsPassed();
818
819  // With the minimal set of vregsPassed we can verify live-in virtual
820  // registers, including PHI instructions.
821  for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
822       MFI != MFE; ++MFI) {
823    BBInfo &MInfo = MBBInfoMap[MFI];
824
825    // Skip unreachable MBBs.
826    if (!MInfo.reachable)
827      continue;
828
829    checkPHIOps(MFI);
830
831    for (MachineBasicBlock::const_pred_iterator PrI = MFI->pred_begin(),
832           PrE = MFI->pred_end(); PrI != PrE; ++PrI) {
833      BBInfo &PrInfo = MBBInfoMap[*PrI];
834      if (!PrInfo.reachable)
835        continue;
836
837      for (RegMap::iterator I = MInfo.vregsLiveIn.begin(),
838             E = MInfo.vregsLiveIn.end(); I != E; ++I) {
839        if (!PrInfo.isLiveOut(I->first)) {
840          report("Used virtual register is not live-in", I->second);
841          *OS << "Register %reg" << I->first
842              << " is not live-out from predecessor MBB #"
843              << (*PrI)->getNumber()
844              << ".\n";
845        }
846      }
847    }
848  }
849}
850