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