MachineVerifier.cpp 75 KB

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