MachineVerifier.cpp 62 KB

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