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