MachineVerifier.cpp 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830
  1. //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Pass to verify generated machine code. The following is checked:
  10. //
  11. // Operand counts: All explicit operands must be present.
  12. //
  13. // Register classes: All physical and virtual register operands must be
  14. // compatible with the register class required by the instruction descriptor.
  15. //
  16. // Register live intervals: Registers must be defined only once, and must be
  17. // defined before use.
  18. //
  19. // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
  20. // command-line option -verify-machineinstrs, or by defining the environment
  21. // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
  22. // the verifier errors.
  23. //===----------------------------------------------------------------------===//
  24. #include "LiveRangeCalc.h"
  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/LiveIntervals.h"
  39. #include "llvm/CodeGen/LiveStacks.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 *FirstNonPHI;
  102. const MachineInstr *FirstTerminator;
  103. BlockSet FunctionBlocks;
  104. BitVector regsReserved;
  105. RegSet regsLive;
  106. RegVector regsDefined, regsDead, regsKilled;
  107. RegMaskVector regMasks;
  108. SlotIndex lastIndex;
  109. // Add Reg and any sub-registers to RV
  110. void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
  111. RV.push_back(Reg);
  112. if (Register::isPhysicalRegister(Reg))
  113. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  114. RV.push_back(*SubRegs);
  115. }
  116. struct BBInfo {
  117. // Is this MBB reachable from the MF entry point?
  118. bool reachable = false;
  119. // Vregs that must be live in because they are used without being
  120. // defined. Map value is the user.
  121. RegMap vregsLiveIn;
  122. // Regs killed in MBB. They may be defined again, and will then be in both
  123. // regsKilled and regsLiveOut.
  124. RegSet regsKilled;
  125. // Regs defined in MBB and live out. Note that vregs passing through may
  126. // be live out without being mentioned here.
  127. RegSet regsLiveOut;
  128. // Vregs that pass through MBB untouched. This set is disjoint from
  129. // regsKilled and regsLiveOut.
  130. RegSet vregsPassed;
  131. // Vregs that must pass through MBB because they are needed by a successor
  132. // block. This set is disjoint from regsLiveOut.
  133. RegSet vregsRequired;
  134. // Set versions of block's predecessor and successor lists.
  135. BlockSet Preds, Succs;
  136. BBInfo() = default;
  137. // Add register to vregsPassed if it belongs there. Return true if
  138. // anything changed.
  139. bool addPassed(unsigned Reg) {
  140. if (!Register::isVirtualRegister(Reg))
  141. return false;
  142. if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
  143. return false;
  144. return vregsPassed.insert(Reg).second;
  145. }
  146. // Same for a full set.
  147. bool addPassed(const RegSet &RS) {
  148. bool changed = false;
  149. for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
  150. if (addPassed(*I))
  151. changed = true;
  152. return changed;
  153. }
  154. // Add register to vregsRequired if it belongs there. Return true if
  155. // anything changed.
  156. bool addRequired(unsigned Reg) {
  157. if (!Register::isVirtualRegister(Reg))
  158. return false;
  159. if (regsLiveOut.count(Reg))
  160. return false;
  161. return vregsRequired.insert(Reg).second;
  162. }
  163. // Same for a full set.
  164. bool addRequired(const RegSet &RS) {
  165. bool changed = false;
  166. for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
  167. if (addRequired(*I))
  168. changed = true;
  169. return changed;
  170. }
  171. // Same for a full map.
  172. bool addRequired(const RegMap &RM) {
  173. bool changed = false;
  174. for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
  175. if (addRequired(I->first))
  176. changed = true;
  177. return changed;
  178. }
  179. // Live-out registers are either in regsLiveOut or vregsPassed.
  180. bool isLiveOut(unsigned Reg) const {
  181. return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
  182. }
  183. };
  184. // Extra register info per MBB.
  185. DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
  186. bool isReserved(unsigned Reg) {
  187. return Reg < regsReserved.size() && regsReserved.test(Reg);
  188. }
  189. bool isAllocatable(unsigned Reg) const {
  190. return Reg < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
  191. !regsReserved.test(Reg);
  192. }
  193. // Analysis information if available
  194. LiveVariables *LiveVars;
  195. LiveIntervals *LiveInts;
  196. LiveStacks *LiveStks;
  197. SlotIndexes *Indexes;
  198. void visitMachineFunctionBefore();
  199. void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
  200. void visitMachineBundleBefore(const MachineInstr *MI);
  201. bool verifyVectorElementMatch(LLT Ty0, LLT Ty1, const MachineInstr *MI);
  202. void verifyPreISelGenericInstruction(const MachineInstr *MI);
  203. void visitMachineInstrBefore(const MachineInstr *MI);
  204. void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
  205. void visitMachineInstrAfter(const MachineInstr *MI);
  206. void visitMachineBundleAfter(const MachineInstr *MI);
  207. void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
  208. void visitMachineFunctionAfter();
  209. void report(const char *msg, const MachineFunction *MF);
  210. void report(const char *msg, const MachineBasicBlock *MBB);
  211. void report(const char *msg, const MachineInstr *MI);
  212. void report(const char *msg, const MachineOperand *MO, unsigned MONum,
  213. LLT MOVRegType = LLT{});
  214. void report_context(const LiveInterval &LI) const;
  215. void report_context(const LiveRange &LR, unsigned VRegUnit,
  216. LaneBitmask LaneMask) const;
  217. void report_context(const LiveRange::Segment &S) const;
  218. void report_context(const VNInfo &VNI) const;
  219. void report_context(SlotIndex Pos) const;
  220. void report_context(MCPhysReg PhysReg) const;
  221. void report_context_liverange(const LiveRange &LR) const;
  222. void report_context_lanemask(LaneBitmask LaneMask) const;
  223. void report_context_vreg(unsigned VReg) const;
  224. void report_context_vreg_regunit(unsigned VRegOrUnit) const;
  225. void verifyInlineAsm(const MachineInstr *MI);
  226. void checkLiveness(const MachineOperand *MO, unsigned MONum);
  227. void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
  228. SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
  229. LaneBitmask LaneMask = LaneBitmask::getNone());
  230. void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
  231. SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
  232. bool SubRangeCheck = false,
  233. LaneBitmask LaneMask = LaneBitmask::getNone());
  234. void markReachable(const MachineBasicBlock *MBB);
  235. void calcRegsPassed();
  236. void checkPHIOps(const MachineBasicBlock &MBB);
  237. void calcRegsRequired();
  238. void verifyLiveVariables();
  239. void verifyLiveIntervals();
  240. void verifyLiveInterval(const LiveInterval&);
  241. void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned,
  242. LaneBitmask);
  243. void verifyLiveRangeSegment(const LiveRange&,
  244. const LiveRange::const_iterator I, unsigned,
  245. LaneBitmask);
  246. void verifyLiveRange(const LiveRange&, unsigned,
  247. LaneBitmask LaneMask = LaneBitmask::getNone());
  248. void verifyStackFrame();
  249. void verifySlotIndexes() const;
  250. void verifyProperties(const MachineFunction &MF);
  251. };
  252. struct MachineVerifierPass : public MachineFunctionPass {
  253. static char ID; // Pass ID, replacement for typeid
  254. const std::string Banner;
  255. MachineVerifierPass(std::string banner = std::string())
  256. : MachineFunctionPass(ID), Banner(std::move(banner)) {
  257. initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
  258. }
  259. void getAnalysisUsage(AnalysisUsage &AU) const override {
  260. AU.setPreservesAll();
  261. MachineFunctionPass::getAnalysisUsage(AU);
  262. }
  263. bool runOnMachineFunction(MachineFunction &MF) override {
  264. unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF);
  265. if (FoundErrors)
  266. report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
  267. return false;
  268. }
  269. };
  270. } // end anonymous namespace
  271. char MachineVerifierPass::ID = 0;
  272. INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
  273. "Verify generated machine code", false, false)
  274. FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
  275. return new MachineVerifierPass(Banner);
  276. }
  277. bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors)
  278. const {
  279. MachineFunction &MF = const_cast<MachineFunction&>(*this);
  280. unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF);
  281. if (AbortOnErrors && FoundErrors)
  282. report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
  283. return FoundErrors == 0;
  284. }
  285. void MachineVerifier::verifySlotIndexes() const {
  286. if (Indexes == nullptr)
  287. return;
  288. // Ensure the IdxMBB list is sorted by slot indexes.
  289. SlotIndex Last;
  290. for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
  291. E = Indexes->MBBIndexEnd(); I != E; ++I) {
  292. assert(!Last.isValid() || I->first > Last);
  293. Last = I->first;
  294. }
  295. }
  296. void MachineVerifier::verifyProperties(const MachineFunction &MF) {
  297. // If a pass has introduced virtual registers without clearing the
  298. // NoVRegs property (or set it without allocating the vregs)
  299. // then report an error.
  300. if (MF.getProperties().hasProperty(
  301. MachineFunctionProperties::Property::NoVRegs) &&
  302. MRI->getNumVirtRegs())
  303. report("Function has NoVRegs property but there are VReg operands", &MF);
  304. }
  305. unsigned MachineVerifier::verify(MachineFunction &MF) {
  306. foundErrors = 0;
  307. this->MF = &MF;
  308. TM = &MF.getTarget();
  309. TII = MF.getSubtarget().getInstrInfo();
  310. TRI = MF.getSubtarget().getRegisterInfo();
  311. MRI = &MF.getRegInfo();
  312. const bool isFunctionFailedISel = MF.getProperties().hasProperty(
  313. MachineFunctionProperties::Property::FailedISel);
  314. // If we're mid-GlobalISel and we already triggered the fallback path then
  315. // it's expected that the MIR is somewhat broken but that's ok since we'll
  316. // reset it and clear the FailedISel attribute in ResetMachineFunctions.
  317. if (isFunctionFailedISel)
  318. return foundErrors;
  319. isFunctionRegBankSelected =
  320. !isFunctionFailedISel &&
  321. MF.getProperties().hasProperty(
  322. MachineFunctionProperties::Property::RegBankSelected);
  323. isFunctionSelected = !isFunctionFailedISel &&
  324. MF.getProperties().hasProperty(
  325. MachineFunctionProperties::Property::Selected);
  326. LiveVars = nullptr;
  327. LiveInts = nullptr;
  328. LiveStks = nullptr;
  329. Indexes = nullptr;
  330. if (PASS) {
  331. LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
  332. // We don't want to verify LiveVariables if LiveIntervals is available.
  333. if (!LiveInts)
  334. LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
  335. LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
  336. Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
  337. }
  338. verifySlotIndexes();
  339. verifyProperties(MF);
  340. visitMachineFunctionBefore();
  341. for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
  342. MFI!=MFE; ++MFI) {
  343. visitMachineBasicBlockBefore(&*MFI);
  344. // Keep track of the current bundle header.
  345. const MachineInstr *CurBundle = nullptr;
  346. // Do we expect the next instruction to be part of the same bundle?
  347. bool InBundle = false;
  348. for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
  349. MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
  350. if (MBBI->getParent() != &*MFI) {
  351. report("Bad instruction parent pointer", &*MFI);
  352. errs() << "Instruction: " << *MBBI;
  353. continue;
  354. }
  355. // Check for consistent bundle flags.
  356. if (InBundle && !MBBI->isBundledWithPred())
  357. report("Missing BundledPred flag, "
  358. "BundledSucc was set on predecessor",
  359. &*MBBI);
  360. if (!InBundle && MBBI->isBundledWithPred())
  361. report("BundledPred flag is set, "
  362. "but BundledSucc not set on predecessor",
  363. &*MBBI);
  364. // Is this a bundle header?
  365. if (!MBBI->isInsideBundle()) {
  366. if (CurBundle)
  367. visitMachineBundleAfter(CurBundle);
  368. CurBundle = &*MBBI;
  369. visitMachineBundleBefore(CurBundle);
  370. } else if (!CurBundle)
  371. report("No bundle header", &*MBBI);
  372. visitMachineInstrBefore(&*MBBI);
  373. for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
  374. const MachineInstr &MI = *MBBI;
  375. const MachineOperand &Op = MI.getOperand(I);
  376. if (Op.getParent() != &MI) {
  377. // Make sure to use correct addOperand / RemoveOperand / ChangeTo
  378. // functions when replacing operands of a MachineInstr.
  379. report("Instruction has operand with wrong parent set", &MI);
  380. }
  381. visitMachineOperand(&Op, I);
  382. }
  383. visitMachineInstrAfter(&*MBBI);
  384. // Was this the last bundled instruction?
  385. InBundle = MBBI->isBundledWithSucc();
  386. }
  387. if (CurBundle)
  388. visitMachineBundleAfter(CurBundle);
  389. if (InBundle)
  390. report("BundledSucc flag set on last instruction in block", &MFI->back());
  391. visitMachineBasicBlockAfter(&*MFI);
  392. }
  393. visitMachineFunctionAfter();
  394. // Clean up.
  395. regsLive.clear();
  396. regsDefined.clear();
  397. regsDead.clear();
  398. regsKilled.clear();
  399. regMasks.clear();
  400. MBBInfoMap.clear();
  401. return foundErrors;
  402. }
  403. void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
  404. assert(MF);
  405. errs() << '\n';
  406. if (!foundErrors++) {
  407. if (Banner)
  408. errs() << "# " << Banner << '\n';
  409. if (LiveInts != nullptr)
  410. LiveInts->print(errs());
  411. else
  412. MF->print(errs(), Indexes);
  413. }
  414. errs() << "*** Bad machine code: " << msg << " ***\n"
  415. << "- function: " << MF->getName() << "\n";
  416. }
  417. void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
  418. assert(MBB);
  419. report(msg, MBB->getParent());
  420. errs() << "- basic block: " << printMBBReference(*MBB) << ' '
  421. << MBB->getName() << " (" << (const void *)MBB << ')';
  422. if (Indexes)
  423. errs() << " [" << Indexes->getMBBStartIdx(MBB)
  424. << ';' << Indexes->getMBBEndIdx(MBB) << ')';
  425. errs() << '\n';
  426. }
  427. void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
  428. assert(MI);
  429. report(msg, MI->getParent());
  430. errs() << "- instruction: ";
  431. if (Indexes && Indexes->hasIndex(*MI))
  432. errs() << Indexes->getInstructionIndex(*MI) << '\t';
  433. MI->print(errs(), /*SkipOpers=*/true);
  434. }
  435. void MachineVerifier::report(const char *msg, const MachineOperand *MO,
  436. unsigned MONum, LLT MOVRegType) {
  437. assert(MO);
  438. report(msg, MO->getParent());
  439. errs() << "- operand " << MONum << ": ";
  440. MO->print(errs(), MOVRegType, TRI);
  441. errs() << "\n";
  442. }
  443. void MachineVerifier::report_context(SlotIndex Pos) const {
  444. errs() << "- at: " << Pos << '\n';
  445. }
  446. void MachineVerifier::report_context(const LiveInterval &LI) const {
  447. errs() << "- interval: " << LI << '\n';
  448. }
  449. void MachineVerifier::report_context(const LiveRange &LR, unsigned VRegUnit,
  450. LaneBitmask LaneMask) const {
  451. report_context_liverange(LR);
  452. report_context_vreg_regunit(VRegUnit);
  453. if (LaneMask.any())
  454. report_context_lanemask(LaneMask);
  455. }
  456. void MachineVerifier::report_context(const LiveRange::Segment &S) const {
  457. errs() << "- segment: " << S << '\n';
  458. }
  459. void MachineVerifier::report_context(const VNInfo &VNI) const {
  460. errs() << "- ValNo: " << VNI.id << " (def " << VNI.def << ")\n";
  461. }
  462. void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
  463. errs() << "- liverange: " << LR << '\n';
  464. }
  465. void MachineVerifier::report_context(MCPhysReg PReg) const {
  466. errs() << "- p. register: " << printReg(PReg, TRI) << '\n';
  467. }
  468. void MachineVerifier::report_context_vreg(unsigned VReg) const {
  469. errs() << "- v. register: " << printReg(VReg, TRI) << '\n';
  470. }
  471. void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit) const {
  472. if (Register::isVirtualRegister(VRegOrUnit)) {
  473. report_context_vreg(VRegOrUnit);
  474. } else {
  475. errs() << "- regunit: " << printRegUnit(VRegOrUnit, TRI) << '\n';
  476. }
  477. }
  478. void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
  479. errs() << "- lanemask: " << PrintLaneMask(LaneMask) << '\n';
  480. }
  481. void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
  482. BBInfo &MInfo = MBBInfoMap[MBB];
  483. if (!MInfo.reachable) {
  484. MInfo.reachable = true;
  485. for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
  486. SuE = MBB->succ_end(); SuI != SuE; ++SuI)
  487. markReachable(*SuI);
  488. }
  489. }
  490. void MachineVerifier::visitMachineFunctionBefore() {
  491. lastIndex = SlotIndex();
  492. regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
  493. : TRI->getReservedRegs(*MF);
  494. if (!MF->empty())
  495. markReachable(&MF->front());
  496. // Build a set of the basic blocks in the function.
  497. FunctionBlocks.clear();
  498. for (const auto &MBB : *MF) {
  499. FunctionBlocks.insert(&MBB);
  500. BBInfo &MInfo = MBBInfoMap[&MBB];
  501. MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
  502. if (MInfo.Preds.size() != MBB.pred_size())
  503. report("MBB has duplicate entries in its predecessor list.", &MBB);
  504. MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
  505. if (MInfo.Succs.size() != MBB.succ_size())
  506. report("MBB has duplicate entries in its successor list.", &MBB);
  507. }
  508. // Check that the register use lists are sane.
  509. MRI->verifyUseLists();
  510. if (!MF->empty())
  511. verifyStackFrame();
  512. }
  513. // Does iterator point to a and b as the first two elements?
  514. static bool matchPair(MachineBasicBlock::const_succ_iterator i,
  515. const MachineBasicBlock *a, const MachineBasicBlock *b) {
  516. if (*i == a)
  517. return *++i == b;
  518. if (*i == b)
  519. return *++i == a;
  520. return false;
  521. }
  522. void
  523. MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
  524. FirstTerminator = nullptr;
  525. FirstNonPHI = nullptr;
  526. if (!MF->getProperties().hasProperty(
  527. MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) {
  528. // If this block has allocatable physical registers live-in, check that
  529. // it is an entry block or landing pad.
  530. for (const auto &LI : MBB->liveins()) {
  531. if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
  532. MBB->getIterator() != MBB->getParent()->begin()) {
  533. report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB);
  534. report_context(LI.PhysReg);
  535. }
  536. }
  537. }
  538. // Count the number of landing pad successors.
  539. SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
  540. for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
  541. E = MBB->succ_end(); I != E; ++I) {
  542. if ((*I)->isEHPad())
  543. LandingPadSuccs.insert(*I);
  544. if (!FunctionBlocks.count(*I))
  545. report("MBB has successor that isn't part of the function.", MBB);
  546. if (!MBBInfoMap[*I].Preds.count(MBB)) {
  547. report("Inconsistent CFG", MBB);
  548. errs() << "MBB is not in the predecessor list of the successor "
  549. << printMBBReference(*(*I)) << ".\n";
  550. }
  551. }
  552. // Check the predecessor list.
  553. for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
  554. E = MBB->pred_end(); I != E; ++I) {
  555. if (!FunctionBlocks.count(*I))
  556. report("MBB has predecessor that isn't part of the function.", MBB);
  557. if (!MBBInfoMap[*I].Succs.count(MBB)) {
  558. report("Inconsistent CFG", MBB);
  559. errs() << "MBB is not in the successor list of the predecessor "
  560. << printMBBReference(*(*I)) << ".\n";
  561. }
  562. }
  563. const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
  564. const BasicBlock *BB = MBB->getBasicBlock();
  565. const Function &F = MF->getFunction();
  566. if (LandingPadSuccs.size() > 1 &&
  567. !(AsmInfo &&
  568. AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
  569. BB && isa<SwitchInst>(BB->getTerminator())) &&
  570. !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
  571. report("MBB has more than one landing pad successor", MBB);
  572. // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
  573. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  574. SmallVector<MachineOperand, 4> Cond;
  575. if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB,
  576. Cond)) {
  577. // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
  578. // check whether its answers match up with reality.
  579. if (!TBB && !FBB) {
  580. // Block falls through to its successor.
  581. MachineFunction::const_iterator MBBI = MBB->getIterator();
  582. ++MBBI;
  583. if (MBBI == MF->end()) {
  584. // It's possible that the block legitimately ends with a noreturn
  585. // call or an unreachable, in which case it won't actually fall
  586. // out the bottom of the function.
  587. } else if (MBB->succ_size() == LandingPadSuccs.size()) {
  588. // It's possible that the block legitimately ends with a noreturn
  589. // call or an unreachable, in which case it won't actually fall
  590. // out of the block.
  591. } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
  592. report("MBB exits via unconditional fall-through but doesn't have "
  593. "exactly one CFG successor!", MBB);
  594. } else if (!MBB->isSuccessor(&*MBBI)) {
  595. report("MBB exits via unconditional fall-through but its successor "
  596. "differs from its CFG successor!", MBB);
  597. }
  598. if (!MBB->empty() && MBB->back().isBarrier() &&
  599. !TII->isPredicated(MBB->back())) {
  600. report("MBB exits via unconditional fall-through but ends with a "
  601. "barrier instruction!", MBB);
  602. }
  603. if (!Cond.empty()) {
  604. report("MBB exits via unconditional fall-through but has a condition!",
  605. MBB);
  606. }
  607. } else if (TBB && !FBB && Cond.empty()) {
  608. // Block unconditionally branches somewhere.
  609. // If the block has exactly one successor, that happens to be a
  610. // landingpad, accept it as valid control flow.
  611. if (MBB->succ_size() != 1+LandingPadSuccs.size() &&
  612. (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 ||
  613. *MBB->succ_begin() != *LandingPadSuccs.begin())) {
  614. report("MBB exits via unconditional branch but doesn't have "
  615. "exactly one CFG successor!", MBB);
  616. } else if (!MBB->isSuccessor(TBB)) {
  617. report("MBB exits via unconditional branch but the CFG "
  618. "successor doesn't match the actual successor!", MBB);
  619. }
  620. if (MBB->empty()) {
  621. report("MBB exits via unconditional branch but doesn't contain "
  622. "any instructions!", MBB);
  623. } else if (!MBB->back().isBarrier()) {
  624. report("MBB exits via unconditional branch but doesn't end with a "
  625. "barrier instruction!", MBB);
  626. } else if (!MBB->back().isTerminator()) {
  627. report("MBB exits via unconditional branch but the branch isn't a "
  628. "terminator instruction!", MBB);
  629. }
  630. } else if (TBB && !FBB && !Cond.empty()) {
  631. // Block conditionally branches somewhere, otherwise falls through.
  632. MachineFunction::const_iterator MBBI = MBB->getIterator();
  633. ++MBBI;
  634. if (MBBI == MF->end()) {
  635. report("MBB conditionally falls through out of function!", MBB);
  636. } else if (MBB->succ_size() == 1) {
  637. // A conditional branch with only one successor is weird, but allowed.
  638. if (&*MBBI != TBB)
  639. report("MBB exits via conditional branch/fall-through but only has "
  640. "one CFG successor!", MBB);
  641. else if (TBB != *MBB->succ_begin())
  642. report("MBB exits via conditional branch/fall-through but the CFG "
  643. "successor don't match the actual successor!", MBB);
  644. } else if (MBB->succ_size() != 2) {
  645. report("MBB exits via conditional branch/fall-through but doesn't have "
  646. "exactly two CFG successors!", MBB);
  647. } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
  648. report("MBB exits via conditional branch/fall-through but the CFG "
  649. "successors don't match the actual successors!", MBB);
  650. }
  651. if (MBB->empty()) {
  652. report("MBB exits via conditional branch/fall-through but doesn't "
  653. "contain any instructions!", MBB);
  654. } else if (MBB->back().isBarrier()) {
  655. report("MBB exits via conditional branch/fall-through but ends with a "
  656. "barrier instruction!", MBB);
  657. } else if (!MBB->back().isTerminator()) {
  658. report("MBB exits via conditional branch/fall-through but the branch "
  659. "isn't a terminator instruction!", MBB);
  660. }
  661. } else if (TBB && FBB) {
  662. // Block conditionally branches somewhere, otherwise branches
  663. // somewhere else.
  664. if (MBB->succ_size() == 1) {
  665. // A conditional branch with only one successor is weird, but allowed.
  666. if (FBB != TBB)
  667. report("MBB exits via conditional branch/branch through but only has "
  668. "one CFG successor!", MBB);
  669. else if (TBB != *MBB->succ_begin())
  670. report("MBB exits via conditional branch/branch through but the CFG "
  671. "successor don't match the actual successor!", MBB);
  672. } else if (MBB->succ_size() != 2) {
  673. report("MBB exits via conditional branch/branch but doesn't have "
  674. "exactly two CFG successors!", MBB);
  675. } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
  676. report("MBB exits via conditional branch/branch but the CFG "
  677. "successors don't match the actual successors!", MBB);
  678. }
  679. if (MBB->empty()) {
  680. report("MBB exits via conditional branch/branch but doesn't "
  681. "contain any instructions!", MBB);
  682. } else if (!MBB->back().isBarrier()) {
  683. report("MBB exits via conditional branch/branch but doesn't end with a "
  684. "barrier instruction!", MBB);
  685. } else if (!MBB->back().isTerminator()) {
  686. report("MBB exits via conditional branch/branch but the branch "
  687. "isn't a terminator instruction!", MBB);
  688. }
  689. if (Cond.empty()) {
  690. report("MBB exits via conditional branch/branch but there's no "
  691. "condition!", MBB);
  692. }
  693. } else {
  694. report("AnalyzeBranch returned invalid data!", MBB);
  695. }
  696. }
  697. regsLive.clear();
  698. if (MRI->tracksLiveness()) {
  699. for (const auto &LI : MBB->liveins()) {
  700. if (!Register::isPhysicalRegister(LI.PhysReg)) {
  701. report("MBB live-in list contains non-physical register", MBB);
  702. continue;
  703. }
  704. for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
  705. SubRegs.isValid(); ++SubRegs)
  706. regsLive.insert(*SubRegs);
  707. }
  708. }
  709. const MachineFrameInfo &MFI = MF->getFrameInfo();
  710. BitVector PR = MFI.getPristineRegs(*MF);
  711. for (unsigned I : PR.set_bits()) {
  712. for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
  713. SubRegs.isValid(); ++SubRegs)
  714. regsLive.insert(*SubRegs);
  715. }
  716. regsKilled.clear();
  717. regsDefined.clear();
  718. if (Indexes)
  719. lastIndex = Indexes->getMBBStartIdx(MBB);
  720. }
  721. // This function gets called for all bundle headers, including normal
  722. // stand-alone unbundled instructions.
  723. void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
  724. if (Indexes && Indexes->hasIndex(*MI)) {
  725. SlotIndex idx = Indexes->getInstructionIndex(*MI);
  726. if (!(idx > lastIndex)) {
  727. report("Instruction index out of order", MI);
  728. errs() << "Last instruction was at " << lastIndex << '\n';
  729. }
  730. lastIndex = idx;
  731. }
  732. // Ensure non-terminators don't follow terminators.
  733. // Ignore predicated terminators formed by if conversion.
  734. // FIXME: If conversion shouldn't need to violate this rule.
  735. if (MI->isTerminator() && !TII->isPredicated(*MI)) {
  736. if (!FirstTerminator)
  737. FirstTerminator = MI;
  738. } else if (FirstTerminator && !MI->isDebugEntryValue()) {
  739. report("Non-terminator instruction after the first terminator", MI);
  740. errs() << "First terminator was:\t" << *FirstTerminator;
  741. }
  742. }
  743. // The operands on an INLINEASM instruction must follow a template.
  744. // Verify that the flag operands make sense.
  745. void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
  746. // The first two operands on INLINEASM are the asm string and global flags.
  747. if (MI->getNumOperands() < 2) {
  748. report("Too few operands on inline asm", MI);
  749. return;
  750. }
  751. if (!MI->getOperand(0).isSymbol())
  752. report("Asm string must be an external symbol", MI);
  753. if (!MI->getOperand(1).isImm())
  754. report("Asm flags must be an immediate", MI);
  755. // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
  756. // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
  757. // and Extra_IsConvergent = 32.
  758. if (!isUInt<6>(MI->getOperand(1).getImm()))
  759. report("Unknown asm flags", &MI->getOperand(1), 1);
  760. static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
  761. unsigned OpNo = InlineAsm::MIOp_FirstOperand;
  762. unsigned NumOps;
  763. for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
  764. const MachineOperand &MO = MI->getOperand(OpNo);
  765. // There may be implicit ops after the fixed operands.
  766. if (!MO.isImm())
  767. break;
  768. NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
  769. }
  770. if (OpNo > MI->getNumOperands())
  771. report("Missing operands in last group", MI);
  772. // An optional MDNode follows the groups.
  773. if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
  774. ++OpNo;
  775. // All trailing operands must be implicit registers.
  776. for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
  777. const MachineOperand &MO = MI->getOperand(OpNo);
  778. if (!MO.isReg() || !MO.isImplicit())
  779. report("Expected implicit register after groups", &MO, OpNo);
  780. }
  781. }
  782. /// Check that types are consistent when two operands need to have the same
  783. /// number of vector elements.
  784. /// \return true if the types are valid.
  785. bool MachineVerifier::verifyVectorElementMatch(LLT Ty0, LLT Ty1,
  786. const MachineInstr *MI) {
  787. if (Ty0.isVector() != Ty1.isVector()) {
  788. report("operand types must be all-vector or all-scalar", MI);
  789. // Generally we try to report as many issues as possible at once, but in
  790. // this case it's not clear what should we be comparing the size of the
  791. // scalar with: the size of the whole vector or its lane. Instead of
  792. // making an arbitrary choice and emitting not so helpful message, let's
  793. // avoid the extra noise and stop here.
  794. return false;
  795. }
  796. if (Ty0.isVector() && Ty0.getNumElements() != Ty1.getNumElements()) {
  797. report("operand types must preserve number of vector elements", MI);
  798. return false;
  799. }
  800. return true;
  801. }
  802. void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr *MI) {
  803. if (isFunctionSelected)
  804. report("Unexpected generic instruction in a Selected function", MI);
  805. const MCInstrDesc &MCID = MI->getDesc();
  806. unsigned NumOps = MI->getNumOperands();
  807. // Check types.
  808. SmallVector<LLT, 4> Types;
  809. for (unsigned I = 0, E = std::min(MCID.getNumOperands(), NumOps);
  810. I != E; ++I) {
  811. if (!MCID.OpInfo[I].isGenericType())
  812. continue;
  813. // Generic instructions specify type equality constraints between some of
  814. // their operands. Make sure these are consistent.
  815. size_t TypeIdx = MCID.OpInfo[I].getGenericTypeIndex();
  816. Types.resize(std::max(TypeIdx + 1, Types.size()));
  817. const MachineOperand *MO = &MI->getOperand(I);
  818. if (!MO->isReg()) {
  819. report("generic instruction must use register operands", MI);
  820. continue;
  821. }
  822. LLT OpTy = MRI->getType(MO->getReg());
  823. // Don't report a type mismatch if there is no actual mismatch, only a
  824. // type missing, to reduce noise:
  825. if (OpTy.isValid()) {
  826. // Only the first valid type for a type index will be printed: don't
  827. // overwrite it later so it's always clear which type was expected:
  828. if (!Types[TypeIdx].isValid())
  829. Types[TypeIdx] = OpTy;
  830. else if (Types[TypeIdx] != OpTy)
  831. report("Type mismatch in generic instruction", MO, I, OpTy);
  832. } else {
  833. // Generic instructions must have types attached to their operands.
  834. report("Generic instruction is missing a virtual register type", MO, I);
  835. }
  836. }
  837. // Generic opcodes must not have physical register operands.
  838. for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
  839. const MachineOperand *MO = &MI->getOperand(I);
  840. if (MO->isReg() && Register::isPhysicalRegister(MO->getReg()))
  841. report("Generic instruction cannot have physical register", MO, I);
  842. }
  843. // Avoid out of bounds in checks below. This was already reported earlier.
  844. if (MI->getNumOperands() < MCID.getNumOperands())
  845. return;
  846. StringRef ErrorInfo;
  847. if (!TII->verifyInstruction(*MI, ErrorInfo))
  848. report(ErrorInfo.data(), MI);
  849. // Verify properties of various specific instruction types
  850. switch (MI->getOpcode()) {
  851. case TargetOpcode::G_CONSTANT:
  852. case TargetOpcode::G_FCONSTANT: {
  853. if (MI->getNumOperands() < MCID.getNumOperands())
  854. break;
  855. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  856. if (DstTy.isVector())
  857. report("Instruction cannot use a vector result type", MI);
  858. if (MI->getOpcode() == TargetOpcode::G_CONSTANT) {
  859. if (!MI->getOperand(1).isCImm()) {
  860. report("G_CONSTANT operand must be cimm", MI);
  861. break;
  862. }
  863. const ConstantInt *CI = MI->getOperand(1).getCImm();
  864. if (CI->getBitWidth() != DstTy.getSizeInBits())
  865. report("inconsistent constant size", MI);
  866. } else {
  867. if (!MI->getOperand(1).isFPImm()) {
  868. report("G_FCONSTANT operand must be fpimm", MI);
  869. break;
  870. }
  871. const ConstantFP *CF = MI->getOperand(1).getFPImm();
  872. if (APFloat::getSizeInBits(CF->getValueAPF().getSemantics()) !=
  873. DstTy.getSizeInBits()) {
  874. report("inconsistent constant size", MI);
  875. }
  876. }
  877. break;
  878. }
  879. case TargetOpcode::G_LOAD:
  880. case TargetOpcode::G_STORE:
  881. case TargetOpcode::G_ZEXTLOAD:
  882. case TargetOpcode::G_SEXTLOAD: {
  883. LLT ValTy = MRI->getType(MI->getOperand(0).getReg());
  884. LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
  885. if (!PtrTy.isPointer())
  886. report("Generic memory instruction must access a pointer", MI);
  887. // Generic loads and stores must have a single MachineMemOperand
  888. // describing that access.
  889. if (!MI->hasOneMemOperand()) {
  890. report("Generic instruction accessing memory must have one mem operand",
  891. MI);
  892. } else {
  893. const MachineMemOperand &MMO = **MI->memoperands_begin();
  894. if (MI->getOpcode() == TargetOpcode::G_ZEXTLOAD ||
  895. MI->getOpcode() == TargetOpcode::G_SEXTLOAD) {
  896. if (MMO.getSizeInBits() >= ValTy.getSizeInBits())
  897. report("Generic extload must have a narrower memory type", MI);
  898. } else if (MI->getOpcode() == TargetOpcode::G_LOAD) {
  899. if (MMO.getSize() > ValTy.getSizeInBytes())
  900. report("load memory size cannot exceed result size", MI);
  901. } else if (MI->getOpcode() == TargetOpcode::G_STORE) {
  902. if (ValTy.getSizeInBytes() < MMO.getSize())
  903. report("store memory size cannot exceed value size", MI);
  904. }
  905. }
  906. break;
  907. }
  908. case TargetOpcode::G_PHI: {
  909. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  910. if (!DstTy.isValid() ||
  911. !std::all_of(MI->operands_begin() + 1, MI->operands_end(),
  912. [this, &DstTy](const MachineOperand &MO) {
  913. if (!MO.isReg())
  914. return true;
  915. LLT Ty = MRI->getType(MO.getReg());
  916. if (!Ty.isValid() || (Ty != DstTy))
  917. return false;
  918. return true;
  919. }))
  920. report("Generic Instruction G_PHI has operands with incompatible/missing "
  921. "types",
  922. MI);
  923. break;
  924. }
  925. case TargetOpcode::G_BITCAST: {
  926. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  927. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  928. if (!DstTy.isValid() || !SrcTy.isValid())
  929. break;
  930. if (SrcTy.isPointer() != DstTy.isPointer())
  931. report("bitcast cannot convert between pointers and other types", MI);
  932. if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
  933. report("bitcast sizes must match", MI);
  934. break;
  935. }
  936. case TargetOpcode::G_INTTOPTR:
  937. case TargetOpcode::G_PTRTOINT:
  938. case TargetOpcode::G_ADDRSPACE_CAST: {
  939. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  940. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  941. if (!DstTy.isValid() || !SrcTy.isValid())
  942. break;
  943. verifyVectorElementMatch(DstTy, SrcTy, MI);
  944. DstTy = DstTy.getScalarType();
  945. SrcTy = SrcTy.getScalarType();
  946. if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) {
  947. if (!DstTy.isPointer())
  948. report("inttoptr result type must be a pointer", MI);
  949. if (SrcTy.isPointer())
  950. report("inttoptr source type must not be a pointer", MI);
  951. } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) {
  952. if (!SrcTy.isPointer())
  953. report("ptrtoint source type must be a pointer", MI);
  954. if (DstTy.isPointer())
  955. report("ptrtoint result type must not be a pointer", MI);
  956. } else {
  957. assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST);
  958. if (!SrcTy.isPointer() || !DstTy.isPointer())
  959. report("addrspacecast types must be pointers", MI);
  960. else {
  961. if (SrcTy.getAddressSpace() == DstTy.getAddressSpace())
  962. report("addrspacecast must convert different address spaces", MI);
  963. }
  964. }
  965. break;
  966. }
  967. case TargetOpcode::G_GEP: {
  968. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  969. LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
  970. LLT OffsetTy = MRI->getType(MI->getOperand(2).getReg());
  971. if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid())
  972. break;
  973. if (!PtrTy.getScalarType().isPointer())
  974. report("gep first operand must be a pointer", MI);
  975. if (OffsetTy.getScalarType().isPointer())
  976. report("gep offset operand must not be a pointer", MI);
  977. // TODO: Is the offset allowed to be a scalar with a vector?
  978. break;
  979. }
  980. case TargetOpcode::G_SEXT:
  981. case TargetOpcode::G_ZEXT:
  982. case TargetOpcode::G_ANYEXT:
  983. case TargetOpcode::G_TRUNC:
  984. case TargetOpcode::G_FPEXT:
  985. case TargetOpcode::G_FPTRUNC: {
  986. // Number of operands and presense of types is already checked (and
  987. // reported in case of any issues), so no need to report them again. As
  988. // we're trying to report as many issues as possible at once, however, the
  989. // instructions aren't guaranteed to have the right number of operands or
  990. // types attached to them at this point
  991. assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
  992. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  993. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  994. if (!DstTy.isValid() || !SrcTy.isValid())
  995. break;
  996. LLT DstElTy = DstTy.getScalarType();
  997. LLT SrcElTy = SrcTy.getScalarType();
  998. if (DstElTy.isPointer() || SrcElTy.isPointer())
  999. report("Generic extend/truncate can not operate on pointers", MI);
  1000. verifyVectorElementMatch(DstTy, SrcTy, MI);
  1001. unsigned DstSize = DstElTy.getSizeInBits();
  1002. unsigned SrcSize = SrcElTy.getSizeInBits();
  1003. switch (MI->getOpcode()) {
  1004. default:
  1005. if (DstSize <= SrcSize)
  1006. report("Generic extend has destination type no larger than source", MI);
  1007. break;
  1008. case TargetOpcode::G_TRUNC:
  1009. case TargetOpcode::G_FPTRUNC:
  1010. if (DstSize >= SrcSize)
  1011. report("Generic truncate has destination type no smaller than source",
  1012. MI);
  1013. break;
  1014. }
  1015. break;
  1016. }
  1017. case TargetOpcode::G_SELECT: {
  1018. LLT SelTy = MRI->getType(MI->getOperand(0).getReg());
  1019. LLT CondTy = MRI->getType(MI->getOperand(1).getReg());
  1020. if (!SelTy.isValid() || !CondTy.isValid())
  1021. break;
  1022. // Scalar condition select on a vector is valid.
  1023. if (CondTy.isVector())
  1024. verifyVectorElementMatch(SelTy, CondTy, MI);
  1025. break;
  1026. }
  1027. case TargetOpcode::G_MERGE_VALUES: {
  1028. // G_MERGE_VALUES should only be used to merge scalars into a larger scalar,
  1029. // e.g. s2N = MERGE sN, sN
  1030. // Merging multiple scalars into a vector is not allowed, should use
  1031. // G_BUILD_VECTOR for that.
  1032. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1033. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  1034. if (DstTy.isVector() || SrcTy.isVector())
  1035. report("G_MERGE_VALUES cannot operate on vectors", MI);
  1036. const unsigned NumOps = MI->getNumOperands();
  1037. if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1))
  1038. report("G_MERGE_VALUES result size is inconsistent", MI);
  1039. for (unsigned I = 2; I != NumOps; ++I) {
  1040. if (MRI->getType(MI->getOperand(I).getReg()) != SrcTy)
  1041. report("G_MERGE_VALUES source types do not match", MI);
  1042. }
  1043. break;
  1044. }
  1045. case TargetOpcode::G_UNMERGE_VALUES: {
  1046. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1047. LLT SrcTy = MRI->getType(MI->getOperand(MI->getNumOperands()-1).getReg());
  1048. // For now G_UNMERGE can split vectors.
  1049. for (unsigned i = 0; i < MI->getNumOperands()-1; ++i) {
  1050. if (MRI->getType(MI->getOperand(i).getReg()) != DstTy)
  1051. report("G_UNMERGE_VALUES destination types do not match", MI);
  1052. }
  1053. if (SrcTy.getSizeInBits() !=
  1054. (DstTy.getSizeInBits() * (MI->getNumOperands() - 1))) {
  1055. report("G_UNMERGE_VALUES source operand does not cover dest operands",
  1056. MI);
  1057. }
  1058. break;
  1059. }
  1060. case TargetOpcode::G_BUILD_VECTOR: {
  1061. // Source types must be scalars, dest type a vector. Total size of scalars
  1062. // must match the dest vector size.
  1063. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1064. LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
  1065. if (!DstTy.isVector() || SrcEltTy.isVector()) {
  1066. report("G_BUILD_VECTOR must produce a vector from scalar operands", MI);
  1067. break;
  1068. }
  1069. if (DstTy.getElementType() != SrcEltTy)
  1070. report("G_BUILD_VECTOR result element type must match source type", MI);
  1071. if (DstTy.getNumElements() != MI->getNumOperands() - 1)
  1072. report("G_BUILD_VECTOR must have an operand for each elemement", MI);
  1073. for (unsigned i = 2; i < MI->getNumOperands(); ++i) {
  1074. if (MRI->getType(MI->getOperand(1).getReg()) !=
  1075. MRI->getType(MI->getOperand(i).getReg()))
  1076. report("G_BUILD_VECTOR source operand types are not homogeneous", MI);
  1077. }
  1078. break;
  1079. }
  1080. case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
  1081. // Source types must be scalars, dest type a vector. Scalar types must be
  1082. // larger than the dest vector elt type, as this is a truncating operation.
  1083. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1084. LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
  1085. if (!DstTy.isVector() || SrcEltTy.isVector())
  1086. report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
  1087. MI);
  1088. for (unsigned i = 2; i < MI->getNumOperands(); ++i) {
  1089. if (MRI->getType(MI->getOperand(1).getReg()) !=
  1090. MRI->getType(MI->getOperand(i).getReg()))
  1091. report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
  1092. MI);
  1093. }
  1094. if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits())
  1095. report("G_BUILD_VECTOR_TRUNC source operand types are not larger than "
  1096. "dest elt type",
  1097. MI);
  1098. break;
  1099. }
  1100. case TargetOpcode::G_CONCAT_VECTORS: {
  1101. // Source types should be vectors, and total size should match the dest
  1102. // vector size.
  1103. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1104. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  1105. if (!DstTy.isVector() || !SrcTy.isVector())
  1106. report("G_CONCAT_VECTOR requires vector source and destination operands",
  1107. MI);
  1108. for (unsigned i = 2; i < MI->getNumOperands(); ++i) {
  1109. if (MRI->getType(MI->getOperand(1).getReg()) !=
  1110. MRI->getType(MI->getOperand(i).getReg()))
  1111. report("G_CONCAT_VECTOR source operand types are not homogeneous", MI);
  1112. }
  1113. if (DstTy.getNumElements() !=
  1114. SrcTy.getNumElements() * (MI->getNumOperands() - 1))
  1115. report("G_CONCAT_VECTOR num dest and source elements should match", MI);
  1116. break;
  1117. }
  1118. case TargetOpcode::G_ICMP:
  1119. case TargetOpcode::G_FCMP: {
  1120. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1121. LLT SrcTy = MRI->getType(MI->getOperand(2).getReg());
  1122. if ((DstTy.isVector() != SrcTy.isVector()) ||
  1123. (DstTy.isVector() && DstTy.getNumElements() != SrcTy.getNumElements()))
  1124. report("Generic vector icmp/fcmp must preserve number of lanes", MI);
  1125. break;
  1126. }
  1127. case TargetOpcode::G_EXTRACT: {
  1128. const MachineOperand &SrcOp = MI->getOperand(1);
  1129. if (!SrcOp.isReg()) {
  1130. report("extract source must be a register", MI);
  1131. break;
  1132. }
  1133. const MachineOperand &OffsetOp = MI->getOperand(2);
  1134. if (!OffsetOp.isImm()) {
  1135. report("extract offset must be a constant", MI);
  1136. break;
  1137. }
  1138. unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
  1139. unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
  1140. if (SrcSize == DstSize)
  1141. report("extract source must be larger than result", MI);
  1142. if (DstSize + OffsetOp.getImm() > SrcSize)
  1143. report("extract reads past end of register", MI);
  1144. break;
  1145. }
  1146. case TargetOpcode::G_INSERT: {
  1147. const MachineOperand &SrcOp = MI->getOperand(2);
  1148. if (!SrcOp.isReg()) {
  1149. report("insert source must be a register", MI);
  1150. break;
  1151. }
  1152. const MachineOperand &OffsetOp = MI->getOperand(3);
  1153. if (!OffsetOp.isImm()) {
  1154. report("insert offset must be a constant", MI);
  1155. break;
  1156. }
  1157. unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
  1158. unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
  1159. if (DstSize <= SrcSize)
  1160. report("inserted size must be smaller than total register", MI);
  1161. if (SrcSize + OffsetOp.getImm() > DstSize)
  1162. report("insert writes past end of register", MI);
  1163. break;
  1164. }
  1165. case TargetOpcode::G_JUMP_TABLE: {
  1166. if (!MI->getOperand(1).isJTI())
  1167. report("G_JUMP_TABLE source operand must be a jump table index", MI);
  1168. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1169. if (!DstTy.isPointer())
  1170. report("G_JUMP_TABLE dest operand must have a pointer type", MI);
  1171. break;
  1172. }
  1173. case TargetOpcode::G_BRJT: {
  1174. if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
  1175. report("G_BRJT src operand 0 must be a pointer type", MI);
  1176. if (!MI->getOperand(1).isJTI())
  1177. report("G_BRJT src operand 1 must be a jump table index", MI);
  1178. const auto &IdxOp = MI->getOperand(2);
  1179. if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer())
  1180. report("G_BRJT src operand 2 must be a scalar reg type", MI);
  1181. break;
  1182. }
  1183. case TargetOpcode::G_INTRINSIC:
  1184. case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS: {
  1185. // TODO: Should verify number of def and use operands, but the current
  1186. // interface requires passing in IR types for mangling.
  1187. const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs());
  1188. if (!IntrIDOp.isIntrinsicID()) {
  1189. report("G_INTRINSIC first src operand must be an intrinsic ID", MI);
  1190. break;
  1191. }
  1192. bool NoSideEffects = MI->getOpcode() == TargetOpcode::G_INTRINSIC;
  1193. unsigned IntrID = IntrIDOp.getIntrinsicID();
  1194. if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
  1195. AttributeList Attrs
  1196. = Intrinsic::getAttributes(MF->getFunction().getContext(),
  1197. static_cast<Intrinsic::ID>(IntrID));
  1198. bool DeclHasSideEffects = !Attrs.hasFnAttribute(Attribute::ReadNone);
  1199. if (NoSideEffects && DeclHasSideEffects) {
  1200. report("G_INTRINSIC used with intrinsic that accesses memory", MI);
  1201. break;
  1202. }
  1203. if (!NoSideEffects && !DeclHasSideEffects) {
  1204. report("G_INTRINSIC_W_SIDE_EFFECTS used with readnone intrinsic", MI);
  1205. break;
  1206. }
  1207. }
  1208. break;
  1209. }
  1210. case TargetOpcode::G_SEXT_INREG: {
  1211. if (!MI->getOperand(2).isImm()) {
  1212. report("G_SEXT_INREG expects an immediate operand #2", MI);
  1213. break;
  1214. }
  1215. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1216. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  1217. verifyVectorElementMatch(DstTy, SrcTy, MI);
  1218. int64_t Imm = MI->getOperand(2).getImm();
  1219. if (Imm <= 0)
  1220. report("G_SEXT_INREG size must be >= 1", MI);
  1221. if (Imm >= SrcTy.getScalarSizeInBits())
  1222. report("G_SEXT_INREG size must be less than source bit width", MI);
  1223. break;
  1224. }
  1225. case TargetOpcode::G_SHUFFLE_VECTOR: {
  1226. const MachineOperand &MaskOp = MI->getOperand(3);
  1227. if (!MaskOp.isShuffleMask()) {
  1228. report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI);
  1229. break;
  1230. }
  1231. const Constant *Mask = MaskOp.getShuffleMask();
  1232. auto *MaskVT = dyn_cast<VectorType>(Mask->getType());
  1233. if (!MaskVT || !MaskVT->getElementType()->isIntegerTy(32)) {
  1234. report("Invalid shufflemask constant type", MI);
  1235. break;
  1236. }
  1237. if (!Mask->getAggregateElement(0u)) {
  1238. report("Invalid shufflemask constant type", MI);
  1239. break;
  1240. }
  1241. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1242. LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg());
  1243. LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg());
  1244. if (Src0Ty != Src1Ty)
  1245. report("Source operands must be the same type", MI);
  1246. if (Src0Ty.getScalarType() != DstTy.getScalarType())
  1247. report("G_SHUFFLE_VECTOR cannot change element type", MI);
  1248. // Don't check that all operands are vector because scalars are used in
  1249. // place of 1 element vectors.
  1250. int SrcNumElts = Src0Ty.isVector() ? Src0Ty.getNumElements() : 1;
  1251. int DstNumElts = DstTy.isVector() ? DstTy.getNumElements() : 1;
  1252. SmallVector<int, 32> MaskIdxes;
  1253. ShuffleVectorInst::getShuffleMask(Mask, MaskIdxes);
  1254. if (static_cast<int>(MaskIdxes.size()) != DstNumElts)
  1255. report("Wrong result type for shufflemask", MI);
  1256. for (int Idx : MaskIdxes) {
  1257. if (Idx < 0)
  1258. continue;
  1259. if (Idx >= 2 * SrcNumElts)
  1260. report("Out of bounds shuffle index", MI);
  1261. }
  1262. break;
  1263. }
  1264. case TargetOpcode::G_DYN_STACKALLOC: {
  1265. const MachineOperand &DstOp = MI->getOperand(0);
  1266. const MachineOperand &AllocOp = MI->getOperand(1);
  1267. const MachineOperand &AlignOp = MI->getOperand(2);
  1268. if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) {
  1269. report("dst operand 0 must be a pointer type", MI);
  1270. break;
  1271. }
  1272. if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) {
  1273. report("src operand 1 must be a scalar reg type", MI);
  1274. break;
  1275. }
  1276. if (!AlignOp.isImm()) {
  1277. report("src operand 2 must be an immediate type", MI);
  1278. break;
  1279. }
  1280. break;
  1281. }
  1282. default:
  1283. break;
  1284. }
  1285. }
  1286. void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
  1287. const MCInstrDesc &MCID = MI->getDesc();
  1288. if (MI->getNumOperands() < MCID.getNumOperands()) {
  1289. report("Too few operands", MI);
  1290. errs() << MCID.getNumOperands() << " operands expected, but "
  1291. << MI->getNumOperands() << " given.\n";
  1292. }
  1293. if (MI->isPHI()) {
  1294. if (MF->getProperties().hasProperty(
  1295. MachineFunctionProperties::Property::NoPHIs))
  1296. report("Found PHI instruction with NoPHIs property set", MI);
  1297. if (FirstNonPHI)
  1298. report("Found PHI instruction after non-PHI", MI);
  1299. } else if (FirstNonPHI == nullptr)
  1300. FirstNonPHI = MI;
  1301. // Check the tied operands.
  1302. if (MI->isInlineAsm())
  1303. verifyInlineAsm(MI);
  1304. // Check the MachineMemOperands for basic consistency.
  1305. for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
  1306. E = MI->memoperands_end();
  1307. I != E; ++I) {
  1308. if ((*I)->isLoad() && !MI->mayLoad())
  1309. report("Missing mayLoad flag", MI);
  1310. if ((*I)->isStore() && !MI->mayStore())
  1311. report("Missing mayStore flag", MI);
  1312. }
  1313. // Debug values must not have a slot index.
  1314. // Other instructions must have one, unless they are inside a bundle.
  1315. if (LiveInts) {
  1316. bool mapped = !LiveInts->isNotInMIMap(*MI);
  1317. if (MI->isDebugInstr()) {
  1318. if (mapped)
  1319. report("Debug instruction has a slot index", MI);
  1320. } else if (MI->isInsideBundle()) {
  1321. if (mapped)
  1322. report("Instruction inside bundle has a slot index", MI);
  1323. } else {
  1324. if (!mapped)
  1325. report("Missing slot index", MI);
  1326. }
  1327. }
  1328. if (isPreISelGenericOpcode(MCID.getOpcode())) {
  1329. verifyPreISelGenericInstruction(MI);
  1330. return;
  1331. }
  1332. StringRef ErrorInfo;
  1333. if (!TII->verifyInstruction(*MI, ErrorInfo))
  1334. report(ErrorInfo.data(), MI);
  1335. // Verify properties of various specific instruction types
  1336. switch (MI->getOpcode()) {
  1337. case TargetOpcode::COPY: {
  1338. if (foundErrors)
  1339. break;
  1340. const MachineOperand &DstOp = MI->getOperand(0);
  1341. const MachineOperand &SrcOp = MI->getOperand(1);
  1342. LLT DstTy = MRI->getType(DstOp.getReg());
  1343. LLT SrcTy = MRI->getType(SrcOp.getReg());
  1344. if (SrcTy.isValid() && DstTy.isValid()) {
  1345. // If both types are valid, check that the types are the same.
  1346. if (SrcTy != DstTy) {
  1347. report("Copy Instruction is illegal with mismatching types", MI);
  1348. errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n";
  1349. }
  1350. }
  1351. if (SrcTy.isValid() || DstTy.isValid()) {
  1352. // If one of them have valid types, let's just check they have the same
  1353. // size.
  1354. unsigned SrcSize = TRI->getRegSizeInBits(SrcOp.getReg(), *MRI);
  1355. unsigned DstSize = TRI->getRegSizeInBits(DstOp.getReg(), *MRI);
  1356. assert(SrcSize && "Expecting size here");
  1357. assert(DstSize && "Expecting size here");
  1358. if (SrcSize != DstSize)
  1359. if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
  1360. report("Copy Instruction is illegal with mismatching sizes", MI);
  1361. errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize
  1362. << "\n";
  1363. }
  1364. }
  1365. break;
  1366. }
  1367. case TargetOpcode::STATEPOINT:
  1368. if (!MI->getOperand(StatepointOpers::IDPos).isImm() ||
  1369. !MI->getOperand(StatepointOpers::NBytesPos).isImm() ||
  1370. !MI->getOperand(StatepointOpers::NCallArgsPos).isImm())
  1371. report("meta operands to STATEPOINT not constant!", MI);
  1372. break;
  1373. auto VerifyStackMapConstant = [&](unsigned Offset) {
  1374. if (!MI->getOperand(Offset).isImm() ||
  1375. MI->getOperand(Offset).getImm() != StackMaps::ConstantOp ||
  1376. !MI->getOperand(Offset + 1).isImm())
  1377. report("stack map constant to STATEPOINT not well formed!", MI);
  1378. };
  1379. const unsigned VarStart = StatepointOpers(MI).getVarIdx();
  1380. VerifyStackMapConstant(VarStart + StatepointOpers::CCOffset);
  1381. VerifyStackMapConstant(VarStart + StatepointOpers::FlagsOffset);
  1382. VerifyStackMapConstant(VarStart + StatepointOpers::NumDeoptOperandsOffset);
  1383. // TODO: verify we have properly encoded deopt arguments
  1384. break;
  1385. }
  1386. }
  1387. void
  1388. MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
  1389. const MachineInstr *MI = MO->getParent();
  1390. const MCInstrDesc &MCID = MI->getDesc();
  1391. unsigned NumDefs = MCID.getNumDefs();
  1392. if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
  1393. NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
  1394. // The first MCID.NumDefs operands must be explicit register defines
  1395. if (MONum < NumDefs) {
  1396. const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
  1397. if (!MO->isReg())
  1398. report("Explicit definition must be a register", MO, MONum);
  1399. else if (!MO->isDef() && !MCOI.isOptionalDef())
  1400. report("Explicit definition marked as use", MO, MONum);
  1401. else if (MO->isImplicit())
  1402. report("Explicit definition marked as implicit", MO, MONum);
  1403. } else if (MONum < MCID.getNumOperands()) {
  1404. const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
  1405. // Don't check if it's the last operand in a variadic instruction. See,
  1406. // e.g., LDM_RET in the arm back end.
  1407. if (MO->isReg() &&
  1408. !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
  1409. if (MO->isDef() && !MCOI.isOptionalDef())
  1410. report("Explicit operand marked as def", MO, MONum);
  1411. if (MO->isImplicit())
  1412. report("Explicit operand marked as implicit", MO, MONum);
  1413. }
  1414. int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
  1415. if (TiedTo != -1) {
  1416. if (!MO->isReg())
  1417. report("Tied use must be a register", MO, MONum);
  1418. else if (!MO->isTied())
  1419. report("Operand should be tied", MO, MONum);
  1420. else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
  1421. report("Tied def doesn't match MCInstrDesc", MO, MONum);
  1422. else if (Register::isPhysicalRegister(MO->getReg())) {
  1423. const MachineOperand &MOTied = MI->getOperand(TiedTo);
  1424. if (!MOTied.isReg())
  1425. report("Tied counterpart must be a register", &MOTied, TiedTo);
  1426. else if (Register::isPhysicalRegister(MOTied.getReg()) &&
  1427. MO->getReg() != MOTied.getReg())
  1428. report("Tied physical registers must match.", &MOTied, TiedTo);
  1429. }
  1430. } else if (MO->isReg() && MO->isTied())
  1431. report("Explicit operand should not be tied", MO, MONum);
  1432. } else {
  1433. // ARM adds %reg0 operands to indicate predicates. We'll allow that.
  1434. if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
  1435. report("Extra explicit operand on non-variadic instruction", MO, MONum);
  1436. }
  1437. switch (MO->getType()) {
  1438. case MachineOperand::MO_Register: {
  1439. const Register Reg = MO->getReg();
  1440. if (!Reg)
  1441. return;
  1442. if (MRI->tracksLiveness() && !MI->isDebugValue())
  1443. checkLiveness(MO, MONum);
  1444. // Verify the consistency of tied operands.
  1445. if (MO->isTied()) {
  1446. unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
  1447. const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
  1448. if (!OtherMO.isReg())
  1449. report("Must be tied to a register", MO, MONum);
  1450. if (!OtherMO.isTied())
  1451. report("Missing tie flags on tied operand", MO, MONum);
  1452. if (MI->findTiedOperandIdx(OtherIdx) != MONum)
  1453. report("Inconsistent tie links", MO, MONum);
  1454. if (MONum < MCID.getNumDefs()) {
  1455. if (OtherIdx < MCID.getNumOperands()) {
  1456. if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
  1457. report("Explicit def tied to explicit use without tie constraint",
  1458. MO, MONum);
  1459. } else {
  1460. if (!OtherMO.isImplicit())
  1461. report("Explicit def should be tied to implicit use", MO, MONum);
  1462. }
  1463. }
  1464. }
  1465. // Verify two-address constraints after leaving SSA form.
  1466. unsigned DefIdx;
  1467. if (!MRI->isSSA() && MO->isUse() &&
  1468. MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
  1469. Reg != MI->getOperand(DefIdx).getReg())
  1470. report("Two-address instruction operands must be identical", MO, MONum);
  1471. // Check register classes.
  1472. unsigned SubIdx = MO->getSubReg();
  1473. if (Register::isPhysicalRegister(Reg)) {
  1474. if (SubIdx) {
  1475. report("Illegal subregister index for physical register", MO, MONum);
  1476. return;
  1477. }
  1478. if (MONum < MCID.getNumOperands()) {
  1479. if (const TargetRegisterClass *DRC =
  1480. TII->getRegClass(MCID, MONum, TRI, *MF)) {
  1481. if (!DRC->contains(Reg)) {
  1482. report("Illegal physical register for instruction", MO, MONum);
  1483. errs() << printReg(Reg, TRI) << " is not a "
  1484. << TRI->getRegClassName(DRC) << " register.\n";
  1485. }
  1486. }
  1487. }
  1488. if (MO->isRenamable()) {
  1489. if (MRI->isReserved(Reg)) {
  1490. report("isRenamable set on reserved register", MO, MONum);
  1491. return;
  1492. }
  1493. }
  1494. if (MI->isDebugValue() && MO->isUse() && !MO->isDebug()) {
  1495. report("Use-reg is not IsDebug in a DBG_VALUE", MO, MONum);
  1496. return;
  1497. }
  1498. } else {
  1499. // Virtual register.
  1500. const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
  1501. if (!RC) {
  1502. // This is a generic virtual register.
  1503. // If we're post-Select, we can't have gvregs anymore.
  1504. if (isFunctionSelected) {
  1505. report("Generic virtual register invalid in a Selected function",
  1506. MO, MONum);
  1507. return;
  1508. }
  1509. // The gvreg must have a type and it must not have a SubIdx.
  1510. LLT Ty = MRI->getType(Reg);
  1511. if (!Ty.isValid()) {
  1512. report("Generic virtual register must have a valid type", MO,
  1513. MONum);
  1514. return;
  1515. }
  1516. const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
  1517. // If we're post-RegBankSelect, the gvreg must have a bank.
  1518. if (!RegBank && isFunctionRegBankSelected) {
  1519. report("Generic virtual register must have a bank in a "
  1520. "RegBankSelected function",
  1521. MO, MONum);
  1522. return;
  1523. }
  1524. // Make sure the register fits into its register bank if any.
  1525. if (RegBank && Ty.isValid() &&
  1526. RegBank->getSize() < Ty.getSizeInBits()) {
  1527. report("Register bank is too small for virtual register", MO,
  1528. MONum);
  1529. errs() << "Register bank " << RegBank->getName() << " too small("
  1530. << RegBank->getSize() << ") to fit " << Ty.getSizeInBits()
  1531. << "-bits\n";
  1532. return;
  1533. }
  1534. if (SubIdx) {
  1535. report("Generic virtual register does not allow subregister index", MO,
  1536. MONum);
  1537. return;
  1538. }
  1539. // If this is a target specific instruction and this operand
  1540. // has register class constraint, the virtual register must
  1541. // comply to it.
  1542. if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
  1543. MONum < MCID.getNumOperands() &&
  1544. TII->getRegClass(MCID, MONum, TRI, *MF)) {
  1545. report("Virtual register does not match instruction constraint", MO,
  1546. MONum);
  1547. errs() << "Expect register class "
  1548. << TRI->getRegClassName(
  1549. TII->getRegClass(MCID, MONum, TRI, *MF))
  1550. << " but got nothing\n";
  1551. return;
  1552. }
  1553. break;
  1554. }
  1555. if (SubIdx) {
  1556. const TargetRegisterClass *SRC =
  1557. TRI->getSubClassWithSubReg(RC, SubIdx);
  1558. if (!SRC) {
  1559. report("Invalid subregister index for virtual register", MO, MONum);
  1560. errs() << "Register class " << TRI->getRegClassName(RC)
  1561. << " does not support subreg index " << SubIdx << "\n";
  1562. return;
  1563. }
  1564. if (RC != SRC) {
  1565. report("Invalid register class for subregister index", MO, MONum);
  1566. errs() << "Register class " << TRI->getRegClassName(RC)
  1567. << " does not fully support subreg index " << SubIdx << "\n";
  1568. return;
  1569. }
  1570. }
  1571. if (MONum < MCID.getNumOperands()) {
  1572. if (const TargetRegisterClass *DRC =
  1573. TII->getRegClass(MCID, MONum, TRI, *MF)) {
  1574. if (SubIdx) {
  1575. const TargetRegisterClass *SuperRC =
  1576. TRI->getLargestLegalSuperClass(RC, *MF);
  1577. if (!SuperRC) {
  1578. report("No largest legal super class exists.", MO, MONum);
  1579. return;
  1580. }
  1581. DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
  1582. if (!DRC) {
  1583. report("No matching super-reg register class.", MO, MONum);
  1584. return;
  1585. }
  1586. }
  1587. if (!RC->hasSuperClassEq(DRC)) {
  1588. report("Illegal virtual register for instruction", MO, MONum);
  1589. errs() << "Expected a " << TRI->getRegClassName(DRC)
  1590. << " register, but got a " << TRI->getRegClassName(RC)
  1591. << " register\n";
  1592. }
  1593. }
  1594. }
  1595. }
  1596. break;
  1597. }
  1598. case MachineOperand::MO_RegisterMask:
  1599. regMasks.push_back(MO->getRegMask());
  1600. break;
  1601. case MachineOperand::MO_MachineBasicBlock:
  1602. if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
  1603. report("PHI operand is not in the CFG", MO, MONum);
  1604. break;
  1605. case MachineOperand::MO_FrameIndex:
  1606. if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
  1607. LiveInts && !LiveInts->isNotInMIMap(*MI)) {
  1608. int FI = MO->getIndex();
  1609. LiveInterval &LI = LiveStks->getInterval(FI);
  1610. SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
  1611. bool stores = MI->mayStore();
  1612. bool loads = MI->mayLoad();
  1613. // For a memory-to-memory move, we need to check if the frame
  1614. // index is used for storing or loading, by inspecting the
  1615. // memory operands.
  1616. if (stores && loads) {
  1617. for (auto *MMO : MI->memoperands()) {
  1618. const PseudoSourceValue *PSV = MMO->getPseudoValue();
  1619. if (PSV == nullptr) continue;
  1620. const FixedStackPseudoSourceValue *Value =
  1621. dyn_cast<FixedStackPseudoSourceValue>(PSV);
  1622. if (Value == nullptr) continue;
  1623. if (Value->getFrameIndex() != FI) continue;
  1624. if (MMO->isStore())
  1625. loads = false;
  1626. else
  1627. stores = false;
  1628. break;
  1629. }
  1630. if (loads == stores)
  1631. report("Missing fixed stack memoperand.", MI);
  1632. }
  1633. if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
  1634. report("Instruction loads from dead spill slot", MO, MONum);
  1635. errs() << "Live stack: " << LI << '\n';
  1636. }
  1637. if (stores && !LI.liveAt(Idx.getRegSlot())) {
  1638. report("Instruction stores to dead spill slot", MO, MONum);
  1639. errs() << "Live stack: " << LI << '\n';
  1640. }
  1641. }
  1642. break;
  1643. default:
  1644. break;
  1645. }
  1646. }
  1647. void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
  1648. unsigned MONum, SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
  1649. LaneBitmask LaneMask) {
  1650. LiveQueryResult LRQ = LR.Query(UseIdx);
  1651. // Check if we have a segment at the use, note however that we only need one
  1652. // live subregister range, the others may be dead.
  1653. if (!LRQ.valueIn() && LaneMask.none()) {
  1654. report("No live segment at use", MO, MONum);
  1655. report_context_liverange(LR);
  1656. report_context_vreg_regunit(VRegOrUnit);
  1657. report_context(UseIdx);
  1658. }
  1659. if (MO->isKill() && !LRQ.isKill()) {
  1660. report("Live range continues after kill flag", MO, MONum);
  1661. report_context_liverange(LR);
  1662. report_context_vreg_regunit(VRegOrUnit);
  1663. if (LaneMask.any())
  1664. report_context_lanemask(LaneMask);
  1665. report_context(UseIdx);
  1666. }
  1667. }
  1668. void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
  1669. unsigned MONum, SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
  1670. bool SubRangeCheck, LaneBitmask LaneMask) {
  1671. if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
  1672. assert(VNI && "NULL valno is not allowed");
  1673. if (VNI->def != DefIdx) {
  1674. report("Inconsistent valno->def", MO, MONum);
  1675. report_context_liverange(LR);
  1676. report_context_vreg_regunit(VRegOrUnit);
  1677. if (LaneMask.any())
  1678. report_context_lanemask(LaneMask);
  1679. report_context(*VNI);
  1680. report_context(DefIdx);
  1681. }
  1682. } else {
  1683. report("No live segment at def", MO, MONum);
  1684. report_context_liverange(LR);
  1685. report_context_vreg_regunit(VRegOrUnit);
  1686. if (LaneMask.any())
  1687. report_context_lanemask(LaneMask);
  1688. report_context(DefIdx);
  1689. }
  1690. // Check that, if the dead def flag is present, LiveInts agree.
  1691. if (MO->isDead()) {
  1692. LiveQueryResult LRQ = LR.Query(DefIdx);
  1693. if (!LRQ.isDeadDef()) {
  1694. assert(Register::isVirtualRegister(VRegOrUnit) &&
  1695. "Expecting a virtual register.");
  1696. // A dead subreg def only tells us that the specific subreg is dead. There
  1697. // could be other non-dead defs of other subregs, or we could have other
  1698. // parts of the register being live through the instruction. So unless we
  1699. // are checking liveness for a subrange it is ok for the live range to
  1700. // continue, given that we have a dead def of a subregister.
  1701. if (SubRangeCheck || MO->getSubReg() == 0) {
  1702. report("Live range continues after dead def flag", MO, MONum);
  1703. report_context_liverange(LR);
  1704. report_context_vreg_regunit(VRegOrUnit);
  1705. if (LaneMask.any())
  1706. report_context_lanemask(LaneMask);
  1707. }
  1708. }
  1709. }
  1710. }
  1711. void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
  1712. const MachineInstr *MI = MO->getParent();
  1713. const unsigned Reg = MO->getReg();
  1714. // Both use and def operands can read a register.
  1715. if (MO->readsReg()) {
  1716. if (MO->isKill())
  1717. addRegWithSubRegs(regsKilled, Reg);
  1718. // Check that LiveVars knows this kill.
  1719. if (LiveVars && Register::isVirtualRegister(Reg) && MO->isKill()) {
  1720. LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
  1721. if (!is_contained(VI.Kills, MI))
  1722. report("Kill missing from LiveVariables", MO, MONum);
  1723. }
  1724. // Check LiveInts liveness and kill.
  1725. if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
  1726. SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI);
  1727. // Check the cached regunit intervals.
  1728. if (Register::isPhysicalRegister(Reg) && !isReserved(Reg)) {
  1729. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
  1730. if (MRI->isReservedRegUnit(*Units))
  1731. continue;
  1732. if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units))
  1733. checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units);
  1734. }
  1735. }
  1736. if (Register::isVirtualRegister(Reg)) {
  1737. if (LiveInts->hasInterval(Reg)) {
  1738. // This is a virtual register interval.
  1739. const LiveInterval &LI = LiveInts->getInterval(Reg);
  1740. checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg);
  1741. if (LI.hasSubRanges() && !MO->isDef()) {
  1742. unsigned SubRegIdx = MO->getSubReg();
  1743. LaneBitmask MOMask = SubRegIdx != 0
  1744. ? TRI->getSubRegIndexLaneMask(SubRegIdx)
  1745. : MRI->getMaxLaneMaskForVReg(Reg);
  1746. LaneBitmask LiveInMask;
  1747. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  1748. if ((MOMask & SR.LaneMask).none())
  1749. continue;
  1750. checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
  1751. LiveQueryResult LRQ = SR.Query(UseIdx);
  1752. if (LRQ.valueIn())
  1753. LiveInMask |= SR.LaneMask;
  1754. }
  1755. // At least parts of the register has to be live at the use.
  1756. if ((LiveInMask & MOMask).none()) {
  1757. report("No live subrange at use", MO, MONum);
  1758. report_context(LI);
  1759. report_context(UseIdx);
  1760. }
  1761. }
  1762. } else {
  1763. report("Virtual register has no live interval", MO, MONum);
  1764. }
  1765. }
  1766. }
  1767. // Use of a dead register.
  1768. if (!regsLive.count(Reg)) {
  1769. if (Register::isPhysicalRegister(Reg)) {
  1770. // Reserved registers may be used even when 'dead'.
  1771. bool Bad = !isReserved(Reg);
  1772. // We are fine if just any subregister has a defined value.
  1773. if (Bad) {
  1774. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid();
  1775. ++SubRegs) {
  1776. if (regsLive.count(*SubRegs)) {
  1777. Bad = false;
  1778. break;
  1779. }
  1780. }
  1781. }
  1782. // If there is an additional implicit-use of a super register we stop
  1783. // here. By definition we are fine if the super register is not
  1784. // (completely) dead, if the complete super register is dead we will
  1785. // get a report for its operand.
  1786. if (Bad) {
  1787. for (const MachineOperand &MOP : MI->uses()) {
  1788. if (!MOP.isReg() || !MOP.isImplicit())
  1789. continue;
  1790. if (!Register::isPhysicalRegister(MOP.getReg()))
  1791. continue;
  1792. for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid();
  1793. ++SubRegs) {
  1794. if (*SubRegs == Reg) {
  1795. Bad = false;
  1796. break;
  1797. }
  1798. }
  1799. }
  1800. }
  1801. if (Bad)
  1802. report("Using an undefined physical register", MO, MONum);
  1803. } else if (MRI->def_empty(Reg)) {
  1804. report("Reading virtual register without a def", MO, MONum);
  1805. } else {
  1806. BBInfo &MInfo = MBBInfoMap[MI->getParent()];
  1807. // We don't know which virtual registers are live in, so only complain
  1808. // if vreg was killed in this MBB. Otherwise keep track of vregs that
  1809. // must be live in. PHI instructions are handled separately.
  1810. if (MInfo.regsKilled.count(Reg))
  1811. report("Using a killed virtual register", MO, MONum);
  1812. else if (!MI->isPHI())
  1813. MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
  1814. }
  1815. }
  1816. }
  1817. if (MO->isDef()) {
  1818. // Register defined.
  1819. // TODO: verify that earlyclobber ops are not used.
  1820. if (MO->isDead())
  1821. addRegWithSubRegs(regsDead, Reg);
  1822. else
  1823. addRegWithSubRegs(regsDefined, Reg);
  1824. // Verify SSA form.
  1825. if (MRI->isSSA() && Register::isVirtualRegister(Reg) &&
  1826. std::next(MRI->def_begin(Reg)) != MRI->def_end())
  1827. report("Multiple virtual register defs in SSA form", MO, MONum);
  1828. // Check LiveInts for a live segment, but only for virtual registers.
  1829. if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
  1830. SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
  1831. DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
  1832. if (Register::isVirtualRegister(Reg)) {
  1833. if (LiveInts->hasInterval(Reg)) {
  1834. const LiveInterval &LI = LiveInts->getInterval(Reg);
  1835. checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg);
  1836. if (LI.hasSubRanges()) {
  1837. unsigned SubRegIdx = MO->getSubReg();
  1838. LaneBitmask MOMask = SubRegIdx != 0
  1839. ? TRI->getSubRegIndexLaneMask(SubRegIdx)
  1840. : MRI->getMaxLaneMaskForVReg(Reg);
  1841. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  1842. if ((SR.LaneMask & MOMask).none())
  1843. continue;
  1844. checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask);
  1845. }
  1846. }
  1847. } else {
  1848. report("Virtual register has no Live interval", MO, MONum);
  1849. }
  1850. }
  1851. }
  1852. }
  1853. }
  1854. void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {}
  1855. // This function gets called after visiting all instructions in a bundle. The
  1856. // argument points to the bundle header.
  1857. // Normal stand-alone instructions are also considered 'bundles', and this
  1858. // function is called for all of them.
  1859. void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
  1860. BBInfo &MInfo = MBBInfoMap[MI->getParent()];
  1861. set_union(MInfo.regsKilled, regsKilled);
  1862. set_subtract(regsLive, regsKilled); regsKilled.clear();
  1863. // Kill any masked registers.
  1864. while (!regMasks.empty()) {
  1865. const uint32_t *Mask = regMasks.pop_back_val();
  1866. for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
  1867. if (Register::isPhysicalRegister(*I) &&
  1868. MachineOperand::clobbersPhysReg(Mask, *I))
  1869. regsDead.push_back(*I);
  1870. }
  1871. set_subtract(regsLive, regsDead); regsDead.clear();
  1872. set_union(regsLive, regsDefined); regsDefined.clear();
  1873. }
  1874. void
  1875. MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
  1876. MBBInfoMap[MBB].regsLiveOut = regsLive;
  1877. regsLive.clear();
  1878. if (Indexes) {
  1879. SlotIndex stop = Indexes->getMBBEndIdx(MBB);
  1880. if (!(stop > lastIndex)) {
  1881. report("Block ends before last instruction index", MBB);
  1882. errs() << "Block ends at " << stop
  1883. << " last instruction was at " << lastIndex << '\n';
  1884. }
  1885. lastIndex = stop;
  1886. }
  1887. }
  1888. // Calculate the largest possible vregsPassed sets. These are the registers that
  1889. // can pass through an MBB live, but may not be live every time. It is assumed
  1890. // that all vregsPassed sets are empty before the call.
  1891. void MachineVerifier::calcRegsPassed() {
  1892. // First push live-out regs to successors' vregsPassed. Remember the MBBs that
  1893. // have any vregsPassed.
  1894. SmallPtrSet<const MachineBasicBlock*, 8> todo;
  1895. for (const auto &MBB : *MF) {
  1896. BBInfo &MInfo = MBBInfoMap[&MBB];
  1897. if (!MInfo.reachable)
  1898. continue;
  1899. for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
  1900. SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
  1901. BBInfo &SInfo = MBBInfoMap[*SuI];
  1902. if (SInfo.addPassed(MInfo.regsLiveOut))
  1903. todo.insert(*SuI);
  1904. }
  1905. }
  1906. // Iteratively push vregsPassed to successors. This will converge to the same
  1907. // final state regardless of DenseSet iteration order.
  1908. while (!todo.empty()) {
  1909. const MachineBasicBlock *MBB = *todo.begin();
  1910. todo.erase(MBB);
  1911. BBInfo &MInfo = MBBInfoMap[MBB];
  1912. for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
  1913. SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
  1914. if (*SuI == MBB)
  1915. continue;
  1916. BBInfo &SInfo = MBBInfoMap[*SuI];
  1917. if (SInfo.addPassed(MInfo.vregsPassed))
  1918. todo.insert(*SuI);
  1919. }
  1920. }
  1921. }
  1922. // Calculate the set of virtual registers that must be passed through each basic
  1923. // block in order to satisfy the requirements of successor blocks. This is very
  1924. // similar to calcRegsPassed, only backwards.
  1925. void MachineVerifier::calcRegsRequired() {
  1926. // First push live-in regs to predecessors' vregsRequired.
  1927. SmallPtrSet<const MachineBasicBlock*, 8> todo;
  1928. for (const auto &MBB : *MF) {
  1929. BBInfo &MInfo = MBBInfoMap[&MBB];
  1930. for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
  1931. PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
  1932. BBInfo &PInfo = MBBInfoMap[*PrI];
  1933. if (PInfo.addRequired(MInfo.vregsLiveIn))
  1934. todo.insert(*PrI);
  1935. }
  1936. }
  1937. // Iteratively push vregsRequired to predecessors. This will converge to the
  1938. // same final state regardless of DenseSet iteration order.
  1939. while (!todo.empty()) {
  1940. const MachineBasicBlock *MBB = *todo.begin();
  1941. todo.erase(MBB);
  1942. BBInfo &MInfo = MBBInfoMap[MBB];
  1943. for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
  1944. PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
  1945. if (*PrI == MBB)
  1946. continue;
  1947. BBInfo &SInfo = MBBInfoMap[*PrI];
  1948. if (SInfo.addRequired(MInfo.vregsRequired))
  1949. todo.insert(*PrI);
  1950. }
  1951. }
  1952. }
  1953. // Check PHI instructions at the beginning of MBB. It is assumed that
  1954. // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
  1955. void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
  1956. BBInfo &MInfo = MBBInfoMap[&MBB];
  1957. SmallPtrSet<const MachineBasicBlock*, 8> seen;
  1958. for (const MachineInstr &Phi : MBB) {
  1959. if (!Phi.isPHI())
  1960. break;
  1961. seen.clear();
  1962. const MachineOperand &MODef = Phi.getOperand(0);
  1963. if (!MODef.isReg() || !MODef.isDef()) {
  1964. report("Expected first PHI operand to be a register def", &MODef, 0);
  1965. continue;
  1966. }
  1967. if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
  1968. MODef.isEarlyClobber() || MODef.isDebug())
  1969. report("Unexpected flag on PHI operand", &MODef, 0);
  1970. Register DefReg = MODef.getReg();
  1971. if (!Register::isVirtualRegister(DefReg))
  1972. report("Expected first PHI operand to be a virtual register", &MODef, 0);
  1973. for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
  1974. const MachineOperand &MO0 = Phi.getOperand(I);
  1975. if (!MO0.isReg()) {
  1976. report("Expected PHI operand to be a register", &MO0, I);
  1977. continue;
  1978. }
  1979. if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
  1980. MO0.isDebug() || MO0.isTied())
  1981. report("Unexpected flag on PHI operand", &MO0, I);
  1982. const MachineOperand &MO1 = Phi.getOperand(I + 1);
  1983. if (!MO1.isMBB()) {
  1984. report("Expected PHI operand to be a basic block", &MO1, I + 1);
  1985. continue;
  1986. }
  1987. const MachineBasicBlock &Pre = *MO1.getMBB();
  1988. if (!Pre.isSuccessor(&MBB)) {
  1989. report("PHI input is not a predecessor block", &MO1, I + 1);
  1990. continue;
  1991. }
  1992. if (MInfo.reachable) {
  1993. seen.insert(&Pre);
  1994. BBInfo &PrInfo = MBBInfoMap[&Pre];
  1995. if (!MO0.isUndef() && PrInfo.reachable &&
  1996. !PrInfo.isLiveOut(MO0.getReg()))
  1997. report("PHI operand is not live-out from predecessor", &MO0, I);
  1998. }
  1999. }
  2000. // Did we see all predecessors?
  2001. if (MInfo.reachable) {
  2002. for (MachineBasicBlock *Pred : MBB.predecessors()) {
  2003. if (!seen.count(Pred)) {
  2004. report("Missing PHI operand", &Phi);
  2005. errs() << printMBBReference(*Pred)
  2006. << " is a predecessor according to the CFG.\n";
  2007. }
  2008. }
  2009. }
  2010. }
  2011. }
  2012. void MachineVerifier::visitMachineFunctionAfter() {
  2013. calcRegsPassed();
  2014. for (const MachineBasicBlock &MBB : *MF)
  2015. checkPHIOps(MBB);
  2016. // Now check liveness info if available
  2017. calcRegsRequired();
  2018. // Check for killed virtual registers that should be live out.
  2019. for (const auto &MBB : *MF) {
  2020. BBInfo &MInfo = MBBInfoMap[&MBB];
  2021. for (RegSet::iterator
  2022. I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
  2023. ++I)
  2024. if (MInfo.regsKilled.count(*I)) {
  2025. report("Virtual register killed in block, but needed live out.", &MBB);
  2026. errs() << "Virtual register " << printReg(*I)
  2027. << " is used after the block.\n";
  2028. }
  2029. }
  2030. if (!MF->empty()) {
  2031. BBInfo &MInfo = MBBInfoMap[&MF->front()];
  2032. for (RegSet::iterator
  2033. I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
  2034. ++I) {
  2035. report("Virtual register defs don't dominate all uses.", MF);
  2036. report_context_vreg(*I);
  2037. }
  2038. }
  2039. if (LiveVars)
  2040. verifyLiveVariables();
  2041. if (LiveInts)
  2042. verifyLiveIntervals();
  2043. for (auto CSInfo : MF->getCallSitesInfo())
  2044. if (!CSInfo.first->isCall())
  2045. report("Call site info referencing instruction that is not call", MF);
  2046. }
  2047. void MachineVerifier::verifyLiveVariables() {
  2048. assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
  2049. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  2050. unsigned Reg = Register::index2VirtReg(i);
  2051. LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
  2052. for (const auto &MBB : *MF) {
  2053. BBInfo &MInfo = MBBInfoMap[&MBB];
  2054. // Our vregsRequired should be identical to LiveVariables' AliveBlocks
  2055. if (MInfo.vregsRequired.count(Reg)) {
  2056. if (!VI.AliveBlocks.test(MBB.getNumber())) {
  2057. report("LiveVariables: Block missing from AliveBlocks", &MBB);
  2058. errs() << "Virtual register " << printReg(Reg)
  2059. << " must be live through the block.\n";
  2060. }
  2061. } else {
  2062. if (VI.AliveBlocks.test(MBB.getNumber())) {
  2063. report("LiveVariables: Block should not be in AliveBlocks", &MBB);
  2064. errs() << "Virtual register " << printReg(Reg)
  2065. << " is not needed live through the block.\n";
  2066. }
  2067. }
  2068. }
  2069. }
  2070. }
  2071. void MachineVerifier::verifyLiveIntervals() {
  2072. assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
  2073. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  2074. unsigned Reg = Register::index2VirtReg(i);
  2075. // Spilling and splitting may leave unused registers around. Skip them.
  2076. if (MRI->reg_nodbg_empty(Reg))
  2077. continue;
  2078. if (!LiveInts->hasInterval(Reg)) {
  2079. report("Missing live interval for virtual register", MF);
  2080. errs() << printReg(Reg, TRI) << " still has defs or uses\n";
  2081. continue;
  2082. }
  2083. const LiveInterval &LI = LiveInts->getInterval(Reg);
  2084. assert(Reg == LI.reg && "Invalid reg to interval mapping");
  2085. verifyLiveInterval(LI);
  2086. }
  2087. // Verify all the cached regunit intervals.
  2088. for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
  2089. if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
  2090. verifyLiveRange(*LR, i);
  2091. }
  2092. void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
  2093. const VNInfo *VNI, unsigned Reg,
  2094. LaneBitmask LaneMask) {
  2095. if (VNI->isUnused())
  2096. return;
  2097. const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
  2098. if (!DefVNI) {
  2099. report("Value not live at VNInfo def and not marked unused", MF);
  2100. report_context(LR, Reg, LaneMask);
  2101. report_context(*VNI);
  2102. return;
  2103. }
  2104. if (DefVNI != VNI) {
  2105. report("Live segment at def has different VNInfo", MF);
  2106. report_context(LR, Reg, LaneMask);
  2107. report_context(*VNI);
  2108. return;
  2109. }
  2110. const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
  2111. if (!MBB) {
  2112. report("Invalid VNInfo definition index", MF);
  2113. report_context(LR, Reg, LaneMask);
  2114. report_context(*VNI);
  2115. return;
  2116. }
  2117. if (VNI->isPHIDef()) {
  2118. if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
  2119. report("PHIDef VNInfo is not defined at MBB start", MBB);
  2120. report_context(LR, Reg, LaneMask);
  2121. report_context(*VNI);
  2122. }
  2123. return;
  2124. }
  2125. // Non-PHI def.
  2126. const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
  2127. if (!MI) {
  2128. report("No instruction at VNInfo def index", MBB);
  2129. report_context(LR, Reg, LaneMask);
  2130. report_context(*VNI);
  2131. return;
  2132. }
  2133. if (Reg != 0) {
  2134. bool hasDef = false;
  2135. bool isEarlyClobber = false;
  2136. for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
  2137. if (!MOI->isReg() || !MOI->isDef())
  2138. continue;
  2139. if (Register::isVirtualRegister(Reg)) {
  2140. if (MOI->getReg() != Reg)
  2141. continue;
  2142. } else {
  2143. if (!Register::isPhysicalRegister(MOI->getReg()) ||
  2144. !TRI->hasRegUnit(MOI->getReg(), Reg))
  2145. continue;
  2146. }
  2147. if (LaneMask.any() &&
  2148. (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
  2149. continue;
  2150. hasDef = true;
  2151. if (MOI->isEarlyClobber())
  2152. isEarlyClobber = true;
  2153. }
  2154. if (!hasDef) {
  2155. report("Defining instruction does not modify register", MI);
  2156. report_context(LR, Reg, LaneMask);
  2157. report_context(*VNI);
  2158. }
  2159. // Early clobber defs begin at USE slots, but other defs must begin at
  2160. // DEF slots.
  2161. if (isEarlyClobber) {
  2162. if (!VNI->def.isEarlyClobber()) {
  2163. report("Early clobber def must be at an early-clobber slot", MBB);
  2164. report_context(LR, Reg, LaneMask);
  2165. report_context(*VNI);
  2166. }
  2167. } else if (!VNI->def.isRegister()) {
  2168. report("Non-PHI, non-early clobber def must be at a register slot", MBB);
  2169. report_context(LR, Reg, LaneMask);
  2170. report_context(*VNI);
  2171. }
  2172. }
  2173. }
  2174. void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
  2175. const LiveRange::const_iterator I,
  2176. unsigned Reg, LaneBitmask LaneMask)
  2177. {
  2178. const LiveRange::Segment &S = *I;
  2179. const VNInfo *VNI = S.valno;
  2180. assert(VNI && "Live segment has no valno");
  2181. if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
  2182. report("Foreign valno in live segment", MF);
  2183. report_context(LR, Reg, LaneMask);
  2184. report_context(S);
  2185. report_context(*VNI);
  2186. }
  2187. if (VNI->isUnused()) {
  2188. report("Live segment valno is marked unused", MF);
  2189. report_context(LR, Reg, LaneMask);
  2190. report_context(S);
  2191. }
  2192. const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
  2193. if (!MBB) {
  2194. report("Bad start of live segment, no basic block", MF);
  2195. report_context(LR, Reg, LaneMask);
  2196. report_context(S);
  2197. return;
  2198. }
  2199. SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
  2200. if (S.start != MBBStartIdx && S.start != VNI->def) {
  2201. report("Live segment must begin at MBB entry or valno def", MBB);
  2202. report_context(LR, Reg, LaneMask);
  2203. report_context(S);
  2204. }
  2205. const MachineBasicBlock *EndMBB =
  2206. LiveInts->getMBBFromIndex(S.end.getPrevSlot());
  2207. if (!EndMBB) {
  2208. report("Bad end of live segment, no basic block", MF);
  2209. report_context(LR, Reg, LaneMask);
  2210. report_context(S);
  2211. return;
  2212. }
  2213. // No more checks for live-out segments.
  2214. if (S.end == LiveInts->getMBBEndIdx(EndMBB))
  2215. return;
  2216. // RegUnit intervals are allowed dead phis.
  2217. if (!Register::isVirtualRegister(Reg) && VNI->isPHIDef() &&
  2218. S.start == VNI->def && S.end == VNI->def.getDeadSlot())
  2219. return;
  2220. // The live segment is ending inside EndMBB
  2221. const MachineInstr *MI =
  2222. LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
  2223. if (!MI) {
  2224. report("Live segment doesn't end at a valid instruction", EndMBB);
  2225. report_context(LR, Reg, LaneMask);
  2226. report_context(S);
  2227. return;
  2228. }
  2229. // The block slot must refer to a basic block boundary.
  2230. if (S.end.isBlock()) {
  2231. report("Live segment ends at B slot of an instruction", EndMBB);
  2232. report_context(LR, Reg, LaneMask);
  2233. report_context(S);
  2234. }
  2235. if (S.end.isDead()) {
  2236. // Segment ends on the dead slot.
  2237. // That means there must be a dead def.
  2238. if (!SlotIndex::isSameInstr(S.start, S.end)) {
  2239. report("Live segment ending at dead slot spans instructions", EndMBB);
  2240. report_context(LR, Reg, LaneMask);
  2241. report_context(S);
  2242. }
  2243. }
  2244. // A live segment can only end at an early-clobber slot if it is being
  2245. // redefined by an early-clobber def.
  2246. if (S.end.isEarlyClobber()) {
  2247. if (I+1 == LR.end() || (I+1)->start != S.end) {
  2248. report("Live segment ending at early clobber slot must be "
  2249. "redefined by an EC def in the same instruction", EndMBB);
  2250. report_context(LR, Reg, LaneMask);
  2251. report_context(S);
  2252. }
  2253. }
  2254. // The following checks only apply to virtual registers. Physreg liveness
  2255. // is too weird to check.
  2256. if (Register::isVirtualRegister(Reg)) {
  2257. // A live segment can end with either a redefinition, a kill flag on a
  2258. // use, or a dead flag on a def.
  2259. bool hasRead = false;
  2260. bool hasSubRegDef = false;
  2261. bool hasDeadDef = false;
  2262. for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
  2263. if (!MOI->isReg() || MOI->getReg() != Reg)
  2264. continue;
  2265. unsigned Sub = MOI->getSubReg();
  2266. LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
  2267. : LaneBitmask::getAll();
  2268. if (MOI->isDef()) {
  2269. if (Sub != 0) {
  2270. hasSubRegDef = true;
  2271. // An operand %0:sub0 reads %0:sub1..n. Invert the lane
  2272. // mask for subregister defs. Read-undef defs will be handled by
  2273. // readsReg below.
  2274. SLM = ~SLM;
  2275. }
  2276. if (MOI->isDead())
  2277. hasDeadDef = true;
  2278. }
  2279. if (LaneMask.any() && (LaneMask & SLM).none())
  2280. continue;
  2281. if (MOI->readsReg())
  2282. hasRead = true;
  2283. }
  2284. if (S.end.isDead()) {
  2285. // Make sure that the corresponding machine operand for a "dead" live
  2286. // range has the dead flag. We cannot perform this check for subregister
  2287. // liveranges as partially dead values are allowed.
  2288. if (LaneMask.none() && !hasDeadDef) {
  2289. report("Instruction ending live segment on dead slot has no dead flag",
  2290. MI);
  2291. report_context(LR, Reg, LaneMask);
  2292. report_context(S);
  2293. }
  2294. } else {
  2295. if (!hasRead) {
  2296. // When tracking subregister liveness, the main range must start new
  2297. // values on partial register writes, even if there is no read.
  2298. if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
  2299. !hasSubRegDef) {
  2300. report("Instruction ending live segment doesn't read the register",
  2301. MI);
  2302. report_context(LR, Reg, LaneMask);
  2303. report_context(S);
  2304. }
  2305. }
  2306. }
  2307. }
  2308. // Now check all the basic blocks in this live segment.
  2309. MachineFunction::const_iterator MFI = MBB->getIterator();
  2310. // Is this live segment the beginning of a non-PHIDef VN?
  2311. if (S.start == VNI->def && !VNI->isPHIDef()) {
  2312. // Not live-in to any blocks.
  2313. if (MBB == EndMBB)
  2314. return;
  2315. // Skip this block.
  2316. ++MFI;
  2317. }
  2318. SmallVector<SlotIndex, 4> Undefs;
  2319. if (LaneMask.any()) {
  2320. LiveInterval &OwnerLI = LiveInts->getInterval(Reg);
  2321. OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
  2322. }
  2323. while (true) {
  2324. assert(LiveInts->isLiveInToMBB(LR, &*MFI));
  2325. // We don't know how to track physregs into a landing pad.
  2326. if (!Register::isVirtualRegister(Reg) && MFI->isEHPad()) {
  2327. if (&*MFI == EndMBB)
  2328. break;
  2329. ++MFI;
  2330. continue;
  2331. }
  2332. // Is VNI a PHI-def in the current block?
  2333. bool IsPHI = VNI->isPHIDef() &&
  2334. VNI->def == LiveInts->getMBBStartIdx(&*MFI);
  2335. // Check that VNI is live-out of all predecessors.
  2336. for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
  2337. PE = MFI->pred_end(); PI != PE; ++PI) {
  2338. SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
  2339. const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
  2340. // All predecessors must have a live-out value. However for a phi
  2341. // instruction with subregister intervals
  2342. // only one of the subregisters (not necessarily the current one) needs to
  2343. // be defined.
  2344. if (!PVNI && (LaneMask.none() || !IsPHI)) {
  2345. if (LiveRangeCalc::isJointlyDominated(*PI, Undefs, *Indexes))
  2346. continue;
  2347. report("Register not marked live out of predecessor", *PI);
  2348. report_context(LR, Reg, LaneMask);
  2349. report_context(*VNI);
  2350. errs() << " live into " << printMBBReference(*MFI) << '@'
  2351. << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
  2352. << PEnd << '\n';
  2353. continue;
  2354. }
  2355. // Only PHI-defs can take different predecessor values.
  2356. if (!IsPHI && PVNI != VNI) {
  2357. report("Different value live out of predecessor", *PI);
  2358. report_context(LR, Reg, LaneMask);
  2359. errs() << "Valno #" << PVNI->id << " live out of "
  2360. << printMBBReference(*(*PI)) << '@' << PEnd << "\nValno #"
  2361. << VNI->id << " live into " << printMBBReference(*MFI) << '@'
  2362. << LiveInts->getMBBStartIdx(&*MFI) << '\n';
  2363. }
  2364. }
  2365. if (&*MFI == EndMBB)
  2366. break;
  2367. ++MFI;
  2368. }
  2369. }
  2370. void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg,
  2371. LaneBitmask LaneMask) {
  2372. for (const VNInfo *VNI : LR.valnos)
  2373. verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
  2374. for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
  2375. verifyLiveRangeSegment(LR, I, Reg, LaneMask);
  2376. }
  2377. void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
  2378. unsigned Reg = LI.reg;
  2379. assert(Register::isVirtualRegister(Reg));
  2380. verifyLiveRange(LI, Reg);
  2381. LaneBitmask Mask;
  2382. LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
  2383. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  2384. if ((Mask & SR.LaneMask).any()) {
  2385. report("Lane masks of sub ranges overlap in live interval", MF);
  2386. report_context(LI);
  2387. }
  2388. if ((SR.LaneMask & ~MaxMask).any()) {
  2389. report("Subrange lanemask is invalid", MF);
  2390. report_context(LI);
  2391. }
  2392. if (SR.empty()) {
  2393. report("Subrange must not be empty", MF);
  2394. report_context(SR, LI.reg, SR.LaneMask);
  2395. }
  2396. Mask |= SR.LaneMask;
  2397. verifyLiveRange(SR, LI.reg, SR.LaneMask);
  2398. if (!LI.covers(SR)) {
  2399. report("A Subrange is not covered by the main range", MF);
  2400. report_context(LI);
  2401. }
  2402. }
  2403. // Check the LI only has one connected component.
  2404. ConnectedVNInfoEqClasses ConEQ(*LiveInts);
  2405. unsigned NumComp = ConEQ.Classify(LI);
  2406. if (NumComp > 1) {
  2407. report("Multiple connected components in live interval", MF);
  2408. report_context(LI);
  2409. for (unsigned comp = 0; comp != NumComp; ++comp) {
  2410. errs() << comp << ": valnos";
  2411. for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
  2412. E = LI.vni_end(); I!=E; ++I)
  2413. if (comp == ConEQ.getEqClass(*I))
  2414. errs() << ' ' << (*I)->id;
  2415. errs() << '\n';
  2416. }
  2417. }
  2418. }
  2419. namespace {
  2420. // FrameSetup and FrameDestroy can have zero adjustment, so using a single
  2421. // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
  2422. // value is zero.
  2423. // We use a bool plus an integer to capture the stack state.
  2424. struct StackStateOfBB {
  2425. StackStateOfBB() = default;
  2426. StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
  2427. EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
  2428. ExitIsSetup(ExitSetup) {}
  2429. // Can be negative, which means we are setting up a frame.
  2430. int EntryValue = 0;
  2431. int ExitValue = 0;
  2432. bool EntryIsSetup = false;
  2433. bool ExitIsSetup = false;
  2434. };
  2435. } // end anonymous namespace
  2436. /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
  2437. /// by a FrameDestroy <n>, stack adjustments are identical on all
  2438. /// CFG edges to a merge point, and frame is destroyed at end of a return block.
  2439. void MachineVerifier::verifyStackFrame() {
  2440. unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
  2441. unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
  2442. if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
  2443. return;
  2444. SmallVector<StackStateOfBB, 8> SPState;
  2445. SPState.resize(MF->getNumBlockIDs());
  2446. df_iterator_default_set<const MachineBasicBlock*> Reachable;
  2447. // Visit the MBBs in DFS order.
  2448. for (df_ext_iterator<const MachineFunction *,
  2449. df_iterator_default_set<const MachineBasicBlock *>>
  2450. DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
  2451. DFI != DFE; ++DFI) {
  2452. const MachineBasicBlock *MBB = *DFI;
  2453. StackStateOfBB BBState;
  2454. // Check the exit state of the DFS stack predecessor.
  2455. if (DFI.getPathLength() >= 2) {
  2456. const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
  2457. assert(Reachable.count(StackPred) &&
  2458. "DFS stack predecessor is already visited.\n");
  2459. BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
  2460. BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
  2461. BBState.ExitValue = BBState.EntryValue;
  2462. BBState.ExitIsSetup = BBState.EntryIsSetup;
  2463. }
  2464. // Update stack state by checking contents of MBB.
  2465. for (const auto &I : *MBB) {
  2466. if (I.getOpcode() == FrameSetupOpcode) {
  2467. if (BBState.ExitIsSetup)
  2468. report("FrameSetup is after another FrameSetup", &I);
  2469. BBState.ExitValue -= TII->getFrameTotalSize(I);
  2470. BBState.ExitIsSetup = true;
  2471. }
  2472. if (I.getOpcode() == FrameDestroyOpcode) {
  2473. int Size = TII->getFrameTotalSize(I);
  2474. if (!BBState.ExitIsSetup)
  2475. report("FrameDestroy is not after a FrameSetup", &I);
  2476. int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
  2477. BBState.ExitValue;
  2478. if (BBState.ExitIsSetup && AbsSPAdj != Size) {
  2479. report("FrameDestroy <n> is after FrameSetup <m>", &I);
  2480. errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
  2481. << AbsSPAdj << ">.\n";
  2482. }
  2483. BBState.ExitValue += Size;
  2484. BBState.ExitIsSetup = false;
  2485. }
  2486. }
  2487. SPState[MBB->getNumber()] = BBState;
  2488. // Make sure the exit state of any predecessor is consistent with the entry
  2489. // state.
  2490. for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
  2491. E = MBB->pred_end(); I != E; ++I) {
  2492. if (Reachable.count(*I) &&
  2493. (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
  2494. SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
  2495. report("The exit stack state of a predecessor is inconsistent.", MBB);
  2496. errs() << "Predecessor " << printMBBReference(*(*I))
  2497. << " has exit state (" << SPState[(*I)->getNumber()].ExitValue
  2498. << ", " << SPState[(*I)->getNumber()].ExitIsSetup << "), while "
  2499. << printMBBReference(*MBB) << " has entry state ("
  2500. << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
  2501. }
  2502. }
  2503. // Make sure the entry state of any successor is consistent with the exit
  2504. // state.
  2505. for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
  2506. E = MBB->succ_end(); I != E; ++I) {
  2507. if (Reachable.count(*I) &&
  2508. (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
  2509. SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
  2510. report("The entry stack state of a successor is inconsistent.", MBB);
  2511. errs() << "Successor " << printMBBReference(*(*I))
  2512. << " has entry state (" << SPState[(*I)->getNumber()].EntryValue
  2513. << ", " << SPState[(*I)->getNumber()].EntryIsSetup << "), while "
  2514. << printMBBReference(*MBB) << " has exit state ("
  2515. << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
  2516. }
  2517. }
  2518. // Make sure a basic block with return ends with zero stack adjustment.
  2519. if (!MBB->empty() && MBB->back().isReturn()) {
  2520. if (BBState.ExitIsSetup)
  2521. report("A return block ends with a FrameSetup.", MBB);
  2522. if (BBState.ExitValue)
  2523. report("A return block ends with a nonzero stack adjustment.", MBB);
  2524. }
  2525. }
  2526. }