MachineVerifier.cpp 48 KB

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