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