MachineVerifier.cpp 81 KB

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