Disable more of physical register live intervals verification.
[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/Function.h"
27 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
28 #include "llvm/CodeGen/LiveVariables.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/SetOperations.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 using namespace llvm;
44
45 namespace {
46   struct MachineVerifier {
47
48     MachineVerifier(Pass *pass) :
49       PASS(pass),
50       OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
51       {}
52
53     bool runOnMachineFunction(MachineFunction &MF);
54
55     Pass *const PASS;
56     const char *const OutFileName;
57     raw_ostream *OS;
58     const MachineFunction *MF;
59     const TargetMachine *TM;
60     const TargetRegisterInfo *TRI;
61     const MachineRegisterInfo *MRI;
62
63     unsigned foundErrors;
64
65     typedef SmallVector<unsigned, 16> RegVector;
66     typedef DenseSet<unsigned> RegSet;
67     typedef DenseMap<unsigned, const MachineInstr*> RegMap;
68
69     BitVector regsReserved;
70     RegSet regsLive;
71     RegVector regsDefined, regsDead, regsKilled;
72     RegSet regsLiveInButUnused;
73
74     // Add Reg and any sub-registers to RV
75     void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
76       RV.push_back(Reg);
77       if (TargetRegisterInfo::isPhysicalRegister(Reg))
78         for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
79           RV.push_back(*R);
80     }
81
82     struct BBInfo {
83       // Is this MBB reachable from the MF entry point?
84       bool reachable;
85
86       // Vregs that must be live in because they are used without being
87       // defined. Map value is the user.
88       RegMap vregsLiveIn;
89
90       // Regs killed in MBB. They may be defined again, and will then be in both
91       // regsKilled and regsLiveOut.
92       RegSet regsKilled;
93
94       // Regs defined in MBB and live out. Note that vregs passing through may
95       // be live out without being mentioned here.
96       RegSet regsLiveOut;
97
98       // Vregs that pass through MBB untouched. This set is disjoint from
99       // regsKilled and regsLiveOut.
100       RegSet vregsPassed;
101
102       // Vregs that must pass through MBB because they are needed by a successor
103       // block. This set is disjoint from regsLiveOut.
104       RegSet vregsRequired;
105
106       BBInfo() : reachable(false) {}
107
108       // Add register to vregsPassed if it belongs there. Return true if
109       // anything changed.
110       bool addPassed(unsigned Reg) {
111         if (!TargetRegisterInfo::isVirtualRegister(Reg))
112           return false;
113         if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
114           return false;
115         return vregsPassed.insert(Reg).second;
116       }
117
118       // Same for a full set.
119       bool addPassed(const RegSet &RS) {
120         bool changed = false;
121         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
122           if (addPassed(*I))
123             changed = true;
124         return changed;
125       }
126
127       // Add register to vregsRequired if it belongs there. Return true if
128       // anything changed.
129       bool addRequired(unsigned Reg) {
130         if (!TargetRegisterInfo::isVirtualRegister(Reg))
131           return false;
132         if (regsLiveOut.count(Reg))
133           return false;
134         return vregsRequired.insert(Reg).second;
135       }
136
137       // Same for a full set.
138       bool addRequired(const RegSet &RS) {
139         bool changed = false;
140         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
141           if (addRequired(*I))
142             changed = true;
143         return changed;
144       }
145
146       // Same for a full map.
147       bool addRequired(const RegMap &RM) {
148         bool changed = false;
149         for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
150           if (addRequired(I->first))
151             changed = true;
152         return changed;
153       }
154
155       // Live-out registers are either in regsLiveOut or vregsPassed.
156       bool isLiveOut(unsigned Reg) const {
157         return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
158       }
159     };
160
161     // Extra register info per MBB.
162     DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
163
164     bool isReserved(unsigned Reg) {
165       return Reg < regsReserved.size() && regsReserved.test(Reg);
166     }
167
168     // Analysis information if available
169     LiveVariables *LiveVars;
170     LiveIntervals *LiveInts;
171     SlotIndexes *Indexes;
172
173     void visitMachineFunctionBefore();
174     void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
175     void visitMachineInstrBefore(const MachineInstr *MI);
176     void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
177     void visitMachineInstrAfter(const MachineInstr *MI);
178     void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
179     void visitMachineFunctionAfter();
180
181     void report(const char *msg, const MachineFunction *MF);
182     void report(const char *msg, const MachineBasicBlock *MBB);
183     void report(const char *msg, const MachineInstr *MI);
184     void report(const char *msg, const MachineOperand *MO, unsigned MONum);
185
186     void markReachable(const MachineBasicBlock *MBB);
187     void calcRegsPassed();
188     void checkPHIOps(const MachineBasicBlock *MBB);
189
190     void calcRegsRequired();
191     void verifyLiveVariables();
192     void verifyLiveIntervals();
193   };
194
195   struct MachineVerifierPass : public MachineFunctionPass {
196     static char ID; // Pass ID, replacement for typeid
197
198     MachineVerifierPass()
199       : MachineFunctionPass(ID) {
200         initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
201       }
202
203     void getAnalysisUsage(AnalysisUsage &AU) const {
204       AU.setPreservesAll();
205       MachineFunctionPass::getAnalysisUsage(AU);
206     }
207
208     bool runOnMachineFunction(MachineFunction &MF) {
209       MF.verify(this);
210       return false;
211     }
212   };
213
214 }
215
216 char MachineVerifierPass::ID = 0;
217 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
218                 "Verify generated machine code", false, false)
219
220 FunctionPass *llvm::createMachineVerifierPass() {
221   return new MachineVerifierPass();
222 }
223
224 void MachineFunction::verify(Pass *p) const {
225   MachineVerifier(p).runOnMachineFunction(const_cast<MachineFunction&>(*this));
226 }
227
228 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
229   raw_ostream *OutFile = 0;
230   if (OutFileName) {
231     std::string ErrorInfo;
232     OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
233                                  raw_fd_ostream::F_Append);
234     if (!ErrorInfo.empty()) {
235       errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
236       exit(1);
237     }
238
239     OS = OutFile;
240   } else {
241     OS = &errs();
242   }
243
244   foundErrors = 0;
245
246   this->MF = &MF;
247   TM = &MF.getTarget();
248   TRI = TM->getRegisterInfo();
249   MRI = &MF.getRegInfo();
250
251   LiveVars = NULL;
252   LiveInts = NULL;
253   Indexes = NULL;
254   if (PASS) {
255     LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
256     // We don't want to verify LiveVariables if LiveIntervals is available.
257     if (!LiveInts)
258       LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
259     Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
260   }
261
262   visitMachineFunctionBefore();
263   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
264        MFI!=MFE; ++MFI) {
265     visitMachineBasicBlockBefore(MFI);
266     for (MachineBasicBlock::const_iterator MBBI = MFI->begin(),
267            MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
268       visitMachineInstrBefore(MBBI);
269       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
270         visitMachineOperand(&MBBI->getOperand(I), I);
271       visitMachineInstrAfter(MBBI);
272     }
273     visitMachineBasicBlockAfter(MFI);
274   }
275   visitMachineFunctionAfter();
276
277   if (OutFile)
278     delete OutFile;
279   else if (foundErrors)
280     report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
281
282   // Clean up.
283   regsLive.clear();
284   regsDefined.clear();
285   regsDead.clear();
286   regsKilled.clear();
287   regsLiveInButUnused.clear();
288   MBBInfoMap.clear();
289
290   return false;                 // no changes
291 }
292
293 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
294   assert(MF);
295   *OS << '\n';
296   if (!foundErrors++)
297     MF->print(*OS, Indexes);
298   *OS << "*** Bad machine code: " << msg << " ***\n"
299       << "- function:    " << MF->getFunction()->getNameStr() << "\n";
300 }
301
302 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
303   assert(MBB);
304   report(msg, MBB->getParent());
305   *OS << "- basic block: " << MBB->getName()
306       << " " << (void*)MBB
307       << " (BB#" << MBB->getNumber() << ")";
308   if (Indexes)
309     *OS << " [" << Indexes->getMBBStartIdx(MBB)
310         << ';' <<  Indexes->getMBBEndIdx(MBB) << ')';
311   *OS << '\n';
312 }
313
314 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
315   assert(MI);
316   report(msg, MI->getParent());
317   *OS << "- instruction: ";
318   if (Indexes && Indexes->hasIndex(MI))
319     *OS << Indexes->getInstructionIndex(MI) << '\t';
320   MI->print(*OS, TM);
321 }
322
323 void MachineVerifier::report(const char *msg,
324                              const MachineOperand *MO, unsigned MONum) {
325   assert(MO);
326   report(msg, MO->getParent());
327   *OS << "- operand " << MONum << ":   ";
328   MO->print(*OS, TM);
329   *OS << "\n";
330 }
331
332 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
333   BBInfo &MInfo = MBBInfoMap[MBB];
334   if (!MInfo.reachable) {
335     MInfo.reachable = true;
336     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
337            SuE = MBB->succ_end(); SuI != SuE; ++SuI)
338       markReachable(*SuI);
339   }
340 }
341
342 void MachineVerifier::visitMachineFunctionBefore() {
343   regsReserved = TRI->getReservedRegs(*MF);
344
345   // A sub-register of a reserved register is also reserved
346   for (int Reg = regsReserved.find_first(); Reg>=0;
347        Reg = regsReserved.find_next(Reg)) {
348     for (const unsigned *Sub = TRI->getSubRegisters(Reg); *Sub; ++Sub) {
349       // FIXME: This should probably be:
350       // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
351       regsReserved.set(*Sub);
352     }
353   }
354   markReachable(&MF->front());
355 }
356
357 // Does iterator point to a and b as the first two elements?
358 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
359                       const MachineBasicBlock *a, const MachineBasicBlock *b) {
360   if (*i == a)
361     return *++i == b;
362   if (*i == b)
363     return *++i == a;
364   return false;
365 }
366
367 void
368 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
369   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
370
371   // Count the number of landing pad successors.
372   unsigned LandingPadSuccs = 0;
373   for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
374        E = MBB->succ_end(); I != E; ++I)
375     LandingPadSuccs += (*I)->isLandingPad();
376   if (LandingPadSuccs > 1)
377     report("MBB has more than one landing pad successor", MBB);
378
379   // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
380   MachineBasicBlock *TBB = 0, *FBB = 0;
381   SmallVector<MachineOperand, 4> Cond;
382   if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
383                           TBB, FBB, Cond)) {
384     // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
385     // check whether its answers match up with reality.
386     if (!TBB && !FBB) {
387       // Block falls through to its successor.
388       MachineFunction::const_iterator MBBI = MBB;
389       ++MBBI;
390       if (MBBI == MF->end()) {
391         // It's possible that the block legitimately ends with a noreturn
392         // call or an unreachable, in which case it won't actually fall
393         // out the bottom of the function.
394       } else if (MBB->succ_size() == LandingPadSuccs) {
395         // It's possible that the block legitimately ends with a noreturn
396         // call or an unreachable, in which case it won't actuall fall
397         // out of the block.
398       } else if (MBB->succ_size() != 1+LandingPadSuccs) {
399         report("MBB exits via unconditional fall-through but doesn't have "
400                "exactly one CFG successor!", MBB);
401       } else if (!MBB->isSuccessor(MBBI)) {
402         report("MBB exits via unconditional fall-through but its successor "
403                "differs from its CFG successor!", MBB);
404       }
405       if (!MBB->empty() && MBB->back().getDesc().isBarrier() &&
406           !TII->isPredicated(&MBB->back())) {
407         report("MBB exits via unconditional fall-through but ends with a "
408                "barrier instruction!", MBB);
409       }
410       if (!Cond.empty()) {
411         report("MBB exits via unconditional fall-through but has a condition!",
412                MBB);
413       }
414     } else if (TBB && !FBB && Cond.empty()) {
415       // Block unconditionally branches somewhere.
416       if (MBB->succ_size() != 1+LandingPadSuccs) {
417         report("MBB exits via unconditional branch but doesn't have "
418                "exactly one CFG successor!", MBB);
419       } else if (!MBB->isSuccessor(TBB)) {
420         report("MBB exits via unconditional branch but the CFG "
421                "successor doesn't match the actual successor!", MBB);
422       }
423       if (MBB->empty()) {
424         report("MBB exits via unconditional branch but doesn't contain "
425                "any instructions!", MBB);
426       } else if (!MBB->back().getDesc().isBarrier()) {
427         report("MBB exits via unconditional branch but doesn't end with a "
428                "barrier instruction!", MBB);
429       } else if (!MBB->back().getDesc().isTerminator()) {
430         report("MBB exits via unconditional branch but the branch isn't a "
431                "terminator instruction!", MBB);
432       }
433     } else if (TBB && !FBB && !Cond.empty()) {
434       // Block conditionally branches somewhere, otherwise falls through.
435       MachineFunction::const_iterator MBBI = MBB;
436       ++MBBI;
437       if (MBBI == MF->end()) {
438         report("MBB conditionally falls through out of function!", MBB);
439       } if (MBB->succ_size() != 2) {
440         report("MBB exits via conditional branch/fall-through but doesn't have "
441                "exactly two CFG successors!", MBB);
442       } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
443         report("MBB exits via conditional branch/fall-through but the CFG "
444                "successors don't match the actual successors!", MBB);
445       }
446       if (MBB->empty()) {
447         report("MBB exits via conditional branch/fall-through but doesn't "
448                "contain any instructions!", MBB);
449       } else if (MBB->back().getDesc().isBarrier()) {
450         report("MBB exits via conditional branch/fall-through but ends with a "
451                "barrier instruction!", MBB);
452       } else if (!MBB->back().getDesc().isTerminator()) {
453         report("MBB exits via conditional branch/fall-through but the branch "
454                "isn't a terminator instruction!", MBB);
455       }
456     } else if (TBB && FBB) {
457       // Block conditionally branches somewhere, otherwise branches
458       // somewhere else.
459       if (MBB->succ_size() != 2) {
460         report("MBB exits via conditional branch/branch but doesn't have "
461                "exactly two CFG successors!", MBB);
462       } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
463         report("MBB exits via conditional branch/branch but the CFG "
464                "successors don't match the actual successors!", MBB);
465       }
466       if (MBB->empty()) {
467         report("MBB exits via conditional branch/branch but doesn't "
468                "contain any instructions!", MBB);
469       } else if (!MBB->back().getDesc().isBarrier()) {
470         report("MBB exits via conditional branch/branch but doesn't end with a "
471                "barrier instruction!", MBB);
472       } else if (!MBB->back().getDesc().isTerminator()) {
473         report("MBB exits via conditional branch/branch but the branch "
474                "isn't a terminator instruction!", MBB);
475       }
476       if (Cond.empty()) {
477         report("MBB exits via conditinal branch/branch but there's no "
478                "condition!", MBB);
479       }
480     } else {
481       report("AnalyzeBranch returned invalid data!", MBB);
482     }
483   }
484
485   regsLive.clear();
486   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
487          E = MBB->livein_end(); I != E; ++I) {
488     if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
489       report("MBB live-in list contains non-physical register", MBB);
490       continue;
491     }
492     regsLive.insert(*I);
493     for (const unsigned *R = TRI->getSubRegisters(*I); *R; R++)
494       regsLive.insert(*R);
495   }
496   regsLiveInButUnused = regsLive;
497
498   const MachineFrameInfo *MFI = MF->getFrameInfo();
499   assert(MFI && "Function has no frame info");
500   BitVector PR = MFI->getPristineRegs(MBB);
501   for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
502     regsLive.insert(I);
503     for (const unsigned *R = TRI->getSubRegisters(I); *R; R++)
504       regsLive.insert(*R);
505   }
506
507   regsKilled.clear();
508   regsDefined.clear();
509 }
510
511 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
512   const TargetInstrDesc &TI = MI->getDesc();
513   if (MI->getNumOperands() < TI.getNumOperands()) {
514     report("Too few operands", MI);
515     *OS << TI.getNumOperands() << " operands expected, but "
516         << MI->getNumExplicitOperands() << " given.\n";
517   }
518
519   // Check the MachineMemOperands for basic consistency.
520   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
521        E = MI->memoperands_end(); I != E; ++I) {
522     if ((*I)->isLoad() && !TI.mayLoad())
523       report("Missing mayLoad flag", MI);
524     if ((*I)->isStore() && !TI.mayStore())
525       report("Missing mayStore flag", MI);
526   }
527
528   // Debug values must not have a slot index.
529   // Other instructions must have one.
530   if (LiveInts) {
531     bool mapped = !LiveInts->isNotInMIMap(MI);
532     if (MI->isDebugValue()) {
533       if (mapped)
534         report("Debug instruction has a slot index", MI);
535     } else {
536       if (!mapped)
537         report("Missing slot index", MI);
538     }
539   }
540
541 }
542
543 void
544 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
545   const MachineInstr *MI = MO->getParent();
546   const TargetInstrDesc &TI = MI->getDesc();
547
548   // The first TI.NumDefs operands must be explicit register defines
549   if (MONum < TI.getNumDefs()) {
550     if (!MO->isReg())
551       report("Explicit definition must be a register", MO, MONum);
552     else if (!MO->isDef())
553       report("Explicit definition marked as use", MO, MONum);
554     else if (MO->isImplicit())
555       report("Explicit definition marked as implicit", MO, MONum);
556   } else if (MONum < TI.getNumOperands()) {
557     if (MO->isReg()) {
558       if (MO->isDef())
559         report("Explicit operand marked as def", MO, MONum);
560       if (MO->isImplicit())
561         report("Explicit operand marked as implicit", MO, MONum);
562     }
563   } else {
564     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
565     if (MO->isReg() && !MO->isImplicit() && !TI.isVariadic() && MO->getReg())
566       report("Extra explicit operand on non-variadic instruction", MO, MONum);
567   }
568
569   switch (MO->getType()) {
570   case MachineOperand::MO_Register: {
571     const unsigned Reg = MO->getReg();
572     if (!Reg)
573       return;
574
575     // Check Live Variables.
576     if (MO->isUndef()) {
577       // An <undef> doesn't refer to any register, so just skip it.
578     } else if (MO->isUse()) {
579       regsLiveInButUnused.erase(Reg);
580
581       bool isKill = false;
582       unsigned defIdx;
583       if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
584         // A two-addr use counts as a kill if use and def are the same.
585         unsigned DefReg = MI->getOperand(defIdx).getReg();
586         if (Reg == DefReg) {
587           isKill = true;
588           // ANd in that case an explicit kill flag is not allowed.
589           if (MO->isKill())
590             report("Illegal kill flag on two-address instruction operand",
591                    MO, MONum);
592         } else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
593           report("Two-address instruction operands must be identical",
594                  MO, MONum);
595         }
596       } else
597         isKill = MO->isKill();
598
599       if (isKill)
600         addRegWithSubRegs(regsKilled, Reg);
601
602       // Check that LiveVars knows this kill.
603       if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
604           MO->isKill()) {
605         LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
606         if (std::find(VI.Kills.begin(),
607                       VI.Kills.end(), MI) == VI.Kills.end())
608           report("Kill missing from LiveVariables", MO, MONum);
609       }
610
611       // Check LiveInts liveness and kill.
612       if (TargetRegisterInfo::isVirtualRegister(Reg) &&
613           LiveInts && !LiveInts->isNotInMIMap(MI)) {
614         SlotIndex UseIdx = LiveInts->getInstructionIndex(MI).getUseIndex();
615         if (LiveInts->hasInterval(Reg)) {
616           const LiveInterval &LI = LiveInts->getInterval(Reg);
617           if (!LI.liveAt(UseIdx)) {
618             report("No live range at use", MO, MONum);
619             *OS << UseIdx << " is not live in " << LI << '\n';
620           }
621           // TODO: Verify isKill == LI.killedAt.
622         } else {
623           report("Virtual register has no Live interval", MO, MONum);
624         }
625       }
626
627       // Use of a dead register.
628       if (!regsLive.count(Reg)) {
629         if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
630           // Reserved registers may be used even when 'dead'.
631           if (!isReserved(Reg))
632             report("Using an undefined physical register", MO, MONum);
633         } else {
634           BBInfo &MInfo = MBBInfoMap[MI->getParent()];
635           // We don't know which virtual registers are live in, so only complain
636           // if vreg was killed in this MBB. Otherwise keep track of vregs that
637           // must be live in. PHI instructions are handled separately.
638           if (MInfo.regsKilled.count(Reg))
639             report("Using a killed virtual register", MO, MONum);
640           else if (!MI->isPHI())
641             MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
642         }
643       }
644     } else {
645       assert(MO->isDef());
646       // Register defined.
647       // TODO: verify that earlyclobber ops are not used.
648       if (MO->isDead())
649         addRegWithSubRegs(regsDead, Reg);
650       else
651         addRegWithSubRegs(regsDefined, Reg);
652
653       // Check LiveInts for a live range, but only for virtual registers.
654       if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
655           !LiveInts->isNotInMIMap(MI)) {
656         SlotIndex DefIdx = LiveInts->getInstructionIndex(MI).getDefIndex();
657         if (LiveInts->hasInterval(Reg)) {
658           const LiveInterval &LI = LiveInts->getInterval(Reg);
659           if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
660             assert(VNI && "NULL valno is not allowed");
661             if (VNI->def != DefIdx) {
662               report("Inconsistent valno->def", MO, MONum);
663               *OS << "Valno " << VNI->id << " is not defined at "
664                   << DefIdx << " in " << LI << '\n';
665             }
666           } else {
667             report("No live range at def", MO, MONum);
668             *OS << DefIdx << " is not live in " << LI << '\n';
669           }
670         } else {
671           report("Virtual register has no Live interval", MO, MONum);
672         }
673       }
674     }
675
676     // Check register classes.
677     if (MONum < TI.getNumOperands() && !MO->isImplicit()) {
678       const TargetOperandInfo &TOI = TI.OpInfo[MONum];
679       unsigned SubIdx = MO->getSubReg();
680
681       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
682         unsigned sr = Reg;
683         if (SubIdx) {
684           unsigned s = TRI->getSubReg(Reg, SubIdx);
685           if (!s) {
686             report("Invalid subregister index for physical register",
687                    MO, MONum);
688             return;
689           }
690           sr = s;
691         }
692         if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
693           if (!DRC->contains(sr)) {
694             report("Illegal physical register for instruction", MO, MONum);
695             *OS << TRI->getName(sr) << " is not a "
696                 << DRC->getName() << " register.\n";
697           }
698         }
699       } else {
700         // Virtual register.
701         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
702         if (SubIdx) {
703           const TargetRegisterClass *SRC = RC->getSubRegisterRegClass(SubIdx);
704           if (!SRC) {
705             report("Invalid subregister index for virtual register", MO, MONum);
706             *OS << "Register class " << RC->getName()
707                 << " does not support subreg index " << SubIdx << "\n";
708             return;
709           }
710           RC = SRC;
711         }
712         if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
713           if (RC != DRC && !RC->hasSuperClass(DRC)) {
714             report("Illegal virtual register for instruction", MO, MONum);
715             *OS << "Expected a " << DRC->getName() << " register, but got a "
716                 << RC->getName() << " register\n";
717           }
718         }
719       }
720     }
721     break;
722   }
723
724   case MachineOperand::MO_MachineBasicBlock:
725     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
726       report("PHI operand is not in the CFG", MO, MONum);
727     break;
728
729   default:
730     break;
731   }
732 }
733
734 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
735   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
736   set_union(MInfo.regsKilled, regsKilled);
737   set_subtract(regsLive, regsKilled); regsKilled.clear();
738   set_subtract(regsLive, regsDead);   regsDead.clear();
739   set_union(regsLive, regsDefined);   regsDefined.clear();
740 }
741
742 void
743 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
744   MBBInfoMap[MBB].regsLiveOut = regsLive;
745   regsLive.clear();
746 }
747
748 // Calculate the largest possible vregsPassed sets. These are the registers that
749 // can pass through an MBB live, but may not be live every time. It is assumed
750 // that all vregsPassed sets are empty before the call.
751 void MachineVerifier::calcRegsPassed() {
752   // First push live-out regs to successors' vregsPassed. Remember the MBBs that
753   // have any vregsPassed.
754   DenseSet<const MachineBasicBlock*> todo;
755   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
756        MFI != MFE; ++MFI) {
757     const MachineBasicBlock &MBB(*MFI);
758     BBInfo &MInfo = MBBInfoMap[&MBB];
759     if (!MInfo.reachable)
760       continue;
761     for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
762            SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
763       BBInfo &SInfo = MBBInfoMap[*SuI];
764       if (SInfo.addPassed(MInfo.regsLiveOut))
765         todo.insert(*SuI);
766     }
767   }
768
769   // Iteratively push vregsPassed to successors. This will converge to the same
770   // final state regardless of DenseSet iteration order.
771   while (!todo.empty()) {
772     const MachineBasicBlock *MBB = *todo.begin();
773     todo.erase(MBB);
774     BBInfo &MInfo = MBBInfoMap[MBB];
775     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
776            SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
777       if (*SuI == MBB)
778         continue;
779       BBInfo &SInfo = MBBInfoMap[*SuI];
780       if (SInfo.addPassed(MInfo.vregsPassed))
781         todo.insert(*SuI);
782     }
783   }
784 }
785
786 // Calculate the set of virtual registers that must be passed through each basic
787 // block in order to satisfy the requirements of successor blocks. This is very
788 // similar to calcRegsPassed, only backwards.
789 void MachineVerifier::calcRegsRequired() {
790   // First push live-in regs to predecessors' vregsRequired.
791   DenseSet<const MachineBasicBlock*> todo;
792   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
793        MFI != MFE; ++MFI) {
794     const MachineBasicBlock &MBB(*MFI);
795     BBInfo &MInfo = MBBInfoMap[&MBB];
796     for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
797            PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
798       BBInfo &PInfo = MBBInfoMap[*PrI];
799       if (PInfo.addRequired(MInfo.vregsLiveIn))
800         todo.insert(*PrI);
801     }
802   }
803
804   // Iteratively push vregsRequired to predecessors. This will converge to the
805   // same final state regardless of DenseSet iteration order.
806   while (!todo.empty()) {
807     const MachineBasicBlock *MBB = *todo.begin();
808     todo.erase(MBB);
809     BBInfo &MInfo = MBBInfoMap[MBB];
810     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
811            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
812       if (*PrI == MBB)
813         continue;
814       BBInfo &SInfo = MBBInfoMap[*PrI];
815       if (SInfo.addRequired(MInfo.vregsRequired))
816         todo.insert(*PrI);
817     }
818   }
819 }
820
821 // Check PHI instructions at the beginning of MBB. It is assumed that
822 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
823 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
824   for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
825        BBI != BBE && BBI->isPHI(); ++BBI) {
826     DenseSet<const MachineBasicBlock*> seen;
827
828     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
829       unsigned Reg = BBI->getOperand(i).getReg();
830       const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
831       if (!Pre->isSuccessor(MBB))
832         continue;
833       seen.insert(Pre);
834       BBInfo &PrInfo = MBBInfoMap[Pre];
835       if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
836         report("PHI operand is not live-out from predecessor",
837                &BBI->getOperand(i), i);
838     }
839
840     // Did we see all predecessors?
841     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
842            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
843       if (!seen.count(*PrI)) {
844         report("Missing PHI operand", BBI);
845         *OS << "BB#" << (*PrI)->getNumber()
846             << " is a predecessor according to the CFG.\n";
847       }
848     }
849   }
850 }
851
852 void MachineVerifier::visitMachineFunctionAfter() {
853   calcRegsPassed();
854
855   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
856        MFI != MFE; ++MFI) {
857     BBInfo &MInfo = MBBInfoMap[MFI];
858
859     // Skip unreachable MBBs.
860     if (!MInfo.reachable)
861       continue;
862
863     checkPHIOps(MFI);
864   }
865
866   // Now check liveness info if available
867   if (LiveVars || LiveInts)
868     calcRegsRequired();
869   if (LiveVars)
870     verifyLiveVariables();
871   if (LiveInts)
872     verifyLiveIntervals();
873 }
874
875 void MachineVerifier::verifyLiveVariables() {
876   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
877   for (unsigned Reg = TargetRegisterInfo::FirstVirtualRegister,
878          RegE = MRI->getLastVirtReg()-1; Reg != RegE; ++Reg) {
879     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
880     for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
881          MFI != MFE; ++MFI) {
882       BBInfo &MInfo = MBBInfoMap[MFI];
883
884       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
885       if (MInfo.vregsRequired.count(Reg)) {
886         if (!VI.AliveBlocks.test(MFI->getNumber())) {
887           report("LiveVariables: Block missing from AliveBlocks", MFI);
888           *OS << "Virtual register %reg" << Reg
889               << " must be live through the block.\n";
890         }
891       } else {
892         if (VI.AliveBlocks.test(MFI->getNumber())) {
893           report("LiveVariables: Block should not be in AliveBlocks", MFI);
894           *OS << "Virtual register %reg" << Reg
895               << " is not needed live through the block.\n";
896         }
897       }
898     }
899   }
900 }
901
902 void MachineVerifier::verifyLiveIntervals() {
903   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
904   for (LiveIntervals::const_iterator LVI = LiveInts->begin(),
905        LVE = LiveInts->end(); LVI != LVE; ++LVI) {
906     const LiveInterval &LI = *LVI->second;
907
908     // Spilling and splitting may leave unused registers around. Skip them.
909     if (MRI->use_empty(LI.reg))
910       continue;
911
912     // Physical registers have much weirdness going on, mostly from coalescing.
913     // We should probably fix it, but for now just ignore them.
914     if (TargetRegisterInfo::isPhysicalRegister(LI.reg))
915       continue;
916
917     assert(LVI->first == LI.reg && "Invalid reg to interval mapping");
918
919     for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
920          I!=E; ++I) {
921       VNInfo *VNI = *I;
922       const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
923
924       if (!DefVNI) {
925         if (!VNI->isUnused()) {
926           report("Valno not live at def and not marked unused", MF);
927           *OS << "Valno #" << VNI->id << " in " << LI << '\n';
928         }
929         continue;
930       }
931
932       if (VNI->isUnused())
933         continue;
934
935       if (DefVNI != VNI) {
936         report("Live range at def has different valno", MF);
937         *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
938             << " where valno #" << DefVNI->id << " is live in " << LI << '\n';
939         continue;
940       }
941
942       const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
943       if (!MBB) {
944         report("Invalid definition index", MF);
945         *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
946             << " in " << LI << '\n';
947         continue;
948       }
949
950       if (VNI->isPHIDef()) {
951         if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
952           report("PHIDef value is not defined at MBB start", MF);
953           *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
954               << ", not at the beginning of BB#" << MBB->getNumber()
955               << " in " << LI << '\n';
956         }
957       } else {
958         // Non-PHI def.
959         if (!VNI->def.isDef()) {
960           report("Non-PHI def must be at a DEF slot", MF);
961           *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
962               << " in " << LI << '\n';
963         }
964         const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
965         if (!MI) {
966           report("No instruction at def index", MF);
967           *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
968               << " in " << LI << '\n';
969         } else if (!MI->modifiesRegister(LI.reg, TRI)) {
970           report("Defining instruction does not modify register", MI);
971           *OS << "Valno #" << VNI->id << " in " << LI << '\n';
972         }
973       }
974     }
975
976     for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I) {
977       const VNInfo *VNI = I->valno;
978       assert(VNI && "Live range has no valno");
979
980       if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
981         report("Foreign valno in live range", MF);
982         I->print(*OS);
983         *OS << " has a valno not in " << LI << '\n';
984       }
985
986       if (VNI->isUnused()) {
987         report("Live range valno is marked unused", MF);
988         I->print(*OS);
989         *OS << " in " << LI << '\n';
990       }
991
992       const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
993       if (!MBB) {
994         report("Bad start of live segment, no basic block", MF);
995         I->print(*OS);
996         *OS << " in " << LI << '\n';
997         continue;
998       }
999       SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1000       if (I->start != MBBStartIdx && I->start != VNI->def) {
1001         report("Live segment must begin at MBB entry or valno def", MBB);
1002         I->print(*OS);
1003         *OS << " in " << LI << '\n' << "Basic block starts at "
1004             << MBBStartIdx << '\n';
1005       }
1006
1007       const MachineBasicBlock *EndMBB =
1008                                 LiveInts->getMBBFromIndex(I->end.getPrevSlot());
1009       if (!EndMBB) {
1010         report("Bad end of live segment, no basic block", MF);
1011         I->print(*OS);
1012         *OS << " in " << LI << '\n';
1013         continue;
1014       }
1015       if (I->end != LiveInts->getMBBEndIdx(EndMBB)) {
1016         // The live segment is ending inside EndMBB
1017         const MachineInstr *MI =
1018                         LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
1019         if (!MI) {
1020           report("Live segment doesn't end at a valid instruction", EndMBB);
1021         I->print(*OS);
1022         *OS << " in " << LI << '\n' << "Basic block starts at "
1023             << MBBStartIdx << '\n';
1024         } else if (TargetRegisterInfo::isVirtualRegister(LI.reg) &&
1025                    !MI->readsVirtualRegister(LI.reg)) {
1026           // FIXME: Should we require a kill flag?
1027           report("Instruction killing live segment doesn't read register", MI);
1028           I->print(*OS);
1029           *OS << " in " << LI << '\n';
1030         }
1031       }
1032
1033       // Now check all the basic blocks in this live segment.
1034       MachineFunction::const_iterator MFI = MBB;
1035       // Is LI live-in to MBB and not a PHIDef?
1036       if (I->start == VNI->def) {
1037         // Not live-in to any blocks.
1038         if (MBB == EndMBB)
1039           continue;
1040         // Skip this block.
1041         ++MFI;
1042       }
1043       for (;;) {
1044         assert(LiveInts->isLiveInToMBB(LI, MFI));
1045         // We don't know how to track physregs into a landing pad.
1046         if (TargetRegisterInfo::isPhysicalRegister(LI.reg) &&
1047             MFI->isLandingPad()) {
1048           if (&*MFI == EndMBB)
1049             break;
1050           ++MFI;
1051           continue;
1052         }
1053         // Check that VNI is live-out of all predecessors.
1054         for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1055              PE = MFI->pred_end(); PI != PE; ++PI) {
1056           SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI).getPrevSlot();
1057           const VNInfo *PVNI = LI.getVNInfoAt(PEnd);
1058           if (!PVNI) {
1059             report("Register not marked live out of predecessor", *PI);
1060             *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1061                 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live at "
1062                 << PEnd << " in " << LI << '\n';
1063           } else if (PVNI != VNI) {
1064             report("Different value live out of predecessor", *PI);
1065             *OS << "Valno #" << PVNI->id << " live out of BB#"
1066                 << (*PI)->getNumber() << '@' << PEnd
1067                 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1068                 << '@' << LiveInts->getMBBStartIdx(MFI) << " in " << LI << '\n';
1069           }
1070         }
1071         if (&*MFI == EndMBB)
1072           break;
1073         ++MFI;
1074       }
1075     }
1076
1077     // Check the LI only has one connected component.
1078     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1079       ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1080       unsigned NumComp = ConEQ.Classify(&LI);
1081       if (NumComp > 1) {
1082         report("Multiple connected components in live interval", MF);
1083         *OS << NumComp << " components in " << LI << '\n';
1084         for (unsigned comp = 0; comp != NumComp; ++comp) {
1085           *OS << comp << ": valnos";
1086           for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1087                E = LI.vni_end(); I!=E; ++I)
1088             if (comp == ConEQ.getEqClass(*I))
1089               *OS << ' ' << (*I)->id;
1090           *OS << '\n';
1091         }
1092       }
1093     }
1094   }
1095 }
1096