MachineVerifier.cpp 31 KB

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