Add a function for profiling to run at shutdown. Unlike the existing API, this
[llvm/stm8.git] / lib / CodeGen / MachineVerifier.cpp
blobf95f4112aeda618bb2b4f7287d80233434283bbd
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:
12 // Operand counts: All explicit operands must be present.
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
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 //===----------------------------------------------------------------------===//
26 #include "llvm/Function.h"
27 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
28 #include "llvm/CodeGen/LiveVariables.h"
29 #include "llvm/CodeGen/LiveStackAnalysis.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/DenseSet.h"
39 #include "llvm/ADT/SetOperations.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 using namespace llvm;
46 namespace {
47 struct MachineVerifier {
49 MachineVerifier(Pass *pass, const char *b) :
50 PASS(pass),
51 Banner(b),
52 OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
55 bool runOnMachineFunction(MachineFunction &MF);
57 Pass *const PASS;
58 const char *Banner;
59 const char *const OutFileName;
60 raw_ostream *OS;
61 const MachineFunction *MF;
62 const TargetMachine *TM;
63 const TargetRegisterInfo *TRI;
64 const MachineRegisterInfo *MRI;
66 unsigned foundErrors;
68 typedef SmallVector<unsigned, 16> RegVector;
69 typedef DenseSet<unsigned> RegSet;
70 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
72 BitVector regsReserved;
73 RegSet regsLive;
74 RegVector regsDefined, regsDead, regsKilled;
75 RegSet regsLiveInButUnused;
77 SlotIndex lastIndex;
79 // Add Reg and any sub-registers to RV
80 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
81 RV.push_back(Reg);
82 if (TargetRegisterInfo::isPhysicalRegister(Reg))
83 for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
84 RV.push_back(*R);
87 struct BBInfo {
88 // Is this MBB reachable from the MF entry point?
89 bool reachable;
91 // Vregs that must be live in because they are used without being
92 // defined. Map value is the user.
93 RegMap vregsLiveIn;
95 // Regs killed in MBB. They may be defined again, and will then be in both
96 // regsKilled and regsLiveOut.
97 RegSet regsKilled;
99 // Regs defined in MBB and live out. Note that vregs passing through may
100 // be live out without being mentioned here.
101 RegSet regsLiveOut;
103 // Vregs that pass through MBB untouched. This set is disjoint from
104 // regsKilled and regsLiveOut.
105 RegSet vregsPassed;
107 // Vregs that must pass through MBB because they are needed by a successor
108 // block. This set is disjoint from regsLiveOut.
109 RegSet vregsRequired;
111 BBInfo() : reachable(false) {}
113 // Add register to vregsPassed if it belongs there. Return true if
114 // anything changed.
115 bool addPassed(unsigned Reg) {
116 if (!TargetRegisterInfo::isVirtualRegister(Reg))
117 return false;
118 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
119 return false;
120 return vregsPassed.insert(Reg).second;
123 // Same for a full set.
124 bool addPassed(const RegSet &RS) {
125 bool changed = false;
126 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
127 if (addPassed(*I))
128 changed = true;
129 return changed;
132 // Add register to vregsRequired if it belongs there. Return true if
133 // anything changed.
134 bool addRequired(unsigned Reg) {
135 if (!TargetRegisterInfo::isVirtualRegister(Reg))
136 return false;
137 if (regsLiveOut.count(Reg))
138 return false;
139 return vregsRequired.insert(Reg).second;
142 // Same for a full set.
143 bool addRequired(const RegSet &RS) {
144 bool changed = false;
145 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
146 if (addRequired(*I))
147 changed = true;
148 return changed;
151 // Same for a full map.
152 bool addRequired(const RegMap &RM) {
153 bool changed = false;
154 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
155 if (addRequired(I->first))
156 changed = true;
157 return changed;
160 // Live-out registers are either in regsLiveOut or vregsPassed.
161 bool isLiveOut(unsigned Reg) const {
162 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
166 // Extra register info per MBB.
167 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
169 bool isReserved(unsigned Reg) {
170 return Reg < regsReserved.size() && regsReserved.test(Reg);
173 // Analysis information if available
174 LiveVariables *LiveVars;
175 LiveIntervals *LiveInts;
176 LiveStacks *LiveStks;
177 SlotIndexes *Indexes;
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();
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);
192 void markReachable(const MachineBasicBlock *MBB);
193 void calcRegsPassed();
194 void checkPHIOps(const MachineBasicBlock *MBB);
196 void calcRegsRequired();
197 void verifyLiveVariables();
198 void verifyLiveIntervals();
201 struct MachineVerifierPass : public MachineFunctionPass {
202 static char ID; // Pass ID, replacement for typeid
203 const char *const Banner;
205 MachineVerifierPass(const char *b = 0)
206 : MachineFunctionPass(ID), Banner(b) {
207 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
210 void getAnalysisUsage(AnalysisUsage &AU) const {
211 AU.setPreservesAll();
212 MachineFunctionPass::getAnalysisUsage(AU);
215 bool runOnMachineFunction(MachineFunction &MF) {
216 MF.verify(this, Banner);
217 return false;
223 char MachineVerifierPass::ID = 0;
224 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
225 "Verify generated machine code", false, false)
227 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
228 return new MachineVerifierPass(Banner);
231 void MachineFunction::verify(Pass *p, const char *Banner) const {
232 MachineVerifier(p, Banner)
233 .runOnMachineFunction(const_cast<MachineFunction&>(*this));
236 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
237 raw_ostream *OutFile = 0;
238 if (OutFileName) {
239 std::string ErrorInfo;
240 OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
241 raw_fd_ostream::F_Append);
242 if (!ErrorInfo.empty()) {
243 errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
244 exit(1);
247 OS = OutFile;
248 } else {
249 OS = &errs();
252 foundErrors = 0;
254 this->MF = &MF;
255 TM = &MF.getTarget();
256 TRI = TM->getRegisterInfo();
257 MRI = &MF.getRegInfo();
259 LiveVars = NULL;
260 LiveInts = NULL;
261 LiveStks = NULL;
262 Indexes = NULL;
263 if (PASS) {
264 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
265 // We don't want to verify LiveVariables if LiveIntervals is available.
266 if (!LiveInts)
267 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
268 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
269 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
272 visitMachineFunctionBefore();
273 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
274 MFI!=MFE; ++MFI) {
275 visitMachineBasicBlockBefore(MFI);
276 for (MachineBasicBlock::const_iterator MBBI = MFI->begin(),
277 MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
278 if (MBBI->getParent() != MFI) {
279 report("Bad instruction parent pointer", MFI);
280 *OS << "Instruction: " << *MBBI;
281 continue;
283 visitMachineInstrBefore(MBBI);
284 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
285 visitMachineOperand(&MBBI->getOperand(I), I);
286 visitMachineInstrAfter(MBBI);
288 visitMachineBasicBlockAfter(MFI);
290 visitMachineFunctionAfter();
292 if (OutFile)
293 delete OutFile;
294 else if (foundErrors)
295 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
297 // Clean up.
298 regsLive.clear();
299 regsDefined.clear();
300 regsDead.clear();
301 regsKilled.clear();
302 regsLiveInButUnused.clear();
303 MBBInfoMap.clear();
305 return false; // no changes
308 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
309 assert(MF);
310 *OS << '\n';
311 if (!foundErrors++) {
312 if (Banner)
313 *OS << "# " << Banner << '\n';
314 MF->print(*OS, Indexes);
316 *OS << "*** Bad machine code: " << msg << " ***\n"
317 << "- function: " << MF->getFunction()->getNameStr() << "\n";
320 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
321 assert(MBB);
322 report(msg, MBB->getParent());
323 *OS << "- basic block: " << MBB->getName()
324 << " " << (void*)MBB
325 << " (BB#" << MBB->getNumber() << ")";
326 if (Indexes)
327 *OS << " [" << Indexes->getMBBStartIdx(MBB)
328 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
329 *OS << '\n';
332 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
333 assert(MI);
334 report(msg, MI->getParent());
335 *OS << "- instruction: ";
336 if (Indexes && Indexes->hasIndex(MI))
337 *OS << Indexes->getInstructionIndex(MI) << '\t';
338 MI->print(*OS, TM);
341 void MachineVerifier::report(const char *msg,
342 const MachineOperand *MO, unsigned MONum) {
343 assert(MO);
344 report(msg, MO->getParent());
345 *OS << "- operand " << MONum << ": ";
346 MO->print(*OS, TM);
347 *OS << "\n";
350 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
351 BBInfo &MInfo = MBBInfoMap[MBB];
352 if (!MInfo.reachable) {
353 MInfo.reachable = true;
354 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
355 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
356 markReachable(*SuI);
360 void MachineVerifier::visitMachineFunctionBefore() {
361 lastIndex = SlotIndex();
362 regsReserved = TRI->getReservedRegs(*MF);
364 // A sub-register of a reserved register is also reserved
365 for (int Reg = regsReserved.find_first(); Reg>=0;
366 Reg = regsReserved.find_next(Reg)) {
367 for (const unsigned *Sub = TRI->getSubRegisters(Reg); *Sub; ++Sub) {
368 // FIXME: This should probably be:
369 // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
370 regsReserved.set(*Sub);
373 markReachable(&MF->front());
376 // Does iterator point to a and b as the first two elements?
377 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
378 const MachineBasicBlock *a, const MachineBasicBlock *b) {
379 if (*i == a)
380 return *++i == b;
381 if (*i == b)
382 return *++i == a;
383 return false;
386 void
387 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
388 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
390 // Count the number of landing pad successors.
391 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
392 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
393 E = MBB->succ_end(); I != E; ++I) {
394 if ((*I)->isLandingPad())
395 LandingPadSuccs.insert(*I);
397 if (LandingPadSuccs.size() > 1)
398 report("MBB has more than one landing pad successor", MBB);
400 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
401 MachineBasicBlock *TBB = 0, *FBB = 0;
402 SmallVector<MachineOperand, 4> Cond;
403 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
404 TBB, FBB, Cond)) {
405 // If the block branches directly to a landing pad successor, pretend that
406 // the landing pad is a normal block.
407 LandingPadSuccs.erase(TBB);
408 LandingPadSuccs.erase(FBB);
410 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
411 // check whether its answers match up with reality.
412 if (!TBB && !FBB) {
413 // Block falls through to its successor.
414 MachineFunction::const_iterator MBBI = MBB;
415 ++MBBI;
416 if (MBBI == MF->end()) {
417 // It's possible that the block legitimately ends with a noreturn
418 // call or an unreachable, in which case it won't actually fall
419 // out the bottom of the function.
420 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
421 // It's possible that the block legitimately ends with a noreturn
422 // call or an unreachable, in which case it won't actuall fall
423 // out of the block.
424 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
425 report("MBB exits via unconditional fall-through but doesn't have "
426 "exactly one CFG successor!", MBB);
427 } else if (!MBB->isSuccessor(MBBI)) {
428 report("MBB exits via unconditional fall-through but its successor "
429 "differs from its CFG successor!", MBB);
431 if (!MBB->empty() && MBB->back().getDesc().isBarrier() &&
432 !TII->isPredicated(&MBB->back())) {
433 report("MBB exits via unconditional fall-through but ends with a "
434 "barrier instruction!", MBB);
436 if (!Cond.empty()) {
437 report("MBB exits via unconditional fall-through but has a condition!",
438 MBB);
440 } else if (TBB && !FBB && Cond.empty()) {
441 // Block unconditionally branches somewhere.
442 if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
443 report("MBB exits via unconditional branch but doesn't have "
444 "exactly one CFG successor!", MBB);
445 } else if (!MBB->isSuccessor(TBB)) {
446 report("MBB exits via unconditional branch but the CFG "
447 "successor doesn't match the actual successor!", MBB);
449 if (MBB->empty()) {
450 report("MBB exits via unconditional branch but doesn't contain "
451 "any instructions!", MBB);
452 } else if (!MBB->back().getDesc().isBarrier()) {
453 report("MBB exits via unconditional branch but doesn't end with a "
454 "barrier instruction!", MBB);
455 } else if (!MBB->back().getDesc().isTerminator()) {
456 report("MBB exits via unconditional branch but the branch isn't a "
457 "terminator instruction!", MBB);
459 } else if (TBB && !FBB && !Cond.empty()) {
460 // Block conditionally branches somewhere, otherwise falls through.
461 MachineFunction::const_iterator MBBI = MBB;
462 ++MBBI;
463 if (MBBI == MF->end()) {
464 report("MBB conditionally falls through out of function!", MBB);
465 } if (MBB->succ_size() != 2) {
466 report("MBB exits via conditional branch/fall-through but doesn't have "
467 "exactly two CFG successors!", MBB);
468 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
469 report("MBB exits via conditional branch/fall-through but the CFG "
470 "successors don't match the actual successors!", MBB);
472 if (MBB->empty()) {
473 report("MBB exits via conditional branch/fall-through but doesn't "
474 "contain any instructions!", MBB);
475 } else if (MBB->back().getDesc().isBarrier()) {
476 report("MBB exits via conditional branch/fall-through but ends with a "
477 "barrier instruction!", MBB);
478 } else if (!MBB->back().getDesc().isTerminator()) {
479 report("MBB exits via conditional branch/fall-through but the branch "
480 "isn't a terminator instruction!", MBB);
482 } else if (TBB && FBB) {
483 // Block conditionally branches somewhere, otherwise branches
484 // somewhere else.
485 if (MBB->succ_size() != 2) {
486 report("MBB exits via conditional branch/branch but doesn't have "
487 "exactly two CFG successors!", MBB);
488 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
489 report("MBB exits via conditional branch/branch but the CFG "
490 "successors don't match the actual successors!", MBB);
492 if (MBB->empty()) {
493 report("MBB exits via conditional branch/branch but doesn't "
494 "contain any instructions!", MBB);
495 } else if (!MBB->back().getDesc().isBarrier()) {
496 report("MBB exits via conditional branch/branch but doesn't end with a "
497 "barrier instruction!", MBB);
498 } else if (!MBB->back().getDesc().isTerminator()) {
499 report("MBB exits via conditional branch/branch but the branch "
500 "isn't a terminator instruction!", MBB);
502 if (Cond.empty()) {
503 report("MBB exits via conditinal branch/branch but there's no "
504 "condition!", MBB);
506 } else {
507 report("AnalyzeBranch returned invalid data!", MBB);
511 regsLive.clear();
512 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
513 E = MBB->livein_end(); I != E; ++I) {
514 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
515 report("MBB live-in list contains non-physical register", MBB);
516 continue;
518 regsLive.insert(*I);
519 for (const unsigned *R = TRI->getSubRegisters(*I); *R; R++)
520 regsLive.insert(*R);
522 regsLiveInButUnused = regsLive;
524 const MachineFrameInfo *MFI = MF->getFrameInfo();
525 assert(MFI && "Function has no frame info");
526 BitVector PR = MFI->getPristineRegs(MBB);
527 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
528 regsLive.insert(I);
529 for (const unsigned *R = TRI->getSubRegisters(I); *R; R++)
530 regsLive.insert(*R);
533 regsKilled.clear();
534 regsDefined.clear();
536 if (Indexes)
537 lastIndex = Indexes->getMBBStartIdx(MBB);
540 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
541 const TargetInstrDesc &TI = MI->getDesc();
542 if (MI->getNumOperands() < TI.getNumOperands()) {
543 report("Too few operands", MI);
544 *OS << TI.getNumOperands() << " operands expected, but "
545 << MI->getNumExplicitOperands() << " given.\n";
548 // Check the MachineMemOperands for basic consistency.
549 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
550 E = MI->memoperands_end(); I != E; ++I) {
551 if ((*I)->isLoad() && !TI.mayLoad())
552 report("Missing mayLoad flag", MI);
553 if ((*I)->isStore() && !TI.mayStore())
554 report("Missing mayStore flag", MI);
557 // Debug values must not have a slot index.
558 // Other instructions must have one.
559 if (LiveInts) {
560 bool mapped = !LiveInts->isNotInMIMap(MI);
561 if (MI->isDebugValue()) {
562 if (mapped)
563 report("Debug instruction has a slot index", MI);
564 } else {
565 if (!mapped)
566 report("Missing slot index", MI);
572 void
573 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
574 const MachineInstr *MI = MO->getParent();
575 const TargetInstrDesc &TI = MI->getDesc();
576 const TargetOperandInfo &TOI = TI.OpInfo[MONum];
578 // The first TI.NumDefs operands must be explicit register defines
579 if (MONum < TI.getNumDefs()) {
580 if (!MO->isReg())
581 report("Explicit definition must be a register", MO, MONum);
582 else if (!MO->isDef())
583 report("Explicit definition marked as use", MO, MONum);
584 else if (MO->isImplicit())
585 report("Explicit definition marked as implicit", MO, MONum);
586 } else if (MONum < TI.getNumOperands()) {
587 // Don't check if it's the last operand in a variadic instruction. See,
588 // e.g., LDM_RET in the arm back end.
589 if (MO->isReg() && !(TI.isVariadic() && MONum == TI.getNumOperands()-1)) {
590 if (MO->isDef() && !TOI.isOptionalDef())
591 report("Explicit operand marked as def", MO, MONum);
592 if (MO->isImplicit())
593 report("Explicit operand marked as implicit", MO, MONum);
595 } else {
596 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
597 if (MO->isReg() && !MO->isImplicit() && !TI.isVariadic() && MO->getReg())
598 report("Extra explicit operand on non-variadic instruction", MO, MONum);
601 switch (MO->getType()) {
602 case MachineOperand::MO_Register: {
603 const unsigned Reg = MO->getReg();
604 if (!Reg)
605 return;
607 // Check Live Variables.
608 if (MI->isDebugValue()) {
609 // Liveness checks are not valid for debug values.
610 } else if (MO->isUse() && !MO->isUndef()) {
611 regsLiveInButUnused.erase(Reg);
613 bool isKill = false;
614 unsigned defIdx;
615 if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
616 // A two-addr use counts as a kill if use and def are the same.
617 unsigned DefReg = MI->getOperand(defIdx).getReg();
618 if (Reg == DefReg)
619 isKill = true;
620 else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
621 report("Two-address instruction operands must be identical",
622 MO, MONum);
624 } else
625 isKill = MO->isKill();
627 if (isKill)
628 addRegWithSubRegs(regsKilled, Reg);
630 // Check that LiveVars knows this kill.
631 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
632 MO->isKill()) {
633 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
634 if (std::find(VI.Kills.begin(),
635 VI.Kills.end(), MI) == VI.Kills.end())
636 report("Kill missing from LiveVariables", MO, MONum);
639 // Check LiveInts liveness and kill.
640 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
641 LiveInts && !LiveInts->isNotInMIMap(MI)) {
642 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI).getUseIndex();
643 if (LiveInts->hasInterval(Reg)) {
644 const LiveInterval &LI = LiveInts->getInterval(Reg);
645 if (!LI.liveAt(UseIdx)) {
646 report("No live range at use", MO, MONum);
647 *OS << UseIdx << " is not live in " << LI << '\n';
649 // Check for extra kill flags.
650 // Note that we allow missing kill flags for now.
651 if (MO->isKill() && !LI.killedAt(UseIdx.getDefIndex())) {
652 report("Live range continues after kill flag", MO, MONum);
653 *OS << "Live range: " << LI << '\n';
655 } else {
656 report("Virtual register has no Live interval", MO, MONum);
660 // Use of a dead register.
661 if (!regsLive.count(Reg)) {
662 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
663 // Reserved registers may be used even when 'dead'.
664 if (!isReserved(Reg))
665 report("Using an undefined physical register", MO, MONum);
666 } else {
667 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
668 // We don't know which virtual registers are live in, so only complain
669 // if vreg was killed in this MBB. Otherwise keep track of vregs that
670 // must be live in. PHI instructions are handled separately.
671 if (MInfo.regsKilled.count(Reg))
672 report("Using a killed virtual register", MO, MONum);
673 else if (!MI->isPHI())
674 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
677 } else if (MO->isDef()) {
678 // Register defined.
679 // TODO: verify that earlyclobber ops are not used.
680 if (MO->isDead())
681 addRegWithSubRegs(regsDead, Reg);
682 else
683 addRegWithSubRegs(regsDefined, Reg);
685 // Check LiveInts for a live range, but only for virtual registers.
686 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
687 !LiveInts->isNotInMIMap(MI)) {
688 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI).getDefIndex();
689 if (LiveInts->hasInterval(Reg)) {
690 const LiveInterval &LI = LiveInts->getInterval(Reg);
691 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
692 assert(VNI && "NULL valno is not allowed");
693 if (VNI->def != DefIdx && !MO->isEarlyClobber()) {
694 report("Inconsistent valno->def", MO, MONum);
695 *OS << "Valno " << VNI->id << " is not defined at "
696 << DefIdx << " in " << LI << '\n';
698 } else {
699 report("No live range at def", MO, MONum);
700 *OS << DefIdx << " is not live in " << LI << '\n';
702 } else {
703 report("Virtual register has no Live interval", MO, MONum);
708 // Check register classes.
709 if (MONum < TI.getNumOperands() && !MO->isImplicit()) {
710 unsigned SubIdx = MO->getSubReg();
712 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
713 unsigned sr = Reg;
714 if (SubIdx) {
715 unsigned s = TRI->getSubReg(Reg, SubIdx);
716 if (!s) {
717 report("Invalid subregister index for physical register",
718 MO, MONum);
719 return;
721 sr = s;
723 if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
724 if (!DRC->contains(sr)) {
725 report("Illegal physical register for instruction", MO, MONum);
726 *OS << TRI->getName(sr) << " is not a "
727 << DRC->getName() << " register.\n";
730 } else {
731 // Virtual register.
732 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
733 if (SubIdx) {
734 const TargetRegisterClass *SRC = RC->getSubRegisterRegClass(SubIdx);
735 if (!SRC) {
736 report("Invalid subregister index for virtual register", MO, MONum);
737 *OS << "Register class " << RC->getName()
738 << " does not support subreg index " << SubIdx << "\n";
739 return;
741 RC = SRC;
743 if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
744 if (RC != DRC && !RC->hasSuperClass(DRC)) {
745 report("Illegal virtual register for instruction", MO, MONum);
746 *OS << "Expected a " << DRC->getName() << " register, but got a "
747 << RC->getName() << " register\n";
752 break;
755 case MachineOperand::MO_MachineBasicBlock:
756 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
757 report("PHI operand is not in the CFG", MO, MONum);
758 break;
760 case MachineOperand::MO_FrameIndex:
761 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
762 LiveInts && !LiveInts->isNotInMIMap(MI)) {
763 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
764 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
765 if (TI.mayLoad() && !LI.liveAt(Idx.getUseIndex())) {
766 report("Instruction loads from dead spill slot", MO, MONum);
767 *OS << "Live stack: " << LI << '\n';
769 if (TI.mayStore() && !LI.liveAt(Idx.getDefIndex())) {
770 report("Instruction stores to dead spill slot", MO, MONum);
771 *OS << "Live stack: " << LI << '\n';
774 break;
776 default:
777 break;
781 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
782 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
783 set_union(MInfo.regsKilled, regsKilled);
784 set_subtract(regsLive, regsKilled); regsKilled.clear();
785 set_subtract(regsLive, regsDead); regsDead.clear();
786 set_union(regsLive, regsDefined); regsDefined.clear();
788 if (Indexes && Indexes->hasIndex(MI)) {
789 SlotIndex idx = Indexes->getInstructionIndex(MI);
790 if (!(idx > lastIndex)) {
791 report("Instruction index out of order", MI);
792 *OS << "Last instruction was at " << lastIndex << '\n';
794 lastIndex = idx;
798 void
799 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
800 MBBInfoMap[MBB].regsLiveOut = regsLive;
801 regsLive.clear();
803 if (Indexes) {
804 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
805 if (!(stop > lastIndex)) {
806 report("Block ends before last instruction index", MBB);
807 *OS << "Block ends at " << stop
808 << " last instruction was at " << lastIndex << '\n';
810 lastIndex = stop;
814 // Calculate the largest possible vregsPassed sets. These are the registers that
815 // can pass through an MBB live, but may not be live every time. It is assumed
816 // that all vregsPassed sets are empty before the call.
817 void MachineVerifier::calcRegsPassed() {
818 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
819 // have any vregsPassed.
820 DenseSet<const MachineBasicBlock*> todo;
821 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
822 MFI != MFE; ++MFI) {
823 const MachineBasicBlock &MBB(*MFI);
824 BBInfo &MInfo = MBBInfoMap[&MBB];
825 if (!MInfo.reachable)
826 continue;
827 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
828 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
829 BBInfo &SInfo = MBBInfoMap[*SuI];
830 if (SInfo.addPassed(MInfo.regsLiveOut))
831 todo.insert(*SuI);
835 // Iteratively push vregsPassed to successors. This will converge to the same
836 // final state regardless of DenseSet iteration order.
837 while (!todo.empty()) {
838 const MachineBasicBlock *MBB = *todo.begin();
839 todo.erase(MBB);
840 BBInfo &MInfo = MBBInfoMap[MBB];
841 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
842 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
843 if (*SuI == MBB)
844 continue;
845 BBInfo &SInfo = MBBInfoMap[*SuI];
846 if (SInfo.addPassed(MInfo.vregsPassed))
847 todo.insert(*SuI);
852 // Calculate the set of virtual registers that must be passed through each basic
853 // block in order to satisfy the requirements of successor blocks. This is very
854 // similar to calcRegsPassed, only backwards.
855 void MachineVerifier::calcRegsRequired() {
856 // First push live-in regs to predecessors' vregsRequired.
857 DenseSet<const MachineBasicBlock*> todo;
858 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
859 MFI != MFE; ++MFI) {
860 const MachineBasicBlock &MBB(*MFI);
861 BBInfo &MInfo = MBBInfoMap[&MBB];
862 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
863 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
864 BBInfo &PInfo = MBBInfoMap[*PrI];
865 if (PInfo.addRequired(MInfo.vregsLiveIn))
866 todo.insert(*PrI);
870 // Iteratively push vregsRequired to predecessors. This will converge to the
871 // same final state regardless of DenseSet iteration order.
872 while (!todo.empty()) {
873 const MachineBasicBlock *MBB = *todo.begin();
874 todo.erase(MBB);
875 BBInfo &MInfo = MBBInfoMap[MBB];
876 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
877 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
878 if (*PrI == MBB)
879 continue;
880 BBInfo &SInfo = MBBInfoMap[*PrI];
881 if (SInfo.addRequired(MInfo.vregsRequired))
882 todo.insert(*PrI);
887 // Check PHI instructions at the beginning of MBB. It is assumed that
888 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
889 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
890 for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
891 BBI != BBE && BBI->isPHI(); ++BBI) {
892 DenseSet<const MachineBasicBlock*> seen;
894 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
895 unsigned Reg = BBI->getOperand(i).getReg();
896 const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
897 if (!Pre->isSuccessor(MBB))
898 continue;
899 seen.insert(Pre);
900 BBInfo &PrInfo = MBBInfoMap[Pre];
901 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
902 report("PHI operand is not live-out from predecessor",
903 &BBI->getOperand(i), i);
906 // Did we see all predecessors?
907 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
908 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
909 if (!seen.count(*PrI)) {
910 report("Missing PHI operand", BBI);
911 *OS << "BB#" << (*PrI)->getNumber()
912 << " is a predecessor according to the CFG.\n";
918 void MachineVerifier::visitMachineFunctionAfter() {
919 calcRegsPassed();
921 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
922 MFI != MFE; ++MFI) {
923 BBInfo &MInfo = MBBInfoMap[MFI];
925 // Skip unreachable MBBs.
926 if (!MInfo.reachable)
927 continue;
929 checkPHIOps(MFI);
932 // Now check liveness info if available
933 if (LiveVars || LiveInts)
934 calcRegsRequired();
935 if (LiveVars)
936 verifyLiveVariables();
937 if (LiveInts)
938 verifyLiveIntervals();
941 void MachineVerifier::verifyLiveVariables() {
942 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
943 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
944 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
945 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
946 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
947 MFI != MFE; ++MFI) {
948 BBInfo &MInfo = MBBInfoMap[MFI];
950 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
951 if (MInfo.vregsRequired.count(Reg)) {
952 if (!VI.AliveBlocks.test(MFI->getNumber())) {
953 report("LiveVariables: Block missing from AliveBlocks", MFI);
954 *OS << "Virtual register " << PrintReg(Reg)
955 << " must be live through the block.\n";
957 } else {
958 if (VI.AliveBlocks.test(MFI->getNumber())) {
959 report("LiveVariables: Block should not be in AliveBlocks", MFI);
960 *OS << "Virtual register " << PrintReg(Reg)
961 << " is not needed live through the block.\n";
968 void MachineVerifier::verifyLiveIntervals() {
969 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
970 for (LiveIntervals::const_iterator LVI = LiveInts->begin(),
971 LVE = LiveInts->end(); LVI != LVE; ++LVI) {
972 const LiveInterval &LI = *LVI->second;
974 // Spilling and splitting may leave unused registers around. Skip them.
975 if (MRI->use_empty(LI.reg))
976 continue;
978 // Physical registers have much weirdness going on, mostly from coalescing.
979 // We should probably fix it, but for now just ignore them.
980 if (TargetRegisterInfo::isPhysicalRegister(LI.reg))
981 continue;
983 assert(LVI->first == LI.reg && "Invalid reg to interval mapping");
985 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
986 I!=E; ++I) {
987 VNInfo *VNI = *I;
988 const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
990 if (!DefVNI) {
991 if (!VNI->isUnused()) {
992 report("Valno not live at def and not marked unused", MF);
993 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
995 continue;
998 if (VNI->isUnused())
999 continue;
1001 if (DefVNI != VNI) {
1002 report("Live range at def has different valno", MF);
1003 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1004 << " where valno #" << DefVNI->id << " is live in " << LI << '\n';
1005 continue;
1008 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1009 if (!MBB) {
1010 report("Invalid definition index", MF);
1011 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1012 << " in " << LI << '\n';
1013 continue;
1016 if (VNI->isPHIDef()) {
1017 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1018 report("PHIDef value is not defined at MBB start", MF);
1019 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1020 << ", not at the beginning of BB#" << MBB->getNumber()
1021 << " in " << LI << '\n';
1023 } else {
1024 // Non-PHI def.
1025 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1026 if (!MI) {
1027 report("No instruction at def index", MF);
1028 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1029 << " in " << LI << '\n';
1030 } else if (!MI->modifiesRegister(LI.reg, TRI)) {
1031 report("Defining instruction does not modify register", MI);
1032 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1035 bool isEarlyClobber = false;
1036 if (MI) {
1037 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1038 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1039 if (MOI->isReg() && MOI->getReg() == LI.reg && MOI->isDef() &&
1040 MOI->isEarlyClobber()) {
1041 isEarlyClobber = true;
1042 break;
1047 // Early clobber defs begin at USE slots, but other defs must begin at
1048 // DEF slots.
1049 if (isEarlyClobber) {
1050 if (!VNI->def.isUse()) {
1051 report("Early clobber def must be at a USE slot", MF);
1052 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1053 << " in " << LI << '\n';
1055 } else if (!VNI->def.isDef()) {
1056 report("Non-PHI, non-early clobber def must be at a DEF slot", MF);
1057 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1058 << " in " << LI << '\n';
1063 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I) {
1064 const VNInfo *VNI = I->valno;
1065 assert(VNI && "Live range has no valno");
1067 if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
1068 report("Foreign valno in live range", MF);
1069 I->print(*OS);
1070 *OS << " has a valno not in " << LI << '\n';
1073 if (VNI->isUnused()) {
1074 report("Live range valno is marked unused", MF);
1075 I->print(*OS);
1076 *OS << " in " << LI << '\n';
1079 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
1080 if (!MBB) {
1081 report("Bad start of live segment, no basic block", MF);
1082 I->print(*OS);
1083 *OS << " in " << LI << '\n';
1084 continue;
1086 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1087 if (I->start != MBBStartIdx && I->start != VNI->def) {
1088 report("Live segment must begin at MBB entry or valno def", MBB);
1089 I->print(*OS);
1090 *OS << " in " << LI << '\n' << "Basic block starts at "
1091 << MBBStartIdx << '\n';
1094 const MachineBasicBlock *EndMBB =
1095 LiveInts->getMBBFromIndex(I->end.getPrevSlot());
1096 if (!EndMBB) {
1097 report("Bad end of live segment, no basic block", MF);
1098 I->print(*OS);
1099 *OS << " in " << LI << '\n';
1100 continue;
1102 if (I->end != LiveInts->getMBBEndIdx(EndMBB)) {
1103 // The live segment is ending inside EndMBB
1104 const MachineInstr *MI =
1105 LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
1106 if (!MI) {
1107 report("Live segment doesn't end at a valid instruction", EndMBB);
1108 I->print(*OS);
1109 *OS << " in " << LI << '\n' << "Basic block starts at "
1110 << MBBStartIdx << '\n';
1111 } else if (TargetRegisterInfo::isVirtualRegister(LI.reg) &&
1112 !MI->readsVirtualRegister(LI.reg)) {
1113 // A live range can end with either a redefinition, a kill flag on a
1114 // use, or a dead flag on a def.
1115 // FIXME: Should we check for each of these?
1116 bool hasDeadDef = false;
1117 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1118 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1119 if (MOI->isReg() && MOI->getReg() == LI.reg && MOI->isDef() && MOI->isDead()) {
1120 hasDeadDef = true;
1121 break;
1125 if (!hasDeadDef) {
1126 report("Instruction killing live segment neither defines nor reads "
1127 "register", MI);
1128 I->print(*OS);
1129 *OS << " in " << LI << '\n';
1134 // Now check all the basic blocks in this live segment.
1135 MachineFunction::const_iterator MFI = MBB;
1136 // Is this live range the beginning of a non-PHIDef VN?
1137 if (I->start == VNI->def && !VNI->isPHIDef()) {
1138 // Not live-in to any blocks.
1139 if (MBB == EndMBB)
1140 continue;
1141 // Skip this block.
1142 ++MFI;
1144 for (;;) {
1145 assert(LiveInts->isLiveInToMBB(LI, MFI));
1146 // We don't know how to track physregs into a landing pad.
1147 if (TargetRegisterInfo::isPhysicalRegister(LI.reg) &&
1148 MFI->isLandingPad()) {
1149 if (&*MFI == EndMBB)
1150 break;
1151 ++MFI;
1152 continue;
1154 // Check that VNI is live-out of all predecessors.
1155 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1156 PE = MFI->pred_end(); PI != PE; ++PI) {
1157 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI).getPrevSlot();
1158 const VNInfo *PVNI = LI.getVNInfoAt(PEnd);
1160 if (VNI->isPHIDef() && VNI->def == LiveInts->getMBBStartIdx(MFI)) {
1161 if (PVNI && !PVNI->hasPHIKill()) {
1162 report("Value live out of predecessor doesn't have PHIKill", MF);
1163 *OS << "Valno #" << PVNI->id << " live out of BB#"
1164 << (*PI)->getNumber() << '@' << PEnd
1165 << " doesn't have PHIKill, but Valno #" << VNI->id
1166 << " is PHIDef and defined at the beginning of BB#"
1167 << MFI->getNumber() << '@' << LiveInts->getMBBStartIdx(MFI)
1168 << " in " << LI << '\n';
1170 continue;
1173 if (!PVNI) {
1174 report("Register not marked live out of predecessor", *PI);
1175 *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1176 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live at "
1177 << PEnd << " in " << LI << '\n';
1178 continue;
1181 if (PVNI != VNI) {
1182 report("Different value live out of predecessor", *PI);
1183 *OS << "Valno #" << PVNI->id << " live out of BB#"
1184 << (*PI)->getNumber() << '@' << PEnd
1185 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1186 << '@' << LiveInts->getMBBStartIdx(MFI) << " in " << LI << '\n';
1189 if (&*MFI == EndMBB)
1190 break;
1191 ++MFI;
1195 // Check the LI only has one connected component.
1196 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1197 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1198 unsigned NumComp = ConEQ.Classify(&LI);
1199 if (NumComp > 1) {
1200 report("Multiple connected components in live interval", MF);
1201 *OS << NumComp << " components in " << LI << '\n';
1202 for (unsigned comp = 0; comp != NumComp; ++comp) {
1203 *OS << comp << ": valnos";
1204 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1205 E = LI.vni_end(); I!=E; ++I)
1206 if (comp == ConEQ.getEqClass(*I))
1207 *OS << ' ' << (*I)->id;
1208 *OS << '\n';