MachineVerifier.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  1. //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Pass to verify generated machine code. The following is checked:
  11. //
  12. // Operand counts: All explicit operands must be present.
  13. //
  14. // Register classes: All physical and virtual register operands must be
  15. // compatible with the register class required by the instruction descriptor.
  16. //
  17. // Register live intervals: Registers must be defined only once, and must be
  18. // defined before use.
  19. //
  20. // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
  21. // command-line option -verify-machineinstrs, or by defining the environment
  22. // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
  23. // the verifier errors.
  24. //===----------------------------------------------------------------------===//
  25. #include "llvm/BasicBlock.h"
  26. #include "llvm/InlineAsm.h"
  27. #include "llvm/Instructions.h"
  28. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  29. #include "llvm/CodeGen/LiveVariables.h"
  30. #include "llvm/CodeGen/LiveStackAnalysis.h"
  31. #include "llvm/CodeGen/MachineInstrBundle.h"
  32. #include "llvm/CodeGen/MachineFunctionPass.h"
  33. #include "llvm/CodeGen/MachineFrameInfo.h"
  34. #include "llvm/CodeGen/MachineMemOperand.h"
  35. #include "llvm/CodeGen/MachineRegisterInfo.h"
  36. #include "llvm/CodeGen/Passes.h"
  37. #include "llvm/MC/MCAsmInfo.h"
  38. #include "llvm/Target/TargetMachine.h"
  39. #include "llvm/Target/TargetRegisterInfo.h"
  40. #include "llvm/Target/TargetInstrInfo.h"
  41. #include "llvm/ADT/DenseSet.h"
  42. #include "llvm/ADT/SetOperations.h"
  43. #include "llvm/ADT/SmallVector.h"
  44. #include "llvm/Support/Debug.h"
  45. #include "llvm/Support/ErrorHandling.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. using namespace llvm;
  48. namespace {
  49. struct MachineVerifier {
  50. MachineVerifier(Pass *pass, const char *b) :
  51. PASS(pass),
  52. Banner(b),
  53. OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
  54. {}
  55. bool runOnMachineFunction(MachineFunction &MF);
  56. Pass *const PASS;
  57. const char *Banner;
  58. const char *const OutFileName;
  59. raw_ostream *OS;
  60. const MachineFunction *MF;
  61. const TargetMachine *TM;
  62. const TargetInstrInfo *TII;
  63. const TargetRegisterInfo *TRI;
  64. const MachineRegisterInfo *MRI;
  65. unsigned foundErrors;
  66. typedef SmallVector<unsigned, 16> RegVector;
  67. typedef SmallVector<const uint32_t*, 4> RegMaskVector;
  68. typedef DenseSet<unsigned> RegSet;
  69. typedef DenseMap<unsigned, const MachineInstr*> RegMap;
  70. typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet;
  71. const MachineInstr *FirstTerminator;
  72. BlockSet FunctionBlocks;
  73. BitVector regsReserved;
  74. RegSet regsLive;
  75. RegVector regsDefined, regsDead, regsKilled;
  76. RegMaskVector regMasks;
  77. RegSet regsLiveInButUnused;
  78. 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 (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  84. RV.push_back(*SubRegs);
  85. }
  86. struct BBInfo {
  87. // Is this MBB reachable from the MF entry point?
  88. bool reachable;
  89. // Vregs that must be live in because they are used without being
  90. // defined. Map value is the user.
  91. RegMap vregsLiveIn;
  92. // Regs killed in MBB. They may be defined again, and will then be in both
  93. // regsKilled and regsLiveOut.
  94. RegSet regsKilled;
  95. // Regs defined in MBB and live out. Note that vregs passing through may
  96. // be live out without being mentioned here.
  97. RegSet regsLiveOut;
  98. // Vregs that pass through MBB untouched. This set is disjoint from
  99. // regsKilled and regsLiveOut.
  100. RegSet vregsPassed;
  101. // Vregs that must pass through MBB because they are needed by a successor
  102. // block. This set is disjoint from regsLiveOut.
  103. RegSet vregsRequired;
  104. // Set versions of block's predecessor and successor lists.
  105. BlockSet Preds, Succs;
  106. BBInfo() : reachable(false) {}
  107. // Add register to vregsPassed if it belongs there. Return true if
  108. // anything changed.
  109. bool addPassed(unsigned Reg) {
  110. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  111. return false;
  112. if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
  113. return false;
  114. return vregsPassed.insert(Reg).second;
  115. }
  116. // Same for a full set.
  117. bool addPassed(const RegSet &RS) {
  118. bool changed = false;
  119. for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
  120. if (addPassed(*I))
  121. changed = true;
  122. return changed;
  123. }
  124. // Add register to vregsRequired if it belongs there. Return true if
  125. // anything changed.
  126. bool addRequired(unsigned Reg) {
  127. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  128. return false;
  129. if (regsLiveOut.count(Reg))
  130. return false;
  131. return vregsRequired.insert(Reg).second;
  132. }
  133. // Same for a full set.
  134. bool addRequired(const RegSet &RS) {
  135. bool changed = false;
  136. for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
  137. if (addRequired(*I))
  138. changed = true;
  139. return changed;
  140. }
  141. // Same for a full map.
  142. bool addRequired(const RegMap &RM) {
  143. bool changed = false;
  144. for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
  145. if (addRequired(I->first))
  146. changed = true;
  147. return changed;
  148. }
  149. // Live-out registers are either in regsLiveOut or vregsPassed.
  150. bool isLiveOut(unsigned Reg) const {
  151. return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
  152. }
  153. };
  154. // Extra register info per MBB.
  155. DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
  156. bool isReserved(unsigned Reg) {
  157. return Reg < regsReserved.size() && regsReserved.test(Reg);
  158. }
  159. bool isAllocatable(unsigned Reg) {
  160. return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg);
  161. }
  162. // Analysis information if available
  163. LiveVariables *LiveVars;
  164. LiveIntervals *LiveInts;
  165. LiveStacks *LiveStks;
  166. SlotIndexes *Indexes;
  167. void visitMachineFunctionBefore();
  168. void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
  169. void visitMachineBundleBefore(const MachineInstr *MI);
  170. void visitMachineInstrBefore(const MachineInstr *MI);
  171. void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
  172. void visitMachineInstrAfter(const MachineInstr *MI);
  173. void visitMachineBundleAfter(const MachineInstr *MI);
  174. void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
  175. void visitMachineFunctionAfter();
  176. void report(const char *msg, const MachineFunction *MF);
  177. void report(const char *msg, const MachineBasicBlock *MBB);
  178. void report(const char *msg, const MachineInstr *MI);
  179. void report(const char *msg, const MachineOperand *MO, unsigned MONum);
  180. void report(const char *msg, const MachineFunction *MF,
  181. const LiveInterval &LI);
  182. void report(const char *msg, const MachineBasicBlock *MBB,
  183. const LiveInterval &LI);
  184. void verifyInlineAsm(const MachineInstr *MI);
  185. void checkLiveness(const MachineOperand *MO, unsigned MONum);
  186. void markReachable(const MachineBasicBlock *MBB);
  187. void calcRegsPassed();
  188. void checkPHIOps(const MachineBasicBlock *MBB);
  189. void calcRegsRequired();
  190. void verifyLiveVariables();
  191. void verifyLiveIntervals();
  192. void verifyLiveInterval(const LiveInterval&);
  193. void verifyLiveIntervalValue(const LiveInterval&, VNInfo*);
  194. void verifyLiveIntervalSegment(const LiveInterval&,
  195. LiveInterval::const_iterator);
  196. };
  197. struct MachineVerifierPass : public MachineFunctionPass {
  198. static char ID; // Pass ID, replacement for typeid
  199. const char *const Banner;
  200. MachineVerifierPass(const char *b = 0)
  201. : MachineFunctionPass(ID), Banner(b) {
  202. initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
  203. }
  204. void getAnalysisUsage(AnalysisUsage &AU) const {
  205. AU.setPreservesAll();
  206. MachineFunctionPass::getAnalysisUsage(AU);
  207. }
  208. bool runOnMachineFunction(MachineFunction &MF) {
  209. MF.verify(this, Banner);
  210. return false;
  211. }
  212. };
  213. }
  214. char MachineVerifierPass::ID = 0;
  215. INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
  216. "Verify generated machine code", false, false)
  217. FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
  218. return new MachineVerifierPass(Banner);
  219. }
  220. void MachineFunction::verify(Pass *p, const char *Banner) const {
  221. MachineVerifier(p, Banner)
  222. .runOnMachineFunction(const_cast<MachineFunction&>(*this));
  223. }
  224. bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
  225. raw_ostream *OutFile = 0;
  226. if (OutFileName) {
  227. std::string ErrorInfo;
  228. OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
  229. raw_fd_ostream::F_Append);
  230. if (!ErrorInfo.empty()) {
  231. errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
  232. exit(1);
  233. }
  234. OS = OutFile;
  235. } else {
  236. OS = &errs();
  237. }
  238. foundErrors = 0;
  239. this->MF = &MF;
  240. TM = &MF.getTarget();
  241. TII = TM->getInstrInfo();
  242. TRI = TM->getRegisterInfo();
  243. MRI = &MF.getRegInfo();
  244. LiveVars = NULL;
  245. LiveInts = NULL;
  246. LiveStks = NULL;
  247. Indexes = NULL;
  248. if (PASS) {
  249. LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
  250. // We don't want to verify LiveVariables if LiveIntervals is available.
  251. if (!LiveInts)
  252. LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
  253. LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
  254. Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
  255. }
  256. visitMachineFunctionBefore();
  257. for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
  258. MFI!=MFE; ++MFI) {
  259. visitMachineBasicBlockBefore(MFI);
  260. // Keep track of the current bundle header.
  261. const MachineInstr *CurBundle = 0;
  262. for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
  263. MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
  264. if (MBBI->getParent() != MFI) {
  265. report("Bad instruction parent pointer", MFI);
  266. *OS << "Instruction: " << *MBBI;
  267. continue;
  268. }
  269. // Is this a bundle header?
  270. if (!MBBI->isInsideBundle()) {
  271. if (CurBundle)
  272. visitMachineBundleAfter(CurBundle);
  273. CurBundle = MBBI;
  274. visitMachineBundleBefore(CurBundle);
  275. } else if (!CurBundle)
  276. report("No bundle header", MBBI);
  277. visitMachineInstrBefore(MBBI);
  278. for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
  279. visitMachineOperand(&MBBI->getOperand(I), I);
  280. visitMachineInstrAfter(MBBI);
  281. }
  282. if (CurBundle)
  283. visitMachineBundleAfter(CurBundle);
  284. visitMachineBasicBlockAfter(MFI);
  285. }
  286. visitMachineFunctionAfter();
  287. if (OutFile)
  288. delete OutFile;
  289. else if (foundErrors)
  290. report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
  291. // Clean up.
  292. regsLive.clear();
  293. regsDefined.clear();
  294. regsDead.clear();
  295. regsKilled.clear();
  296. regMasks.clear();
  297. regsLiveInButUnused.clear();
  298. MBBInfoMap.clear();
  299. return false; // no changes
  300. }
  301. void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
  302. assert(MF);
  303. *OS << '\n';
  304. if (!foundErrors++) {
  305. if (Banner)
  306. *OS << "# " << Banner << '\n';
  307. MF->print(*OS, Indexes);
  308. }
  309. *OS << "*** Bad machine code: " << msg << " ***\n"
  310. << "- function: " << MF->getName() << "\n";
  311. }
  312. void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
  313. assert(MBB);
  314. report(msg, MBB->getParent());
  315. *OS << "- basic block: BB#" << MBB->getNumber()
  316. << ' ' << MBB->getName()
  317. << " (" << (const void*)MBB << ')';
  318. if (Indexes)
  319. *OS << " [" << Indexes->getMBBStartIdx(MBB)
  320. << ';' << Indexes->getMBBEndIdx(MBB) << ')';
  321. *OS << '\n';
  322. }
  323. void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
  324. assert(MI);
  325. report(msg, MI->getParent());
  326. *OS << "- instruction: ";
  327. if (Indexes && Indexes->hasIndex(MI))
  328. *OS << Indexes->getInstructionIndex(MI) << '\t';
  329. MI->print(*OS, TM);
  330. }
  331. void MachineVerifier::report(const char *msg,
  332. const MachineOperand *MO, unsigned MONum) {
  333. assert(MO);
  334. report(msg, MO->getParent());
  335. *OS << "- operand " << MONum << ": ";
  336. MO->print(*OS, TM);
  337. *OS << "\n";
  338. }
  339. void MachineVerifier::report(const char *msg, const MachineFunction *MF,
  340. const LiveInterval &LI) {
  341. report(msg, MF);
  342. *OS << "- interval: ";
  343. if (TargetRegisterInfo::isVirtualRegister(LI.reg))
  344. *OS << PrintReg(LI.reg, TRI);
  345. else
  346. *OS << PrintRegUnit(LI.reg, TRI);
  347. *OS << ' ' << LI << '\n';
  348. }
  349. void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
  350. const LiveInterval &LI) {
  351. report(msg, MBB);
  352. *OS << "- interval: ";
  353. if (TargetRegisterInfo::isVirtualRegister(LI.reg))
  354. *OS << PrintReg(LI.reg, TRI);
  355. else
  356. *OS << PrintRegUnit(LI.reg, TRI);
  357. *OS << ' ' << LI << '\n';
  358. }
  359. void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
  360. BBInfo &MInfo = MBBInfoMap[MBB];
  361. if (!MInfo.reachable) {
  362. MInfo.reachable = true;
  363. for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
  364. SuE = MBB->succ_end(); SuI != SuE; ++SuI)
  365. markReachable(*SuI);
  366. }
  367. }
  368. void MachineVerifier::visitMachineFunctionBefore() {
  369. lastIndex = SlotIndex();
  370. regsReserved = MRI->getReservedRegs();
  371. // A sub-register of a reserved register is also reserved
  372. for (int Reg = regsReserved.find_first(); Reg>=0;
  373. Reg = regsReserved.find_next(Reg)) {
  374. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  375. // FIXME: This should probably be:
  376. // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register");
  377. regsReserved.set(*SubRegs);
  378. }
  379. }
  380. markReachable(&MF->front());
  381. // Build a set of the basic blocks in the function.
  382. FunctionBlocks.clear();
  383. for (MachineFunction::const_iterator
  384. I = MF->begin(), E = MF->end(); I != E; ++I) {
  385. FunctionBlocks.insert(I);
  386. BBInfo &MInfo = MBBInfoMap[I];
  387. MInfo.Preds.insert(I->pred_begin(), I->pred_end());
  388. if (MInfo.Preds.size() != I->pred_size())
  389. report("MBB has duplicate entries in its predecessor list.", I);
  390. MInfo.Succs.insert(I->succ_begin(), I->succ_end());
  391. if (MInfo.Succs.size() != I->succ_size())
  392. report("MBB has duplicate entries in its successor list.", I);
  393. }
  394. }
  395. // Does iterator point to a and b as the first two elements?
  396. static bool matchPair(MachineBasicBlock::const_succ_iterator i,
  397. const MachineBasicBlock *a, const MachineBasicBlock *b) {
  398. if (*i == a)
  399. return *++i == b;
  400. if (*i == b)
  401. return *++i == a;
  402. return false;
  403. }
  404. void
  405. MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
  406. FirstTerminator = 0;
  407. if (MRI->isSSA()) {
  408. // If this block has allocatable physical registers live-in, check that
  409. // it is an entry block or landing pad.
  410. for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
  411. LE = MBB->livein_end();
  412. LI != LE; ++LI) {
  413. unsigned reg = *LI;
  414. if (isAllocatable(reg) && !MBB->isLandingPad() &&
  415. MBB != MBB->getParent()->begin()) {
  416. report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
  417. }
  418. }
  419. }
  420. // Count the number of landing pad successors.
  421. SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
  422. for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
  423. E = MBB->succ_end(); I != E; ++I) {
  424. if ((*I)->isLandingPad())
  425. LandingPadSuccs.insert(*I);
  426. if (!FunctionBlocks.count(*I))
  427. report("MBB has successor that isn't part of the function.", MBB);
  428. if (!MBBInfoMap[*I].Preds.count(MBB)) {
  429. report("Inconsistent CFG", MBB);
  430. *OS << "MBB is not in the predecessor list of the successor BB#"
  431. << (*I)->getNumber() << ".\n";
  432. }
  433. }
  434. // Check the predecessor list.
  435. for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
  436. E = MBB->pred_end(); I != E; ++I) {
  437. if (!FunctionBlocks.count(*I))
  438. report("MBB has predecessor that isn't part of the function.", MBB);
  439. if (!MBBInfoMap[*I].Succs.count(MBB)) {
  440. report("Inconsistent CFG", MBB);
  441. *OS << "MBB is not in the successor list of the predecessor BB#"
  442. << (*I)->getNumber() << ".\n";
  443. }
  444. }
  445. const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
  446. const BasicBlock *BB = MBB->getBasicBlock();
  447. if (LandingPadSuccs.size() > 1 &&
  448. !(AsmInfo &&
  449. AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
  450. BB && isa<SwitchInst>(BB->getTerminator())))
  451. report("MBB has more than one landing pad successor", MBB);
  452. // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
  453. MachineBasicBlock *TBB = 0, *FBB = 0;
  454. SmallVector<MachineOperand, 4> Cond;
  455. if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
  456. TBB, FBB, Cond)) {
  457. // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
  458. // check whether its answers match up with reality.
  459. if (!TBB && !FBB) {
  460. // Block falls through to its successor.
  461. MachineFunction::const_iterator MBBI = MBB;
  462. ++MBBI;
  463. if (MBBI == MF->end()) {
  464. // It's possible that the block legitimately ends with a noreturn
  465. // call or an unreachable, in which case it won't actually fall
  466. // out the bottom of the function.
  467. } else if (MBB->succ_size() == LandingPadSuccs.size()) {
  468. // It's possible that the block legitimately ends with a noreturn
  469. // call or an unreachable, in which case it won't actuall fall
  470. // out of the block.
  471. } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
  472. report("MBB exits via unconditional fall-through but doesn't have "
  473. "exactly one CFG successor!", MBB);
  474. } else if (!MBB->isSuccessor(MBBI)) {
  475. report("MBB exits via unconditional fall-through but its successor "
  476. "differs from its CFG successor!", MBB);
  477. }
  478. if (!MBB->empty() && getBundleStart(&MBB->back())->isBarrier() &&
  479. !TII->isPredicated(getBundleStart(&MBB->back()))) {
  480. report("MBB exits via unconditional fall-through but ends with a "
  481. "barrier instruction!", MBB);
  482. }
  483. if (!Cond.empty()) {
  484. report("MBB exits via unconditional fall-through but has a condition!",
  485. MBB);
  486. }
  487. } else if (TBB && !FBB && Cond.empty()) {
  488. // Block unconditionally branches somewhere.
  489. if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
  490. report("MBB exits via unconditional branch but doesn't have "
  491. "exactly one CFG successor!", MBB);
  492. } else if (!MBB->isSuccessor(TBB)) {
  493. report("MBB exits via unconditional branch but the CFG "
  494. "successor doesn't match the actual successor!", MBB);
  495. }
  496. if (MBB->empty()) {
  497. report("MBB exits via unconditional branch but doesn't contain "
  498. "any instructions!", MBB);
  499. } else if (!getBundleStart(&MBB->back())->isBarrier()) {
  500. report("MBB exits via unconditional branch but doesn't end with a "
  501. "barrier instruction!", MBB);
  502. } else if (!getBundleStart(&MBB->back())->isTerminator()) {
  503. report("MBB exits via unconditional branch but the branch isn't a "
  504. "terminator instruction!", MBB);
  505. }
  506. } else if (TBB && !FBB && !Cond.empty()) {
  507. // Block conditionally branches somewhere, otherwise falls through.
  508. MachineFunction::const_iterator MBBI = MBB;
  509. ++MBBI;
  510. if (MBBI == MF->end()) {
  511. report("MBB conditionally falls through out of function!", MBB);
  512. } if (MBB->succ_size() == 1) {
  513. // A conditional branch with only one successor is weird, but allowed.
  514. if (&*MBBI != TBB)
  515. report("MBB exits via conditional branch/fall-through but only has "
  516. "one CFG successor!", MBB);
  517. else if (TBB != *MBB->succ_begin())
  518. report("MBB exits via conditional branch/fall-through but the CFG "
  519. "successor don't match the actual successor!", MBB);
  520. } else if (MBB->succ_size() != 2) {
  521. report("MBB exits via conditional branch/fall-through but doesn't have "
  522. "exactly two CFG successors!", MBB);
  523. } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
  524. report("MBB exits via conditional branch/fall-through but the CFG "
  525. "successors don't match the actual successors!", MBB);
  526. }
  527. if (MBB->empty()) {
  528. report("MBB exits via conditional branch/fall-through but doesn't "
  529. "contain any instructions!", MBB);
  530. } else if (getBundleStart(&MBB->back())->isBarrier()) {
  531. report("MBB exits via conditional branch/fall-through but ends with a "
  532. "barrier instruction!", MBB);
  533. } else if (!getBundleStart(&MBB->back())->isTerminator()) {
  534. report("MBB exits via conditional branch/fall-through but the branch "
  535. "isn't a terminator instruction!", MBB);
  536. }
  537. } else if (TBB && FBB) {
  538. // Block conditionally branches somewhere, otherwise branches
  539. // somewhere else.
  540. if (MBB->succ_size() == 1) {
  541. // A conditional branch with only one successor is weird, but allowed.
  542. if (FBB != TBB)
  543. report("MBB exits via conditional branch/branch through but only has "
  544. "one CFG successor!", MBB);
  545. else if (TBB != *MBB->succ_begin())
  546. report("MBB exits via conditional branch/branch through but the CFG "
  547. "successor don't match the actual successor!", MBB);
  548. } else if (MBB->succ_size() != 2) {
  549. report("MBB exits via conditional branch/branch but doesn't have "
  550. "exactly two CFG successors!", MBB);
  551. } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
  552. report("MBB exits via conditional branch/branch but the CFG "
  553. "successors don't match the actual successors!", MBB);
  554. }
  555. if (MBB->empty()) {
  556. report("MBB exits via conditional branch/branch but doesn't "
  557. "contain any instructions!", MBB);
  558. } else if (!getBundleStart(&MBB->back())->isBarrier()) {
  559. report("MBB exits via conditional branch/branch but doesn't end with a "
  560. "barrier instruction!", MBB);
  561. } else if (!getBundleStart(&MBB->back())->isTerminator()) {
  562. report("MBB exits via conditional branch/branch but the branch "
  563. "isn't a terminator instruction!", MBB);
  564. }
  565. if (Cond.empty()) {
  566. report("MBB exits via conditinal branch/branch but there's no "
  567. "condition!", MBB);
  568. }
  569. } else {
  570. report("AnalyzeBranch returned invalid data!", MBB);
  571. }
  572. }
  573. regsLive.clear();
  574. for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
  575. E = MBB->livein_end(); I != E; ++I) {
  576. if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
  577. report("MBB live-in list contains non-physical register", MBB);
  578. continue;
  579. }
  580. regsLive.insert(*I);
  581. for (MCSubRegIterator SubRegs(*I, TRI); SubRegs.isValid(); ++SubRegs)
  582. regsLive.insert(*SubRegs);
  583. }
  584. regsLiveInButUnused = regsLive;
  585. const MachineFrameInfo *MFI = MF->getFrameInfo();
  586. assert(MFI && "Function has no frame info");
  587. BitVector PR = MFI->getPristineRegs(MBB);
  588. for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
  589. regsLive.insert(I);
  590. for (MCSubRegIterator SubRegs(I, TRI); SubRegs.isValid(); ++SubRegs)
  591. regsLive.insert(*SubRegs);
  592. }
  593. regsKilled.clear();
  594. regsDefined.clear();
  595. if (Indexes)
  596. lastIndex = Indexes->getMBBStartIdx(MBB);
  597. }
  598. // This function gets called for all bundle headers, including normal
  599. // stand-alone unbundled instructions.
  600. void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
  601. if (Indexes && Indexes->hasIndex(MI)) {
  602. SlotIndex idx = Indexes->getInstructionIndex(MI);
  603. if (!(idx > lastIndex)) {
  604. report("Instruction index out of order", MI);
  605. *OS << "Last instruction was at " << lastIndex << '\n';
  606. }
  607. lastIndex = idx;
  608. }
  609. // Ensure non-terminators don't follow terminators.
  610. // Ignore predicated terminators formed by if conversion.
  611. // FIXME: If conversion shouldn't need to violate this rule.
  612. if (MI->isTerminator() && !TII->isPredicated(MI)) {
  613. if (!FirstTerminator)
  614. FirstTerminator = MI;
  615. } else if (FirstTerminator) {
  616. report("Non-terminator instruction after the first terminator", MI);
  617. *OS << "First terminator was:\t" << *FirstTerminator;
  618. }
  619. }
  620. // The operands on an INLINEASM instruction must follow a template.
  621. // Verify that the flag operands make sense.
  622. void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
  623. // The first two operands on INLINEASM are the asm string and global flags.
  624. if (MI->getNumOperands() < 2) {
  625. report("Too few operands on inline asm", MI);
  626. return;
  627. }
  628. if (!MI->getOperand(0).isSymbol())
  629. report("Asm string must be an external symbol", MI);
  630. if (!MI->getOperand(1).isImm())
  631. report("Asm flags must be an immediate", MI);
  632. // Allowed flags are Extra_HasSideEffects = 1, and Extra_IsAlignStack = 2.
  633. if (!isUInt<2>(MI->getOperand(1).getImm()))
  634. report("Unknown asm flags", &MI->getOperand(1), 1);
  635. assert(InlineAsm::MIOp_FirstOperand == 2 && "Asm format changed");
  636. unsigned OpNo = InlineAsm::MIOp_FirstOperand;
  637. unsigned NumOps;
  638. for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
  639. const MachineOperand &MO = MI->getOperand(OpNo);
  640. // There may be implicit ops after the fixed operands.
  641. if (!MO.isImm())
  642. break;
  643. NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
  644. }
  645. if (OpNo > MI->getNumOperands())
  646. report("Missing operands in last group", MI);
  647. // An optional MDNode follows the groups.
  648. if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
  649. ++OpNo;
  650. // All trailing operands must be implicit registers.
  651. for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
  652. const MachineOperand &MO = MI->getOperand(OpNo);
  653. if (!MO.isReg() || !MO.isImplicit())
  654. report("Expected implicit register after groups", &MO, OpNo);
  655. }
  656. }
  657. void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
  658. const MCInstrDesc &MCID = MI->getDesc();
  659. if (MI->getNumOperands() < MCID.getNumOperands()) {
  660. report("Too few operands", MI);
  661. *OS << MCID.getNumOperands() << " operands expected, but "
  662. << MI->getNumExplicitOperands() << " given.\n";
  663. }
  664. // Check the tied operands.
  665. if (MI->isInlineAsm())
  666. verifyInlineAsm(MI);
  667. // Check the MachineMemOperands for basic consistency.
  668. for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
  669. E = MI->memoperands_end(); I != E; ++I) {
  670. if ((*I)->isLoad() && !MI->mayLoad())
  671. report("Missing mayLoad flag", MI);
  672. if ((*I)->isStore() && !MI->mayStore())
  673. report("Missing mayStore flag", MI);
  674. }
  675. // Debug values must not have a slot index.
  676. // Other instructions must have one, unless they are inside a bundle.
  677. if (LiveInts) {
  678. bool mapped = !LiveInts->isNotInMIMap(MI);
  679. if (MI->isDebugValue()) {
  680. if (mapped)
  681. report("Debug instruction has a slot index", MI);
  682. } else if (MI->isInsideBundle()) {
  683. if (mapped)
  684. report("Instruction inside bundle has a slot index", MI);
  685. } else {
  686. if (!mapped)
  687. report("Missing slot index", MI);
  688. }
  689. }
  690. StringRef ErrorInfo;
  691. if (!TII->verifyInstruction(MI, ErrorInfo))
  692. report(ErrorInfo.data(), MI);
  693. }
  694. void
  695. MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
  696. const MachineInstr *MI = MO->getParent();
  697. const MCInstrDesc &MCID = MI->getDesc();
  698. // The first MCID.NumDefs operands must be explicit register defines
  699. if (MONum < MCID.getNumDefs()) {
  700. const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
  701. if (!MO->isReg())
  702. report("Explicit definition must be a register", MO, MONum);
  703. else if (!MO->isDef() && !MCOI.isOptionalDef())
  704. report("Explicit definition marked as use", MO, MONum);
  705. else if (MO->isImplicit())
  706. report("Explicit definition marked as implicit", MO, MONum);
  707. } else if (MONum < MCID.getNumOperands()) {
  708. const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
  709. // Don't check if it's the last operand in a variadic instruction. See,
  710. // e.g., LDM_RET in the arm back end.
  711. if (MO->isReg() &&
  712. !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
  713. if (MO->isDef() && !MCOI.isOptionalDef())
  714. report("Explicit operand marked as def", MO, MONum);
  715. if (MO->isImplicit())
  716. report("Explicit operand marked as implicit", MO, MONum);
  717. }
  718. int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
  719. if (TiedTo != -1) {
  720. if (!MO->isReg())
  721. report("Tied use must be a register", MO, MONum);
  722. else if (!MO->isTied())
  723. report("Operand should be tied", MO, MONum);
  724. else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
  725. report("Tied def doesn't match MCInstrDesc", MO, MONum);
  726. } else if (MO->isReg() && MO->isTied())
  727. report("Explicit operand should not be tied", MO, MONum);
  728. } else {
  729. // ARM adds %reg0 operands to indicate predicates. We'll allow that.
  730. if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
  731. report("Extra explicit operand on non-variadic instruction", MO, MONum);
  732. }
  733. switch (MO->getType()) {
  734. case MachineOperand::MO_Register: {
  735. const unsigned Reg = MO->getReg();
  736. if (!Reg)
  737. return;
  738. if (MRI->tracksLiveness() && !MI->isDebugValue())
  739. checkLiveness(MO, MONum);
  740. // Verify the consistency of tied operands.
  741. if (MO->isTied()) {
  742. unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
  743. const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
  744. if (!OtherMO.isReg())
  745. report("Must be tied to a register", MO, MONum);
  746. if (!OtherMO.isTied())
  747. report("Missing tie flags on tied operand", MO, MONum);
  748. if (MI->findTiedOperandIdx(OtherIdx) != MONum)
  749. report("Inconsistent tie links", MO, MONum);
  750. if (MONum < MCID.getNumDefs()) {
  751. if (OtherIdx < MCID.getNumOperands()) {
  752. if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
  753. report("Explicit def tied to explicit use without tie constraint",
  754. MO, MONum);
  755. } else {
  756. if (!OtherMO.isImplicit())
  757. report("Explicit def should be tied to implicit use", MO, MONum);
  758. }
  759. }
  760. }
  761. // Verify two-address constraints after leaving SSA form.
  762. unsigned DefIdx;
  763. if (!MRI->isSSA() && MO->isUse() &&
  764. MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
  765. Reg != MI->getOperand(DefIdx).getReg())
  766. report("Two-address instruction operands must be identical", MO, MONum);
  767. // Check register classes.
  768. if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
  769. unsigned SubIdx = MO->getSubReg();
  770. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  771. if (SubIdx) {
  772. report("Illegal subregister index for physical register", MO, MONum);
  773. return;
  774. }
  775. if (const TargetRegisterClass *DRC =
  776. TII->getRegClass(MCID, MONum, TRI, *MF)) {
  777. if (!DRC->contains(Reg)) {
  778. report("Illegal physical register for instruction", MO, MONum);
  779. *OS << TRI->getName(Reg) << " is not a "
  780. << DRC->getName() << " register.\n";
  781. }
  782. }
  783. } else {
  784. // Virtual register.
  785. const TargetRegisterClass *RC = MRI->getRegClass(Reg);
  786. if (SubIdx) {
  787. const TargetRegisterClass *SRC =
  788. TRI->getSubClassWithSubReg(RC, SubIdx);
  789. if (!SRC) {
  790. report("Invalid subregister index for virtual register", MO, MONum);
  791. *OS << "Register class " << RC->getName()
  792. << " does not support subreg index " << SubIdx << "\n";
  793. return;
  794. }
  795. if (RC != SRC) {
  796. report("Invalid register class for subregister index", MO, MONum);
  797. *OS << "Register class " << RC->getName()
  798. << " does not fully support subreg index " << SubIdx << "\n";
  799. return;
  800. }
  801. }
  802. if (const TargetRegisterClass *DRC =
  803. TII->getRegClass(MCID, MONum, TRI, *MF)) {
  804. if (SubIdx) {
  805. const TargetRegisterClass *SuperRC =
  806. TRI->getLargestLegalSuperClass(RC);
  807. if (!SuperRC) {
  808. report("No largest legal super class exists.", MO, MONum);
  809. return;
  810. }
  811. DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
  812. if (!DRC) {
  813. report("No matching super-reg register class.", MO, MONum);
  814. return;
  815. }
  816. }
  817. if (!RC->hasSuperClassEq(DRC)) {
  818. report("Illegal virtual register for instruction", MO, MONum);
  819. *OS << "Expected a " << DRC->getName() << " register, but got a "
  820. << RC->getName() << " register\n";
  821. }
  822. }
  823. }
  824. }
  825. break;
  826. }
  827. case MachineOperand::MO_RegisterMask:
  828. regMasks.push_back(MO->getRegMask());
  829. break;
  830. case MachineOperand::MO_MachineBasicBlock:
  831. if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
  832. report("PHI operand is not in the CFG", MO, MONum);
  833. break;
  834. case MachineOperand::MO_FrameIndex:
  835. if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
  836. LiveInts && !LiveInts->isNotInMIMap(MI)) {
  837. LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
  838. SlotIndex Idx = LiveInts->getInstructionIndex(MI);
  839. if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
  840. report("Instruction loads from dead spill slot", MO, MONum);
  841. *OS << "Live stack: " << LI << '\n';
  842. }
  843. if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
  844. report("Instruction stores to dead spill slot", MO, MONum);
  845. *OS << "Live stack: " << LI << '\n';
  846. }
  847. }
  848. break;
  849. default:
  850. break;
  851. }
  852. }
  853. void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
  854. const MachineInstr *MI = MO->getParent();
  855. const unsigned Reg = MO->getReg();
  856. // Both use and def operands can read a register.
  857. if (MO->readsReg()) {
  858. regsLiveInButUnused.erase(Reg);
  859. if (MO->isKill())
  860. addRegWithSubRegs(regsKilled, Reg);
  861. // Check that LiveVars knows this kill.
  862. if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
  863. MO->isKill()) {
  864. LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
  865. if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end())
  866. report("Kill missing from LiveVariables", MO, MONum);
  867. }
  868. // Check LiveInts liveness and kill.
  869. if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
  870. SlotIndex UseIdx = LiveInts->getInstructionIndex(MI);
  871. // Check the cached regunit intervals.
  872. if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
  873. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
  874. if (const LiveInterval *LI = LiveInts->getCachedRegUnit(*Units)) {
  875. LiveRangeQuery LRQ(*LI, UseIdx);
  876. if (!LRQ.valueIn()) {
  877. report("No live range at use", MO, MONum);
  878. *OS << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI)
  879. << ' ' << *LI << '\n';
  880. }
  881. if (MO->isKill() && !LRQ.isKill()) {
  882. report("Live range continues after kill flag", MO, MONum);
  883. *OS << PrintRegUnit(*Units, TRI) << ' ' << *LI << '\n';
  884. }
  885. }
  886. }
  887. }
  888. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  889. if (LiveInts->hasInterval(Reg)) {
  890. // This is a virtual register interval.
  891. const LiveInterval &LI = LiveInts->getInterval(Reg);
  892. LiveRangeQuery LRQ(LI, UseIdx);
  893. if (!LRQ.valueIn()) {
  894. report("No live range at use", MO, MONum);
  895. *OS << UseIdx << " is not live in " << LI << '\n';
  896. }
  897. // Check for extra kill flags.
  898. // Note that we allow missing kill flags for now.
  899. if (MO->isKill() && !LRQ.isKill()) {
  900. report("Live range continues after kill flag", MO, MONum);
  901. *OS << "Live range: " << LI << '\n';
  902. }
  903. } else {
  904. report("Virtual register has no live interval", MO, MONum);
  905. }
  906. }
  907. }
  908. // Use of a dead register.
  909. if (!regsLive.count(Reg)) {
  910. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  911. // Reserved registers may be used even when 'dead'.
  912. if (!isReserved(Reg))
  913. report("Using an undefined physical register", MO, MONum);
  914. } else if (MRI->def_empty(Reg)) {
  915. report("Reading virtual register without a def", MO, MONum);
  916. } else {
  917. BBInfo &MInfo = MBBInfoMap[MI->getParent()];
  918. // We don't know which virtual registers are live in, so only complain
  919. // if vreg was killed in this MBB. Otherwise keep track of vregs that
  920. // must be live in. PHI instructions are handled separately.
  921. if (MInfo.regsKilled.count(Reg))
  922. report("Using a killed virtual register", MO, MONum);
  923. else if (!MI->isPHI())
  924. MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
  925. }
  926. }
  927. }
  928. if (MO->isDef()) {
  929. // Register defined.
  930. // TODO: verify that earlyclobber ops are not used.
  931. if (MO->isDead())
  932. addRegWithSubRegs(regsDead, Reg);
  933. else
  934. addRegWithSubRegs(regsDefined, Reg);
  935. // Verify SSA form.
  936. if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
  937. llvm::next(MRI->def_begin(Reg)) != MRI->def_end())
  938. report("Multiple virtual register defs in SSA form", MO, MONum);
  939. // Check LiveInts for a live range, but only for virtual registers.
  940. if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
  941. !LiveInts->isNotInMIMap(MI)) {
  942. SlotIndex DefIdx = LiveInts->getInstructionIndex(MI);
  943. DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
  944. if (LiveInts->hasInterval(Reg)) {
  945. const LiveInterval &LI = LiveInts->getInterval(Reg);
  946. if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
  947. assert(VNI && "NULL valno is not allowed");
  948. if (VNI->def != DefIdx) {
  949. report("Inconsistent valno->def", MO, MONum);
  950. *OS << "Valno " << VNI->id << " is not defined at "
  951. << DefIdx << " in " << LI << '\n';
  952. }
  953. } else {
  954. report("No live range at def", MO, MONum);
  955. *OS << DefIdx << " is not live in " << LI << '\n';
  956. }
  957. } else {
  958. report("Virtual register has no Live interval", MO, MONum);
  959. }
  960. }
  961. }
  962. }
  963. void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
  964. }
  965. // This function gets called after visiting all instructions in a bundle. The
  966. // argument points to the bundle header.
  967. // Normal stand-alone instructions are also considered 'bundles', and this
  968. // function is called for all of them.
  969. void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
  970. BBInfo &MInfo = MBBInfoMap[MI->getParent()];
  971. set_union(MInfo.regsKilled, regsKilled);
  972. set_subtract(regsLive, regsKilled); regsKilled.clear();
  973. // Kill any masked registers.
  974. while (!regMasks.empty()) {
  975. const uint32_t *Mask = regMasks.pop_back_val();
  976. for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
  977. if (TargetRegisterInfo::isPhysicalRegister(*I) &&
  978. MachineOperand::clobbersPhysReg(Mask, *I))
  979. regsDead.push_back(*I);
  980. }
  981. set_subtract(regsLive, regsDead); regsDead.clear();
  982. set_union(regsLive, regsDefined); regsDefined.clear();
  983. }
  984. void
  985. MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
  986. MBBInfoMap[MBB].regsLiveOut = regsLive;
  987. regsLive.clear();
  988. if (Indexes) {
  989. SlotIndex stop = Indexes->getMBBEndIdx(MBB);
  990. if (!(stop > lastIndex)) {
  991. report("Block ends before last instruction index", MBB);
  992. *OS << "Block ends at " << stop
  993. << " last instruction was at " << lastIndex << '\n';
  994. }
  995. lastIndex = stop;
  996. }
  997. }
  998. // Calculate the largest possible vregsPassed sets. These are the registers that
  999. // can pass through an MBB live, but may not be live every time. It is assumed
  1000. // that all vregsPassed sets are empty before the call.
  1001. void MachineVerifier::calcRegsPassed() {
  1002. // First push live-out regs to successors' vregsPassed. Remember the MBBs that
  1003. // have any vregsPassed.
  1004. SmallPtrSet<const MachineBasicBlock*, 8> todo;
  1005. for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
  1006. MFI != MFE; ++MFI) {
  1007. const MachineBasicBlock &MBB(*MFI);
  1008. BBInfo &MInfo = MBBInfoMap[&MBB];
  1009. if (!MInfo.reachable)
  1010. continue;
  1011. for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
  1012. SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
  1013. BBInfo &SInfo = MBBInfoMap[*SuI];
  1014. if (SInfo.addPassed(MInfo.regsLiveOut))
  1015. todo.insert(*SuI);
  1016. }
  1017. }
  1018. // Iteratively push vregsPassed to successors. This will converge to the same
  1019. // final state regardless of DenseSet iteration order.
  1020. while (!todo.empty()) {
  1021. const MachineBasicBlock *MBB = *todo.begin();
  1022. todo.erase(MBB);
  1023. BBInfo &MInfo = MBBInfoMap[MBB];
  1024. for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
  1025. SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
  1026. if (*SuI == MBB)
  1027. continue;
  1028. BBInfo &SInfo = MBBInfoMap[*SuI];
  1029. if (SInfo.addPassed(MInfo.vregsPassed))
  1030. todo.insert(*SuI);
  1031. }
  1032. }
  1033. }
  1034. // Calculate the set of virtual registers that must be passed through each basic
  1035. // block in order to satisfy the requirements of successor blocks. This is very
  1036. // similar to calcRegsPassed, only backwards.
  1037. void MachineVerifier::calcRegsRequired() {
  1038. // First push live-in regs to predecessors' vregsRequired.
  1039. SmallPtrSet<const MachineBasicBlock*, 8> todo;
  1040. for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
  1041. MFI != MFE; ++MFI) {
  1042. const MachineBasicBlock &MBB(*MFI);
  1043. BBInfo &MInfo = MBBInfoMap[&MBB];
  1044. for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
  1045. PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
  1046. BBInfo &PInfo = MBBInfoMap[*PrI];
  1047. if (PInfo.addRequired(MInfo.vregsLiveIn))
  1048. todo.insert(*PrI);
  1049. }
  1050. }
  1051. // Iteratively push vregsRequired to predecessors. This will converge to the
  1052. // same final state regardless of DenseSet iteration order.
  1053. while (!todo.empty()) {
  1054. const MachineBasicBlock *MBB = *todo.begin();
  1055. todo.erase(MBB);
  1056. BBInfo &MInfo = MBBInfoMap[MBB];
  1057. for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
  1058. PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
  1059. if (*PrI == MBB)
  1060. continue;
  1061. BBInfo &SInfo = MBBInfoMap[*PrI];
  1062. if (SInfo.addRequired(MInfo.vregsRequired))
  1063. todo.insert(*PrI);
  1064. }
  1065. }
  1066. }
  1067. // Check PHI instructions at the beginning of MBB. It is assumed that
  1068. // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
  1069. void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
  1070. SmallPtrSet<const MachineBasicBlock*, 8> seen;
  1071. for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
  1072. BBI != BBE && BBI->isPHI(); ++BBI) {
  1073. seen.clear();
  1074. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
  1075. unsigned Reg = BBI->getOperand(i).getReg();
  1076. const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
  1077. if (!Pre->isSuccessor(MBB))
  1078. continue;
  1079. seen.insert(Pre);
  1080. BBInfo &PrInfo = MBBInfoMap[Pre];
  1081. if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
  1082. report("PHI operand is not live-out from predecessor",
  1083. &BBI->getOperand(i), i);
  1084. }
  1085. // Did we see all predecessors?
  1086. for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
  1087. PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
  1088. if (!seen.count(*PrI)) {
  1089. report("Missing PHI operand", BBI);
  1090. *OS << "BB#" << (*PrI)->getNumber()
  1091. << " is a predecessor according to the CFG.\n";
  1092. }
  1093. }
  1094. }
  1095. }
  1096. void MachineVerifier::visitMachineFunctionAfter() {
  1097. calcRegsPassed();
  1098. for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
  1099. MFI != MFE; ++MFI) {
  1100. BBInfo &MInfo = MBBInfoMap[MFI];
  1101. // Skip unreachable MBBs.
  1102. if (!MInfo.reachable)
  1103. continue;
  1104. checkPHIOps(MFI);
  1105. }
  1106. // Now check liveness info if available
  1107. calcRegsRequired();
  1108. // Check for killed virtual registers that should be live out.
  1109. for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
  1110. MFI != MFE; ++MFI) {
  1111. BBInfo &MInfo = MBBInfoMap[MFI];
  1112. for (RegSet::iterator
  1113. I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
  1114. ++I)
  1115. if (MInfo.regsKilled.count(*I)) {
  1116. report("Virtual register killed in block, but needed live out.", MFI);
  1117. *OS << "Virtual register " << PrintReg(*I)
  1118. << " is used after the block.\n";
  1119. }
  1120. }
  1121. if (!MF->empty()) {
  1122. BBInfo &MInfo = MBBInfoMap[&MF->front()];
  1123. for (RegSet::iterator
  1124. I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
  1125. ++I)
  1126. report("Virtual register def doesn't dominate all uses.",
  1127. MRI->getVRegDef(*I));
  1128. }
  1129. if (LiveVars)
  1130. verifyLiveVariables();
  1131. if (LiveInts)
  1132. verifyLiveIntervals();
  1133. }
  1134. void MachineVerifier::verifyLiveVariables() {
  1135. assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
  1136. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  1137. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  1138. LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
  1139. for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
  1140. MFI != MFE; ++MFI) {
  1141. BBInfo &MInfo = MBBInfoMap[MFI];
  1142. // Our vregsRequired should be identical to LiveVariables' AliveBlocks
  1143. if (MInfo.vregsRequired.count(Reg)) {
  1144. if (!VI.AliveBlocks.test(MFI->getNumber())) {
  1145. report("LiveVariables: Block missing from AliveBlocks", MFI);
  1146. *OS << "Virtual register " << PrintReg(Reg)
  1147. << " must be live through the block.\n";
  1148. }
  1149. } else {
  1150. if (VI.AliveBlocks.test(MFI->getNumber())) {
  1151. report("LiveVariables: Block should not be in AliveBlocks", MFI);
  1152. *OS << "Virtual register " << PrintReg(Reg)
  1153. << " is not needed live through the block.\n";
  1154. }
  1155. }
  1156. }
  1157. }
  1158. }
  1159. void MachineVerifier::verifyLiveIntervals() {
  1160. assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
  1161. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  1162. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  1163. // Spilling and splitting may leave unused registers around. Skip them.
  1164. if (MRI->reg_nodbg_empty(Reg))
  1165. continue;
  1166. if (!LiveInts->hasInterval(Reg)) {
  1167. report("Missing live interval for virtual register", MF);
  1168. *OS << PrintReg(Reg, TRI) << " still has defs or uses\n";
  1169. continue;
  1170. }
  1171. const LiveInterval &LI = LiveInts->getInterval(Reg);
  1172. assert(Reg == LI.reg && "Invalid reg to interval mapping");
  1173. verifyLiveInterval(LI);
  1174. }
  1175. // Verify all the cached regunit intervals.
  1176. for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
  1177. if (const LiveInterval *LI = LiveInts->getCachedRegUnit(i))
  1178. verifyLiveInterval(*LI);
  1179. }
  1180. void MachineVerifier::verifyLiveIntervalValue(const LiveInterval &LI,
  1181. VNInfo *VNI) {
  1182. if (VNI->isUnused())
  1183. return;
  1184. const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
  1185. if (!DefVNI) {
  1186. report("Valno not live at def and not marked unused", MF, LI);
  1187. *OS << "Valno #" << VNI->id << '\n';
  1188. return;
  1189. }
  1190. if (DefVNI != VNI) {
  1191. report("Live range at def has different valno", MF, LI);
  1192. *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
  1193. << " where valno #" << DefVNI->id << " is live\n";
  1194. return;
  1195. }
  1196. const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
  1197. if (!MBB) {
  1198. report("Invalid definition index", MF, LI);
  1199. *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
  1200. << " in " << LI << '\n';
  1201. return;
  1202. }
  1203. if (VNI->isPHIDef()) {
  1204. if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
  1205. report("PHIDef value is not defined at MBB start", MBB, LI);
  1206. *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
  1207. << ", not at the beginning of BB#" << MBB->getNumber() << '\n';
  1208. }
  1209. return;
  1210. }
  1211. // Non-PHI def.
  1212. const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
  1213. if (!MI) {
  1214. report("No instruction at def index", MBB, LI);
  1215. *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
  1216. return;
  1217. }
  1218. bool hasDef = false;
  1219. bool isEarlyClobber = false;
  1220. for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
  1221. if (!MOI->isReg() || !MOI->isDef())
  1222. continue;
  1223. if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
  1224. if (MOI->getReg() != LI.reg)
  1225. continue;
  1226. } else {
  1227. if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
  1228. !TRI->hasRegUnit(MOI->getReg(), LI.reg))
  1229. continue;
  1230. }
  1231. hasDef = true;
  1232. if (MOI->isEarlyClobber())
  1233. isEarlyClobber = true;
  1234. }
  1235. if (!hasDef) {
  1236. report("Defining instruction does not modify register", MI);
  1237. *OS << "Valno #" << VNI->id << " in " << LI << '\n';
  1238. }
  1239. // Early clobber defs begin at USE slots, but other defs must begin at
  1240. // DEF slots.
  1241. if (isEarlyClobber) {
  1242. if (!VNI->def.isEarlyClobber()) {
  1243. report("Early clobber def must be at an early-clobber slot", MBB, LI);
  1244. *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
  1245. }
  1246. } else if (!VNI->def.isRegister()) {
  1247. report("Non-PHI, non-early clobber def must be at a register slot",
  1248. MBB, LI);
  1249. *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
  1250. }
  1251. }
  1252. void
  1253. MachineVerifier::verifyLiveIntervalSegment(const LiveInterval &LI,
  1254. LiveInterval::const_iterator I) {
  1255. const VNInfo *VNI = I->valno;
  1256. assert(VNI && "Live range has no valno");
  1257. if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
  1258. report("Foreign valno in live range", MF, LI);
  1259. *OS << *I << " has a bad valno\n";
  1260. }
  1261. if (VNI->isUnused()) {
  1262. report("Live range valno is marked unused", MF, LI);
  1263. *OS << *I << '\n';
  1264. }
  1265. const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
  1266. if (!MBB) {
  1267. report("Bad start of live segment, no basic block", MF, LI);
  1268. *OS << *I << '\n';
  1269. return;
  1270. }
  1271. SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
  1272. if (I->start != MBBStartIdx && I->start != VNI->def) {
  1273. report("Live segment must begin at MBB entry or valno def", MBB, LI);
  1274. *OS << *I << '\n';
  1275. }
  1276. const MachineBasicBlock *EndMBB =
  1277. LiveInts->getMBBFromIndex(I->end.getPrevSlot());
  1278. if (!EndMBB) {
  1279. report("Bad end of live segment, no basic block", MF, LI);
  1280. *OS << *I << '\n';
  1281. return;
  1282. }
  1283. // No more checks for live-out segments.
  1284. if (I->end == LiveInts->getMBBEndIdx(EndMBB))
  1285. return;
  1286. // RegUnit intervals are allowed dead phis.
  1287. if (!TargetRegisterInfo::isVirtualRegister(LI.reg) && VNI->isPHIDef() &&
  1288. I->start == VNI->def && I->end == VNI->def.getDeadSlot())
  1289. return;
  1290. // The live segment is ending inside EndMBB
  1291. const MachineInstr *MI =
  1292. LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
  1293. if (!MI) {
  1294. report("Live segment doesn't end at a valid instruction", EndMBB, LI);
  1295. *OS << *I << '\n';
  1296. return;
  1297. }
  1298. // The block slot must refer to a basic block boundary.
  1299. if (I->end.isBlock()) {
  1300. report("Live segment ends at B slot of an instruction", EndMBB, LI);
  1301. *OS << *I << '\n';
  1302. }
  1303. if (I->end.isDead()) {
  1304. // Segment ends on the dead slot.
  1305. // That means there must be a dead def.
  1306. if (!SlotIndex::isSameInstr(I->start, I->end)) {
  1307. report("Live segment ending at dead slot spans instructions", EndMBB, LI);
  1308. *OS << *I << '\n';
  1309. }
  1310. }
  1311. // A live segment can only end at an early-clobber slot if it is being
  1312. // redefined by an early-clobber def.
  1313. if (I->end.isEarlyClobber()) {
  1314. if (I+1 == LI.end() || (I+1)->start != I->end) {
  1315. report("Live segment ending at early clobber slot must be "
  1316. "redefined by an EC def in the same instruction", EndMBB, LI);
  1317. *OS << *I << '\n';
  1318. }
  1319. }
  1320. // The following checks only apply to virtual registers. Physreg liveness
  1321. // is too weird to check.
  1322. if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
  1323. // A live range can end with either a redefinition, a kill flag on a
  1324. // use, or a dead flag on a def.
  1325. bool hasRead = false;
  1326. bool hasDeadDef = false;
  1327. for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
  1328. if (!MOI->isReg() || MOI->getReg() != LI.reg)
  1329. continue;
  1330. if (MOI->readsReg())
  1331. hasRead = true;
  1332. if (MOI->isDef() && MOI->isDead())
  1333. hasDeadDef = true;
  1334. }
  1335. if (I->end.isDead()) {
  1336. if (!hasDeadDef) {
  1337. report("Instruction doesn't have a dead def operand", MI);
  1338. I->print(*OS);
  1339. *OS << " in " << LI << '\n';
  1340. }
  1341. } else {
  1342. if (!hasRead) {
  1343. report("Instruction ending live range doesn't read the register", MI);
  1344. *OS << *I << " in " << LI << '\n';
  1345. }
  1346. }
  1347. }
  1348. // Now check all the basic blocks in this live segment.
  1349. MachineFunction::const_iterator MFI = MBB;
  1350. // Is this live range the beginning of a non-PHIDef VN?
  1351. if (I->start == VNI->def && !VNI->isPHIDef()) {
  1352. // Not live-in to any blocks.
  1353. if (MBB == EndMBB)
  1354. return;
  1355. // Skip this block.
  1356. ++MFI;
  1357. }
  1358. for (;;) {
  1359. assert(LiveInts->isLiveInToMBB(LI, MFI));
  1360. // We don't know how to track physregs into a landing pad.
  1361. if (!TargetRegisterInfo::isVirtualRegister(LI.reg) &&
  1362. MFI->isLandingPad()) {
  1363. if (&*MFI == EndMBB)
  1364. break;
  1365. ++MFI;
  1366. continue;
  1367. }
  1368. // Is VNI a PHI-def in the current block?
  1369. bool IsPHI = VNI->isPHIDef() &&
  1370. VNI->def == LiveInts->getMBBStartIdx(MFI);
  1371. // Check that VNI is live-out of all predecessors.
  1372. for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
  1373. PE = MFI->pred_end(); PI != PE; ++PI) {
  1374. SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
  1375. const VNInfo *PVNI = LI.getVNInfoBefore(PEnd);
  1376. // All predecessors must have a live-out value.
  1377. if (!PVNI) {
  1378. report("Register not marked live out of predecessor", *PI, LI);
  1379. *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
  1380. << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
  1381. << PEnd << '\n';
  1382. continue;
  1383. }
  1384. // Only PHI-defs can take different predecessor values.
  1385. if (!IsPHI && PVNI != VNI) {
  1386. report("Different value live out of predecessor", *PI, LI);
  1387. *OS << "Valno #" << PVNI->id << " live out of BB#"
  1388. << (*PI)->getNumber() << '@' << PEnd
  1389. << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
  1390. << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
  1391. }
  1392. }
  1393. if (&*MFI == EndMBB)
  1394. break;
  1395. ++MFI;
  1396. }
  1397. }
  1398. void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
  1399. for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
  1400. I!=E; ++I)
  1401. verifyLiveIntervalValue(LI, *I);
  1402. for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I)
  1403. verifyLiveIntervalSegment(LI, I);
  1404. // Check the LI only has one connected component.
  1405. if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
  1406. ConnectedVNInfoEqClasses ConEQ(*LiveInts);
  1407. unsigned NumComp = ConEQ.Classify(&LI);
  1408. if (NumComp > 1) {
  1409. report("Multiple connected components in live interval", MF, LI);
  1410. for (unsigned comp = 0; comp != NumComp; ++comp) {
  1411. *OS << comp << ": valnos";
  1412. for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
  1413. E = LI.vni_end(); I!=E; ++I)
  1414. if (comp == ConEQ.getEqClass(*I))
  1415. *OS << ' ' << (*I)->id;
  1416. *OS << '\n';
  1417. }
  1418. }
  1419. }
  1420. }