15bc095f212c02adb45757c2c04b98aebafe54ba
[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     const LiveIntervals *LiveInts;
171
172     void visitMachineFunctionBefore();
173     void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
174     void visitMachineInstrBefore(const MachineInstr *MI);
175     void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
176     void visitMachineInstrAfter(const MachineInstr *MI);
177     void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
178     void visitMachineFunctionAfter();
179
180     void report(const char *msg, const MachineFunction *MF);
181     void report(const char *msg, const MachineBasicBlock *MBB);
182     void report(const char *msg, const MachineInstr *MI);
183     void report(const char *msg, const MachineOperand *MO, unsigned MONum);
184
185     void markReachable(const MachineBasicBlock *MBB);
186     void calcRegsPassed();
187     void checkPHIOps(const MachineBasicBlock *MBB);
188
189     void calcRegsRequired();
190     void verifyLiveVariables();
191     void verifyLiveIntervals();
192   };
193
194   struct MachineVerifierPass : public MachineFunctionPass {
195     static char ID; // Pass ID, replacement for typeid
196
197     MachineVerifierPass()
198       : MachineFunctionPass(ID) {
199         initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
200       }
201
202     void getAnalysisUsage(AnalysisUsage &AU) const {
203       AU.setPreservesAll();
204       MachineFunctionPass::getAnalysisUsage(AU);
205     }
206
207     bool runOnMachineFunction(MachineFunction &MF) {
208       MF.verify(this);
209       return false;
210     }
211   };
212
213 }
214
215 char MachineVerifierPass::ID = 0;
216 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
217                 "Verify generated machine code", false, false)
218
219 FunctionPass *llvm::createMachineVerifierPass() {
220   return new MachineVerifierPass();
221 }
222
223 void MachineFunction::verify(Pass *p) const {
224   MachineVerifier(p).runOnMachineFunction(const_cast<MachineFunction&>(*this));
225 }
226
227 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
228   raw_ostream *OutFile = 0;
229   if (OutFileName) {
230     std::string ErrorInfo;
231     OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
232                                  raw_fd_ostream::F_Append);
233     if (!ErrorInfo.empty()) {
234       errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
235       exit(1);
236     }
237
238     OS = OutFile;
239   } else {
240     OS = &errs();
241   }
242
243   foundErrors = 0;
244
245   this->MF = &MF;
246   TM = &MF.getTarget();
247   TRI = TM->getRegisterInfo();
248   MRI = &MF.getRegInfo();
249
250   LiveVars = NULL;
251   LiveInts = NULL;
252   if (PASS) {
253     LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
254     // We don't want to verify LiveVariables if LiveIntervals is available.
255     if (!LiveInts)
256       LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
257   }
258
259   visitMachineFunctionBefore();
260   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
261        MFI!=MFE; ++MFI) {
262     visitMachineBasicBlockBefore(MFI);
263     for (MachineBasicBlock::const_iterator MBBI = MFI->begin(),
264            MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
265       visitMachineInstrBefore(MBBI);
266       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
267         visitMachineOperand(&MBBI->getOperand(I), I);
268       visitMachineInstrAfter(MBBI);
269     }
270     visitMachineBasicBlockAfter(MFI);
271   }
272   visitMachineFunctionAfter();
273
274   if (OutFile)
275     delete OutFile;
276   else if (foundErrors)
277     report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
278
279   // Clean up.
280   regsLive.clear();
281   regsDefined.clear();
282   regsDead.clear();
283   regsKilled.clear();
284   regsLiveInButUnused.clear();
285   MBBInfoMap.clear();
286
287   return false;                 // no changes
288 }
289
290 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
291   assert(MF);
292   *OS << '\n';
293   if (!foundErrors++)
294     MF->print(*OS);
295   *OS << "*** Bad machine code: " << msg << " ***\n"
296       << "- function:    " << MF->getFunction()->getNameStr() << "\n";
297 }
298
299 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
300   assert(MBB);
301   report(msg, MBB->getParent());
302   *OS << "- basic block: " << MBB->getName()
303       << " " << (void*)MBB
304       << " (BB#" << MBB->getNumber() << ")\n";
305 }
306
307 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
308   assert(MI);
309   report(msg, MI->getParent());
310   *OS << "- instruction: ";
311   MI->print(*OS, TM);
312 }
313
314 void MachineVerifier::report(const char *msg,
315                              const MachineOperand *MO, unsigned MONum) {
316   assert(MO);
317   report(msg, MO->getParent());
318   *OS << "- operand " << MONum << ":   ";
319   MO->print(*OS, TM);
320   *OS << "\n";
321 }
322
323 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
324   BBInfo &MInfo = MBBInfoMap[MBB];
325   if (!MInfo.reachable) {
326     MInfo.reachable = true;
327     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
328            SuE = MBB->succ_end(); SuI != SuE; ++SuI)
329       markReachable(*SuI);
330   }
331 }
332
333 void MachineVerifier::visitMachineFunctionBefore() {
334   regsReserved = TRI->getReservedRegs(*MF);
335
336   // A sub-register of a reserved register is also reserved
337   for (int Reg = regsReserved.find_first(); Reg>=0;
338        Reg = regsReserved.find_next(Reg)) {
339     for (const unsigned *Sub = TRI->getSubRegisters(Reg); *Sub; ++Sub) {
340       // FIXME: This should probably be:
341       // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
342       regsReserved.set(*Sub);
343     }
344   }
345   markReachable(&MF->front());
346 }
347
348 // Does iterator point to a and b as the first two elements?
349 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
350                       const MachineBasicBlock *a, const MachineBasicBlock *b) {
351   if (*i == a)
352     return *++i == b;
353   if (*i == b)
354     return *++i == a;
355   return false;
356 }
357
358 void
359 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
360   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
361
362   // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
363   MachineBasicBlock *TBB = 0, *FBB = 0;
364   SmallVector<MachineOperand, 4> Cond;
365   if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
366                           TBB, FBB, Cond)) {
367     // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
368     // check whether its answers match up with reality.
369     if (!TBB && !FBB) {
370       // Block falls through to its successor.
371       MachineFunction::const_iterator MBBI = MBB;
372       ++MBBI;
373       if (MBBI == MF->end()) {
374         // It's possible that the block legitimately ends with a noreturn
375         // call or an unreachable, in which case it won't actually fall
376         // out the bottom of the function.
377       } else if (MBB->succ_empty()) {
378         // It's possible that the block legitimately ends with a noreturn
379         // call or an unreachable, in which case it won't actuall fall
380         // out of the block.
381       } else if (MBB->succ_size() != 1) {
382         report("MBB exits via unconditional fall-through but doesn't have "
383                "exactly one CFG successor!", MBB);
384       } else if (MBB->succ_begin()[0] != MBBI) {
385         report("MBB exits via unconditional fall-through but its successor "
386                "differs from its CFG successor!", MBB);
387       }
388       if (!MBB->empty() && MBB->back().getDesc().isBarrier() &&
389           !TII->isPredicated(&MBB->back())) {
390         report("MBB exits via unconditional fall-through but ends with a "
391                "barrier instruction!", MBB);
392       }
393       if (!Cond.empty()) {
394         report("MBB exits via unconditional fall-through but has a condition!",
395                MBB);
396       }
397     } else if (TBB && !FBB && Cond.empty()) {
398       // Block unconditionally branches somewhere.
399       if (MBB->succ_size() != 1) {
400         report("MBB exits via unconditional branch but doesn't have "
401                "exactly one CFG successor!", MBB);
402       } else if (MBB->succ_begin()[0] != TBB) {
403         report("MBB exits via unconditional branch but the CFG "
404                "successor doesn't match the actual successor!", MBB);
405       }
406       if (MBB->empty()) {
407         report("MBB exits via unconditional branch but doesn't contain "
408                "any instructions!", MBB);
409       } else if (!MBB->back().getDesc().isBarrier()) {
410         report("MBB exits via unconditional branch but doesn't end with a "
411                "barrier instruction!", MBB);
412       } else if (!MBB->back().getDesc().isTerminator()) {
413         report("MBB exits via unconditional branch but the branch isn't a "
414                "terminator instruction!", MBB);
415       }
416     } else if (TBB && !FBB && !Cond.empty()) {
417       // Block conditionally branches somewhere, otherwise falls through.
418       MachineFunction::const_iterator MBBI = MBB;
419       ++MBBI;
420       if (MBBI == MF->end()) {
421         report("MBB conditionally falls through out of function!", MBB);
422       } if (MBB->succ_size() != 2) {
423         report("MBB exits via conditional branch/fall-through but doesn't have "
424                "exactly two CFG successors!", MBB);
425       } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
426         report("MBB exits via conditional branch/fall-through but the CFG "
427                "successors don't match the actual successors!", MBB);
428       }
429       if (MBB->empty()) {
430         report("MBB exits via conditional branch/fall-through but doesn't "
431                "contain any instructions!", MBB);
432       } else if (MBB->back().getDesc().isBarrier()) {
433         report("MBB exits via conditional branch/fall-through but ends with a "
434                "barrier instruction!", MBB);
435       } else if (!MBB->back().getDesc().isTerminator()) {
436         report("MBB exits via conditional branch/fall-through but the branch "
437                "isn't a terminator instruction!", MBB);
438       }
439     } else if (TBB && FBB) {
440       // Block conditionally branches somewhere, otherwise branches
441       // somewhere else.
442       if (MBB->succ_size() != 2) {
443         report("MBB exits via conditional branch/branch but doesn't have "
444                "exactly two CFG successors!", MBB);
445       } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
446         report("MBB exits via conditional branch/branch but the CFG "
447                "successors don't match the actual successors!", MBB);
448       }
449       if (MBB->empty()) {
450         report("MBB exits via conditional branch/branch but doesn't "
451                "contain any instructions!", MBB);
452       } else if (!MBB->back().getDesc().isBarrier()) {
453         report("MBB exits via conditional branch/branch but doesn't end with a "
454                "barrier instruction!", MBB);
455       } else if (!MBB->back().getDesc().isTerminator()) {
456         report("MBB exits via conditional branch/branch but the branch "
457                "isn't a terminator instruction!", MBB);
458       }
459       if (Cond.empty()) {
460         report("MBB exits via conditinal branch/branch but there's no "
461                "condition!", MBB);
462       }
463     } else {
464       report("AnalyzeBranch returned invalid data!", MBB);
465     }
466   }
467
468   regsLive.clear();
469   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
470          E = MBB->livein_end(); I != E; ++I) {
471     if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
472       report("MBB live-in list contains non-physical register", MBB);
473       continue;
474     }
475     regsLive.insert(*I);
476     for (const unsigned *R = TRI->getSubRegisters(*I); *R; R++)
477       regsLive.insert(*R);
478   }
479   regsLiveInButUnused = regsLive;
480
481   const MachineFrameInfo *MFI = MF->getFrameInfo();
482   assert(MFI && "Function has no frame info");
483   BitVector PR = MFI->getPristineRegs(MBB);
484   for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
485     regsLive.insert(I);
486     for (const unsigned *R = TRI->getSubRegisters(I); *R; R++)
487       regsLive.insert(*R);
488   }
489
490   regsKilled.clear();
491   regsDefined.clear();
492 }
493
494 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
495   const TargetInstrDesc &TI = MI->getDesc();
496   if (MI->getNumOperands() < TI.getNumOperands()) {
497     report("Too few operands", MI);
498     *OS << TI.getNumOperands() << " operands expected, but "
499         << MI->getNumExplicitOperands() << " given.\n";
500   }
501
502   // Check the MachineMemOperands for basic consistency.
503   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
504        E = MI->memoperands_end(); I != E; ++I) {
505     if ((*I)->isLoad() && !TI.mayLoad())
506       report("Missing mayLoad flag", MI);
507     if ((*I)->isStore() && !TI.mayStore())
508       report("Missing mayStore flag", MI);
509   }
510
511   // Debug values must not have a slot index.
512   // Other instructions must have one.
513   if (LiveInts) {
514     bool mapped = !LiveInts->isNotInMIMap(MI);
515     if (MI->isDebugValue()) {
516       if (mapped)
517         report("Debug instruction has a slot index", MI);
518     } else {
519       if (!mapped)
520         report("Missing slot index", MI);
521     }
522   }
523
524 }
525
526 void
527 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
528   const MachineInstr *MI = MO->getParent();
529   const TargetInstrDesc &TI = MI->getDesc();
530
531   // The first TI.NumDefs operands must be explicit register defines
532   if (MONum < TI.getNumDefs()) {
533     if (!MO->isReg())
534       report("Explicit definition must be a register", MO, MONum);
535     else if (!MO->isDef())
536       report("Explicit definition marked as use", MO, MONum);
537     else if (MO->isImplicit())
538       report("Explicit definition marked as implicit", MO, MONum);
539   } else if (MONum < TI.getNumOperands()) {
540     if (MO->isReg()) {
541       if (MO->isDef())
542         report("Explicit operand marked as def", MO, MONum);
543       if (MO->isImplicit())
544         report("Explicit operand marked as implicit", MO, MONum);
545     }
546   } else {
547     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
548     if (MO->isReg() && !MO->isImplicit() && !TI.isVariadic() && MO->getReg())
549       report("Extra explicit operand on non-variadic instruction", MO, MONum);
550   }
551
552   switch (MO->getType()) {
553   case MachineOperand::MO_Register: {
554     const unsigned Reg = MO->getReg();
555     if (!Reg)
556       return;
557
558     // Check Live Variables.
559     if (MO->isUndef()) {
560       // An <undef> doesn't refer to any register, so just skip it.
561     } else if (MO->isUse()) {
562       regsLiveInButUnused.erase(Reg);
563
564       bool isKill = false;
565       unsigned defIdx;
566       if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
567         // A two-addr use counts as a kill if use and def are the same.
568         unsigned DefReg = MI->getOperand(defIdx).getReg();
569         if (Reg == DefReg) {
570           isKill = true;
571           // ANd in that case an explicit kill flag is not allowed.
572           if (MO->isKill())
573             report("Illegal kill flag on two-address instruction operand",
574                    MO, MONum);
575         } else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
576           report("Two-address instruction operands must be identical",
577                  MO, MONum);
578         }
579       } else
580         isKill = MO->isKill();
581
582       if (isKill)
583         addRegWithSubRegs(regsKilled, Reg);
584
585       // Check that LiveVars knows this kill.
586       if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
587           MO->isKill()) {
588         LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
589         if (std::find(VI.Kills.begin(),
590                       VI.Kills.end(), MI) == VI.Kills.end())
591           report("Kill missing from LiveVariables", MO, MONum);
592       }
593
594       // Check LiveInts liveness and kill.
595       if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
596         SlotIndex UseIdx = LiveInts->getInstructionIndex(MI).getUseIndex();
597         if (LiveInts->hasInterval(Reg)) {
598           const LiveInterval &LI = LiveInts->getInterval(Reg);
599           if (!LI.liveAt(UseIdx)) {
600             report("No live range at use", MO, MONum);
601             *OS << UseIdx << " is not live in " << LI << '\n';
602           }
603           // TODO: Verify isKill == LI.killedAt.
604         } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
605           report("Virtual register has no Live interval", MO, MONum);
606         }
607       }
608
609       // Use of a dead register.
610       if (!regsLive.count(Reg)) {
611         if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
612           // Reserved registers may be used even when 'dead'.
613           if (!isReserved(Reg))
614             report("Using an undefined physical register", MO, MONum);
615         } else {
616           BBInfo &MInfo = MBBInfoMap[MI->getParent()];
617           // We don't know which virtual registers are live in, so only complain
618           // if vreg was killed in this MBB. Otherwise keep track of vregs that
619           // must be live in. PHI instructions are handled separately.
620           if (MInfo.regsKilled.count(Reg))
621             report("Using a killed virtual register", MO, MONum);
622           else if (!MI->isPHI())
623             MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
624         }
625       }
626     } else {
627       assert(MO->isDef());
628       // Register defined.
629       // TODO: verify that earlyclobber ops are not used.
630       if (MO->isDead())
631         addRegWithSubRegs(regsDead, Reg);
632       else
633         addRegWithSubRegs(regsDefined, Reg);
634
635       // Check LiveInts for a live range, but only for virtual registers.
636       if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
637           !LiveInts->isNotInMIMap(MI)) {
638         SlotIndex DefIdx = LiveInts->getInstructionIndex(MI).getDefIndex();
639         if (LiveInts->hasInterval(Reg)) {
640           const LiveInterval &LI = LiveInts->getInterval(Reg);
641           if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
642             assert(VNI && "NULL valno is not allowed");
643             if (VNI->def != DefIdx) {
644               report("Inconsistent valno->def", MO, MONum);
645               *OS << "Valno " << VNI->id << " is not defined at "
646                   << DefIdx << " in " << LI << '\n';
647             }
648           } else {
649             report("No live range at def", MO, MONum);
650             *OS << DefIdx << " is not live in " << LI << '\n';
651           }
652         } else {
653           report("Virtual register has no Live interval", MO, MONum);
654         }
655       }
656     }
657
658     // Check register classes.
659     if (MONum < TI.getNumOperands() && !MO->isImplicit()) {
660       const TargetOperandInfo &TOI = TI.OpInfo[MONum];
661       unsigned SubIdx = MO->getSubReg();
662
663       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
664         unsigned sr = Reg;
665         if (SubIdx) {
666           unsigned s = TRI->getSubReg(Reg, SubIdx);
667           if (!s) {
668             report("Invalid subregister index for physical register",
669                    MO, MONum);
670             return;
671           }
672           sr = s;
673         }
674         if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
675           if (!DRC->contains(sr)) {
676             report("Illegal physical register for instruction", MO, MONum);
677             *OS << TRI->getName(sr) << " is not a "
678                 << DRC->getName() << " register.\n";
679           }
680         }
681       } else {
682         // Virtual register.
683         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
684         if (SubIdx) {
685           const TargetRegisterClass *SRC = RC->getSubRegisterRegClass(SubIdx);
686           if (!SRC) {
687             report("Invalid subregister index for virtual register", MO, MONum);
688             *OS << "Register class " << RC->getName()
689                 << " does not support subreg index " << SubIdx << "\n";
690             return;
691           }
692           RC = SRC;
693         }
694         if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
695           if (RC != DRC && !RC->hasSuperClass(DRC)) {
696             report("Illegal virtual register for instruction", MO, MONum);
697             *OS << "Expected a " << DRC->getName() << " register, but got a "
698                 << RC->getName() << " register\n";
699           }
700         }
701       }
702     }
703     break;
704   }
705
706   case MachineOperand::MO_MachineBasicBlock:
707     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
708       report("PHI operand is not in the CFG", MO, MONum);
709     break;
710
711   default:
712     break;
713   }
714 }
715
716 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
717   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
718   set_union(MInfo.regsKilled, regsKilled);
719   set_subtract(regsLive, regsKilled); regsKilled.clear();
720   set_subtract(regsLive, regsDead);   regsDead.clear();
721   set_union(regsLive, regsDefined);   regsDefined.clear();
722 }
723
724 void
725 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
726   MBBInfoMap[MBB].regsLiveOut = regsLive;
727   regsLive.clear();
728 }
729
730 // Calculate the largest possible vregsPassed sets. These are the registers that
731 // can pass through an MBB live, but may not be live every time. It is assumed
732 // that all vregsPassed sets are empty before the call.
733 void MachineVerifier::calcRegsPassed() {
734   // First push live-out regs to successors' vregsPassed. Remember the MBBs that
735   // have any vregsPassed.
736   DenseSet<const MachineBasicBlock*> todo;
737   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
738        MFI != MFE; ++MFI) {
739     const MachineBasicBlock &MBB(*MFI);
740     BBInfo &MInfo = MBBInfoMap[&MBB];
741     if (!MInfo.reachable)
742       continue;
743     for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
744            SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
745       BBInfo &SInfo = MBBInfoMap[*SuI];
746       if (SInfo.addPassed(MInfo.regsLiveOut))
747         todo.insert(*SuI);
748     }
749   }
750
751   // Iteratively push vregsPassed to successors. This will converge to the same
752   // final state regardless of DenseSet iteration order.
753   while (!todo.empty()) {
754     const MachineBasicBlock *MBB = *todo.begin();
755     todo.erase(MBB);
756     BBInfo &MInfo = MBBInfoMap[MBB];
757     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
758            SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
759       if (*SuI == MBB)
760         continue;
761       BBInfo &SInfo = MBBInfoMap[*SuI];
762       if (SInfo.addPassed(MInfo.vregsPassed))
763         todo.insert(*SuI);
764     }
765   }
766 }
767
768 // Calculate the set of virtual registers that must be passed through each basic
769 // block in order to satisfy the requirements of successor blocks. This is very
770 // similar to calcRegsPassed, only backwards.
771 void MachineVerifier::calcRegsRequired() {
772   // First push live-in regs to predecessors' vregsRequired.
773   DenseSet<const MachineBasicBlock*> todo;
774   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
775        MFI != MFE; ++MFI) {
776     const MachineBasicBlock &MBB(*MFI);
777     BBInfo &MInfo = MBBInfoMap[&MBB];
778     for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
779            PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
780       BBInfo &PInfo = MBBInfoMap[*PrI];
781       if (PInfo.addRequired(MInfo.vregsLiveIn))
782         todo.insert(*PrI);
783     }
784   }
785
786   // Iteratively push vregsRequired to predecessors. This will converge to the
787   // same final state regardless of DenseSet iteration order.
788   while (!todo.empty()) {
789     const MachineBasicBlock *MBB = *todo.begin();
790     todo.erase(MBB);
791     BBInfo &MInfo = MBBInfoMap[MBB];
792     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
793            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
794       if (*PrI == MBB)
795         continue;
796       BBInfo &SInfo = MBBInfoMap[*PrI];
797       if (SInfo.addRequired(MInfo.vregsRequired))
798         todo.insert(*PrI);
799     }
800   }
801 }
802
803 // Check PHI instructions at the beginning of MBB. It is assumed that
804 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
805 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
806   for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
807        BBI != BBE && BBI->isPHI(); ++BBI) {
808     DenseSet<const MachineBasicBlock*> seen;
809
810     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
811       unsigned Reg = BBI->getOperand(i).getReg();
812       const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
813       if (!Pre->isSuccessor(MBB))
814         continue;
815       seen.insert(Pre);
816       BBInfo &PrInfo = MBBInfoMap[Pre];
817       if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
818         report("PHI operand is not live-out from predecessor",
819                &BBI->getOperand(i), i);
820     }
821
822     // Did we see all predecessors?
823     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
824            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
825       if (!seen.count(*PrI)) {
826         report("Missing PHI operand", BBI);
827         *OS << "BB#" << (*PrI)->getNumber()
828             << " is a predecessor according to the CFG.\n";
829       }
830     }
831   }
832 }
833
834 void MachineVerifier::visitMachineFunctionAfter() {
835   calcRegsPassed();
836
837   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
838        MFI != MFE; ++MFI) {
839     BBInfo &MInfo = MBBInfoMap[MFI];
840
841     // Skip unreachable MBBs.
842     if (!MInfo.reachable)
843       continue;
844
845     checkPHIOps(MFI);
846   }
847
848   // Now check liveness info if available
849   if (LiveVars || LiveInts)
850     calcRegsRequired();
851   if (LiveVars)
852     verifyLiveVariables();
853   if (LiveInts)
854     verifyLiveIntervals();
855 }
856
857 void MachineVerifier::verifyLiveVariables() {
858   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
859   for (unsigned Reg = TargetRegisterInfo::FirstVirtualRegister,
860          RegE = MRI->getLastVirtReg()-1; Reg != RegE; ++Reg) {
861     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
862     for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
863          MFI != MFE; ++MFI) {
864       BBInfo &MInfo = MBBInfoMap[MFI];
865
866       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
867       if (MInfo.vregsRequired.count(Reg)) {
868         if (!VI.AliveBlocks.test(MFI->getNumber())) {
869           report("LiveVariables: Block missing from AliveBlocks", MFI);
870           *OS << "Virtual register %reg" << Reg
871               << " must be live through the block.\n";
872         }
873       } else {
874         if (VI.AliveBlocks.test(MFI->getNumber())) {
875           report("LiveVariables: Block should not be in AliveBlocks", MFI);
876           *OS << "Virtual register %reg" << Reg
877               << " is not needed live through the block.\n";
878         }
879       }
880     }
881   }
882 }
883
884 void MachineVerifier::verifyLiveIntervals() {
885   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
886   for (LiveIntervals::const_iterator LVI = LiveInts->begin(),
887        LVE = LiveInts->end(); LVI != LVE; ++LVI) {
888     const LiveInterval &LI = *LVI->second;
889
890     // Spilling and splitting may leave unused registers around. Skip them.
891     if (MRI->use_empty(LI.reg))
892       continue;
893
894     assert(LVI->first == LI.reg && "Invalid reg to interval mapping");
895
896     for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
897          I!=E; ++I) {
898       VNInfo *VNI = *I;
899       const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
900
901       if (!DefVNI) {
902         if (!VNI->isUnused()) {
903           report("Valno not live at def and not marked unused", MF);
904           *OS << "Valno #" << VNI->id << " in " << LI << '\n';
905         }
906         continue;
907       }
908
909       if (VNI->isUnused())
910         continue;
911
912       if (DefVNI != VNI) {
913         report("Live range at def has different valno", MF);
914         *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
915             << " where valno #" << DefVNI->id << " is live.\n";
916       }
917
918     }
919
920     for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I) {
921       const VNInfo *VNI = I->valno;
922       assert(VNI && "Live range has no valno");
923
924       if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
925         report("Foreign valno in live range", MF);
926         I->print(*OS);
927         *OS << " has a valno not in " << LI << '\n';
928       }
929
930       if (VNI->isUnused()) {
931         report("Live range valno is marked unused", MF);
932         I->print(*OS);
933         *OS << " in " << LI << '\n';
934       }
935
936     }
937   }
938 }
939