Add SSA verification to MachineVerifier.
[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 uint16_t *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 uint16_t *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 uint16_t *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 uint16_t *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   SmallPtrSet<const MachineBasicBlock*, 8> 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   SmallPtrSet<const MachineBasicBlock*, 8> 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   SmallPtrSet<const MachineBasicBlock*, 8> seen;
974   for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
975        BBI != BBE && BBI->isPHI(); ++BBI) {
976     seen.clear();
977
978     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
979       unsigned Reg = BBI->getOperand(i).getReg();
980       const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
981       if (!Pre->isSuccessor(MBB))
982         continue;
983       seen.insert(Pre);
984       BBInfo &PrInfo = MBBInfoMap[Pre];
985       if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
986         report("PHI operand is not live-out from predecessor",
987                &BBI->getOperand(i), i);
988     }
989
990     // Did we see all predecessors?
991     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
992            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
993       if (!seen.count(*PrI)) {
994         report("Missing PHI operand", BBI);
995         *OS << "BB#" << (*PrI)->getNumber()
996             << " is a predecessor according to the CFG.\n";
997       }
998     }
999   }
1000 }
1001
1002 void MachineVerifier::visitMachineFunctionAfter() {
1003   calcRegsPassed();
1004
1005   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1006        MFI != MFE; ++MFI) {
1007     BBInfo &MInfo = MBBInfoMap[MFI];
1008
1009     // Skip unreachable MBBs.
1010     if (!MInfo.reachable)
1011       continue;
1012
1013     checkPHIOps(MFI);
1014   }
1015
1016   // Now check liveness info if available
1017   calcRegsRequired();
1018
1019   if (MRI->isSSA() && !MF->empty()) {
1020     BBInfo &MInfo = MBBInfoMap[&MF->front()];
1021     for (RegSet::iterator
1022          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1023          ++I) {
1024       report("Virtual register def doesn't dominate all uses.", MF);
1025       *OS << "- register:\t" << PrintReg(*I) << '\n';
1026     }
1027   }
1028
1029   if (LiveVars)
1030     verifyLiveVariables();
1031   if (LiveInts)
1032     verifyLiveIntervals();
1033 }
1034
1035 void MachineVerifier::verifyLiveVariables() {
1036   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1037   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1038     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1039     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1040     for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1041          MFI != MFE; ++MFI) {
1042       BBInfo &MInfo = MBBInfoMap[MFI];
1043
1044       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1045       if (MInfo.vregsRequired.count(Reg)) {
1046         if (!VI.AliveBlocks.test(MFI->getNumber())) {
1047           report("LiveVariables: Block missing from AliveBlocks", MFI);
1048           *OS << "Virtual register " << PrintReg(Reg)
1049               << " must be live through the block.\n";
1050         }
1051       } else {
1052         if (VI.AliveBlocks.test(MFI->getNumber())) {
1053           report("LiveVariables: Block should not be in AliveBlocks", MFI);
1054           *OS << "Virtual register " << PrintReg(Reg)
1055               << " is not needed live through the block.\n";
1056         }
1057       }
1058     }
1059   }
1060 }
1061
1062 void MachineVerifier::verifyLiveIntervals() {
1063   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1064   for (LiveIntervals::const_iterator LVI = LiveInts->begin(),
1065        LVE = LiveInts->end(); LVI != LVE; ++LVI) {
1066     const LiveInterval &LI = *LVI->second;
1067
1068     // Spilling and splitting may leave unused registers around. Skip them.
1069     if (MRI->use_empty(LI.reg))
1070       continue;
1071
1072     // Physical registers have much weirdness going on, mostly from coalescing.
1073     // We should probably fix it, but for now just ignore them.
1074     if (TargetRegisterInfo::isPhysicalRegister(LI.reg))
1075       continue;
1076
1077     assert(LVI->first == LI.reg && "Invalid reg to interval mapping");
1078
1079     for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
1080          I!=E; ++I) {
1081       VNInfo *VNI = *I;
1082       const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
1083
1084       if (!DefVNI) {
1085         if (!VNI->isUnused()) {
1086           report("Valno not live at def and not marked unused", MF);
1087           *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1088         }
1089         continue;
1090       }
1091
1092       if (VNI->isUnused())
1093         continue;
1094
1095       if (DefVNI != VNI) {
1096         report("Live range at def has different valno", MF);
1097         *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1098             << " where valno #" << DefVNI->id << " is live in " << LI << '\n';
1099         continue;
1100       }
1101
1102       const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1103       if (!MBB) {
1104         report("Invalid definition index", MF);
1105         *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1106             << " in " << LI << '\n';
1107         continue;
1108       }
1109
1110       if (VNI->isPHIDef()) {
1111         if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1112           report("PHIDef value is not defined at MBB start", MF);
1113           *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1114               << ", not at the beginning of BB#" << MBB->getNumber()
1115               << " in " << LI << '\n';
1116         }
1117       } else {
1118         // Non-PHI def.
1119         const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1120         if (!MI) {
1121           report("No instruction at def index", MF);
1122           *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1123               << " in " << LI << '\n';
1124           continue;
1125         }
1126
1127         bool hasDef = false;
1128         bool isEarlyClobber = false;
1129         for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1130           if (!MOI->isReg() || !MOI->isDef())
1131             continue;
1132           if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1133             if (MOI->getReg() != LI.reg)
1134               continue;
1135           } else {
1136             if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1137                 !TRI->regsOverlap(LI.reg, MOI->getReg()))
1138               continue;
1139           }
1140           hasDef = true;
1141           if (MOI->isEarlyClobber())
1142             isEarlyClobber = true;
1143         }
1144
1145         if (!hasDef) {
1146           report("Defining instruction does not modify register", MI);
1147           *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1148         }
1149
1150         // Early clobber defs begin at USE slots, but other defs must begin at
1151         // DEF slots.
1152         if (isEarlyClobber) {
1153           if (!VNI->def.isEarlyClobber()) {
1154             report("Early clobber def must be at an early-clobber slot", MF);
1155             *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1156                 << " in " << LI << '\n';
1157           }
1158         } else if (!VNI->def.isRegister()) {
1159           report("Non-PHI, non-early clobber def must be at a register slot",
1160                  MF);
1161           *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1162               << " in " << LI << '\n';
1163         }
1164       }
1165     }
1166
1167     for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I) {
1168       const VNInfo *VNI = I->valno;
1169       assert(VNI && "Live range has no valno");
1170
1171       if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
1172         report("Foreign valno in live range", MF);
1173         I->print(*OS);
1174         *OS << " has a valno not in " << LI << '\n';
1175       }
1176
1177       if (VNI->isUnused()) {
1178         report("Live range valno is marked unused", MF);
1179         I->print(*OS);
1180         *OS << " in " << LI << '\n';
1181       }
1182
1183       const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
1184       if (!MBB) {
1185         report("Bad start of live segment, no basic block", MF);
1186         I->print(*OS);
1187         *OS << " in " << LI << '\n';
1188         continue;
1189       }
1190       SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1191       if (I->start != MBBStartIdx && I->start != VNI->def) {
1192         report("Live segment must begin at MBB entry or valno def", MBB);
1193         I->print(*OS);
1194         *OS << " in " << LI << '\n' << "Basic block starts at "
1195             << MBBStartIdx << '\n';
1196       }
1197
1198       const MachineBasicBlock *EndMBB =
1199                                 LiveInts->getMBBFromIndex(I->end.getPrevSlot());
1200       if (!EndMBB) {
1201         report("Bad end of live segment, no basic block", MF);
1202         I->print(*OS);
1203         *OS << " in " << LI << '\n';
1204         continue;
1205       }
1206
1207       // No more checks for live-out segments.
1208       if (I->end == LiveInts->getMBBEndIdx(EndMBB))
1209         continue;
1210
1211       // The live segment is ending inside EndMBB
1212       const MachineInstr *MI =
1213         LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
1214       if (!MI) {
1215         report("Live segment doesn't end at a valid instruction", EndMBB);
1216         I->print(*OS);
1217         *OS << " in " << LI << '\n' << "Basic block starts at "
1218           << MBBStartIdx << '\n';
1219         continue;
1220       }
1221
1222       // The block slot must refer to a basic block boundary.
1223       if (I->end.isBlock()) {
1224         report("Live segment ends at B slot of an instruction", MI);
1225         I->print(*OS);
1226         *OS << " in " << LI << '\n';
1227       }
1228
1229       if (I->end.isDead()) {
1230         // Segment ends on the dead slot.
1231         // That means there must be a dead def.
1232         if (!SlotIndex::isSameInstr(I->start, I->end)) {
1233           report("Live segment ending at dead slot spans instructions", MI);
1234           I->print(*OS);
1235           *OS << " in " << LI << '\n';
1236         }
1237       }
1238
1239       // A live segment can only end at an early-clobber slot if it is being
1240       // redefined by an early-clobber def.
1241       if (I->end.isEarlyClobber()) {
1242         if (I+1 == E || (I+1)->start != I->end) {
1243           report("Live segment ending at early clobber slot must be "
1244                  "redefined by an EC def in the same instruction", MI);
1245           I->print(*OS);
1246           *OS << " in " << LI << '\n';
1247         }
1248       }
1249
1250       // The following checks only apply to virtual registers. Physreg liveness
1251       // is too weird to check.
1252       if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1253         // A live range can end with either a redefinition, a kill flag on a
1254         // use, or a dead flag on a def.
1255         bool hasRead = false;
1256         bool hasDeadDef = false;
1257         for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1258           if (!MOI->isReg() || MOI->getReg() != LI.reg)
1259             continue;
1260           if (MOI->readsReg())
1261             hasRead = true;
1262           if (MOI->isDef() && MOI->isDead())
1263             hasDeadDef = true;
1264         }
1265
1266         if (I->end.isDead()) {
1267           if (!hasDeadDef) {
1268             report("Instruction doesn't have a dead def operand", MI);
1269             I->print(*OS);
1270             *OS << " in " << LI << '\n';
1271           }
1272         } else {
1273           if (!hasRead) {
1274             report("Instruction ending live range doesn't read the register",
1275                    MI);
1276             I->print(*OS);
1277             *OS << " in " << LI << '\n';
1278           }
1279         }
1280       }
1281
1282       // Now check all the basic blocks in this live segment.
1283       MachineFunction::const_iterator MFI = MBB;
1284       // Is this live range the beginning of a non-PHIDef VN?
1285       if (I->start == VNI->def && !VNI->isPHIDef()) {
1286         // Not live-in to any blocks.
1287         if (MBB == EndMBB)
1288           continue;
1289         // Skip this block.
1290         ++MFI;
1291       }
1292       for (;;) {
1293         assert(LiveInts->isLiveInToMBB(LI, MFI));
1294         // We don't know how to track physregs into a landing pad.
1295         if (TargetRegisterInfo::isPhysicalRegister(LI.reg) &&
1296             MFI->isLandingPad()) {
1297           if (&*MFI == EndMBB)
1298             break;
1299           ++MFI;
1300           continue;
1301         }
1302         // Check that VNI is live-out of all predecessors.
1303         for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1304              PE = MFI->pred_end(); PI != PE; ++PI) {
1305           SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1306           const VNInfo *PVNI = LI.getVNInfoBefore(PEnd);
1307
1308           if (VNI->isPHIDef() && VNI->def == LiveInts->getMBBStartIdx(MFI))
1309             continue;
1310
1311           if (!PVNI) {
1312             report("Register not marked live out of predecessor", *PI);
1313             *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1314                 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1315                 << PEnd << " in " << LI << '\n';
1316             continue;
1317           }
1318
1319           if (PVNI != VNI) {
1320             report("Different value live out of predecessor", *PI);
1321             *OS << "Valno #" << PVNI->id << " live out of BB#"
1322                 << (*PI)->getNumber() << '@' << PEnd
1323                 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1324                 << '@' << LiveInts->getMBBStartIdx(MFI) << " in " << LI << '\n';
1325           }
1326         }
1327         if (&*MFI == EndMBB)
1328           break;
1329         ++MFI;
1330       }
1331     }
1332
1333     // Check the LI only has one connected component.
1334     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1335       ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1336       unsigned NumComp = ConEQ.Classify(&LI);
1337       if (NumComp > 1) {
1338         report("Multiple connected components in live interval", MF);
1339         *OS << NumComp << " components in " << LI << '\n';
1340         for (unsigned comp = 0; comp != NumComp; ++comp) {
1341           *OS << comp << ": valnos";
1342           for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1343                E = LI.vni_end(); I!=E; ++I)
1344             if (comp == ConEQ.getEqClass(*I))
1345               *OS << ' ' << (*I)->id;
1346           *OS << '\n';
1347         }
1348       }
1349     }
1350   }
1351 }
1352