MachineInstr.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  1. //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
  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. // Methods common to all machine instructions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/MachineInstr.h"
  13. #include "llvm/ADT/APFloat.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/FoldingSet.h"
  16. #include "llvm/ADT/Hashing.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallBitVector.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/Analysis/Loads.h"
  24. #include "llvm/Analysis/MemoryLocation.h"
  25. #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
  26. #include "llvm/CodeGen/MachineBasicBlock.h"
  27. #include "llvm/CodeGen/MachineFrameInfo.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineInstrBuilder.h"
  30. #include "llvm/CodeGen/MachineInstrBundle.h"
  31. #include "llvm/CodeGen/MachineMemOperand.h"
  32. #include "llvm/CodeGen/MachineModuleInfo.h"
  33. #include "llvm/CodeGen/MachineOperand.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/PseudoSourceValue.h"
  36. #include "llvm/CodeGen/TargetInstrInfo.h"
  37. #include "llvm/CodeGen/TargetRegisterInfo.h"
  38. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  39. #include "llvm/Config/llvm-config.h"
  40. #include "llvm/IR/Constants.h"
  41. #include "llvm/IR/DebugInfoMetadata.h"
  42. #include "llvm/IR/DebugLoc.h"
  43. #include "llvm/IR/DerivedTypes.h"
  44. #include "llvm/IR/Function.h"
  45. #include "llvm/IR/InlineAsm.h"
  46. #include "llvm/IR/InstrTypes.h"
  47. #include "llvm/IR/Intrinsics.h"
  48. #include "llvm/IR/LLVMContext.h"
  49. #include "llvm/IR/Metadata.h"
  50. #include "llvm/IR/Module.h"
  51. #include "llvm/IR/ModuleSlotTracker.h"
  52. #include "llvm/IR/Operator.h"
  53. #include "llvm/IR/Type.h"
  54. #include "llvm/IR/Value.h"
  55. #include "llvm/MC/MCInstrDesc.h"
  56. #include "llvm/MC/MCRegisterInfo.h"
  57. #include "llvm/MC/MCSymbol.h"
  58. #include "llvm/Support/Casting.h"
  59. #include "llvm/Support/CommandLine.h"
  60. #include "llvm/Support/Compiler.h"
  61. #include "llvm/Support/Debug.h"
  62. #include "llvm/Support/ErrorHandling.h"
  63. #include "llvm/Support/LowLevelTypeImpl.h"
  64. #include "llvm/Support/MathExtras.h"
  65. #include "llvm/Support/raw_ostream.h"
  66. #include "llvm/Target/TargetIntrinsicInfo.h"
  67. #include "llvm/Target/TargetMachine.h"
  68. #include <algorithm>
  69. #include <cassert>
  70. #include <cstddef>
  71. #include <cstdint>
  72. #include <cstring>
  73. #include <iterator>
  74. #include <utility>
  75. using namespace llvm;
  76. static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) {
  77. if (const MachineBasicBlock *MBB = MI.getParent())
  78. if (const MachineFunction *MF = MBB->getParent())
  79. return MF;
  80. return nullptr;
  81. }
  82. // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
  83. // it.
  84. static void tryToGetTargetInfo(const MachineInstr &MI,
  85. const TargetRegisterInfo *&TRI,
  86. const MachineRegisterInfo *&MRI,
  87. const TargetIntrinsicInfo *&IntrinsicInfo,
  88. const TargetInstrInfo *&TII) {
  89. if (const MachineFunction *MF = getMFIfAvailable(MI)) {
  90. TRI = MF->getSubtarget().getRegisterInfo();
  91. MRI = &MF->getRegInfo();
  92. IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
  93. TII = MF->getSubtarget().getInstrInfo();
  94. }
  95. }
  96. void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
  97. if (MCID->ImplicitDefs)
  98. for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
  99. ++ImpDefs)
  100. addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
  101. if (MCID->ImplicitUses)
  102. for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
  103. ++ImpUses)
  104. addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
  105. }
  106. /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
  107. /// implicit operands. It reserves space for the number of operands specified by
  108. /// the MCInstrDesc.
  109. MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
  110. DebugLoc dl, bool NoImp)
  111. : MCID(&tid), debugLoc(std::move(dl)) {
  112. assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
  113. // Reserve space for the expected number of operands.
  114. if (unsigned NumOps = MCID->getNumOperands() +
  115. MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
  116. CapOperands = OperandCapacity::get(NumOps);
  117. Operands = MF.allocateOperandArray(CapOperands);
  118. }
  119. if (!NoImp)
  120. addImplicitDefUseOperands(MF);
  121. }
  122. /// MachineInstr ctor - Copies MachineInstr arg exactly
  123. ///
  124. MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
  125. : MCID(&MI.getDesc()), Info(MI.Info), debugLoc(MI.getDebugLoc()) {
  126. assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
  127. CapOperands = OperandCapacity::get(MI.getNumOperands());
  128. Operands = MF.allocateOperandArray(CapOperands);
  129. // Copy operands.
  130. for (const MachineOperand &MO : MI.operands())
  131. addOperand(MF, MO);
  132. // Copy all the sensible flags.
  133. setFlags(MI.Flags);
  134. }
  135. /// getRegInfo - If this instruction is embedded into a MachineFunction,
  136. /// return the MachineRegisterInfo object for the current function, otherwise
  137. /// return null.
  138. MachineRegisterInfo *MachineInstr::getRegInfo() {
  139. if (MachineBasicBlock *MBB = getParent())
  140. return &MBB->getParent()->getRegInfo();
  141. return nullptr;
  142. }
  143. /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
  144. /// this instruction from their respective use lists. This requires that the
  145. /// operands already be on their use lists.
  146. void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
  147. for (MachineOperand &MO : operands())
  148. if (MO.isReg())
  149. MRI.removeRegOperandFromUseList(&MO);
  150. }
  151. /// AddRegOperandsToUseLists - Add all of the register operands in
  152. /// this instruction from their respective use lists. This requires that the
  153. /// operands not be on their use lists yet.
  154. void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
  155. for (MachineOperand &MO : operands())
  156. if (MO.isReg())
  157. MRI.addRegOperandToUseList(&MO);
  158. }
  159. void MachineInstr::addOperand(const MachineOperand &Op) {
  160. MachineBasicBlock *MBB = getParent();
  161. assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
  162. MachineFunction *MF = MBB->getParent();
  163. assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
  164. addOperand(*MF, Op);
  165. }
  166. /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
  167. /// ranges. If MRI is non-null also update use-def chains.
  168. static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
  169. unsigned NumOps, MachineRegisterInfo *MRI) {
  170. if (MRI)
  171. return MRI->moveOperands(Dst, Src, NumOps);
  172. // MachineOperand is a trivially copyable type so we can just use memmove.
  173. std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
  174. }
  175. /// addOperand - Add the specified operand to the instruction. If it is an
  176. /// implicit operand, it is added to the end of the operand list. If it is
  177. /// an explicit operand it is added at the end of the explicit operand list
  178. /// (before the first implicit operand).
  179. void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
  180. assert(MCID && "Cannot add operands before providing an instr descriptor");
  181. // Check if we're adding one of our existing operands.
  182. if (&Op >= Operands && &Op < Operands + NumOperands) {
  183. // This is unusual: MI->addOperand(MI->getOperand(i)).
  184. // If adding Op requires reallocating or moving existing operands around,
  185. // the Op reference could go stale. Support it by copying Op.
  186. MachineOperand CopyOp(Op);
  187. return addOperand(MF, CopyOp);
  188. }
  189. // Find the insert location for the new operand. Implicit registers go at
  190. // the end, everything else goes before the implicit regs.
  191. //
  192. // FIXME: Allow mixed explicit and implicit operands on inline asm.
  193. // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
  194. // implicit-defs, but they must not be moved around. See the FIXME in
  195. // InstrEmitter.cpp.
  196. unsigned OpNo = getNumOperands();
  197. bool isImpReg = Op.isReg() && Op.isImplicit();
  198. if (!isImpReg && !isInlineAsm()) {
  199. while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
  200. --OpNo;
  201. assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
  202. }
  203. }
  204. #ifndef NDEBUG
  205. bool isDebugOp = Op.getType() == MachineOperand::MO_Metadata ||
  206. Op.getType() == MachineOperand::MO_MCSymbol;
  207. // OpNo now points as the desired insertion point. Unless this is a variadic
  208. // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
  209. // RegMask operands go between the explicit and implicit operands.
  210. assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
  211. OpNo < MCID->getNumOperands() || isDebugOp) &&
  212. "Trying to add an operand to a machine instr that is already done!");
  213. #endif
  214. MachineRegisterInfo *MRI = getRegInfo();
  215. // Determine if the Operands array needs to be reallocated.
  216. // Save the old capacity and operand array.
  217. OperandCapacity OldCap = CapOperands;
  218. MachineOperand *OldOperands = Operands;
  219. if (!OldOperands || OldCap.getSize() == getNumOperands()) {
  220. CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
  221. Operands = MF.allocateOperandArray(CapOperands);
  222. // Move the operands before the insertion point.
  223. if (OpNo)
  224. moveOperands(Operands, OldOperands, OpNo, MRI);
  225. }
  226. // Move the operands following the insertion point.
  227. if (OpNo != NumOperands)
  228. moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
  229. MRI);
  230. ++NumOperands;
  231. // Deallocate the old operand array.
  232. if (OldOperands != Operands && OldOperands)
  233. MF.deallocateOperandArray(OldCap, OldOperands);
  234. // Copy Op into place. It still needs to be inserted into the MRI use lists.
  235. MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
  236. NewMO->ParentMI = this;
  237. // When adding a register operand, tell MRI about it.
  238. if (NewMO->isReg()) {
  239. // Ensure isOnRegUseList() returns false, regardless of Op's status.
  240. NewMO->Contents.Reg.Prev = nullptr;
  241. // Ignore existing ties. This is not a property that can be copied.
  242. NewMO->TiedTo = 0;
  243. // Add the new operand to MRI, but only for instructions in an MBB.
  244. if (MRI)
  245. MRI->addRegOperandToUseList(NewMO);
  246. // The MCID operand information isn't accurate until we start adding
  247. // explicit operands. The implicit operands are added first, then the
  248. // explicits are inserted before them.
  249. if (!isImpReg) {
  250. // Tie uses to defs as indicated in MCInstrDesc.
  251. if (NewMO->isUse()) {
  252. int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
  253. if (DefIdx != -1)
  254. tieOperands(DefIdx, OpNo);
  255. }
  256. // If the register operand is flagged as early, mark the operand as such.
  257. if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
  258. NewMO->setIsEarlyClobber(true);
  259. }
  260. }
  261. }
  262. /// RemoveOperand - Erase an operand from an instruction, leaving it with one
  263. /// fewer operand than it started with.
  264. ///
  265. void MachineInstr::RemoveOperand(unsigned OpNo) {
  266. assert(OpNo < getNumOperands() && "Invalid operand number");
  267. untieRegOperand(OpNo);
  268. #ifndef NDEBUG
  269. // Moving tied operands would break the ties.
  270. for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
  271. if (Operands[i].isReg())
  272. assert(!Operands[i].isTied() && "Cannot move tied operands");
  273. #endif
  274. MachineRegisterInfo *MRI = getRegInfo();
  275. if (MRI && Operands[OpNo].isReg())
  276. MRI->removeRegOperandFromUseList(Operands + OpNo);
  277. // Don't call the MachineOperand destructor. A lot of this code depends on
  278. // MachineOperand having a trivial destructor anyway, and adding a call here
  279. // wouldn't make it 'destructor-correct'.
  280. if (unsigned N = NumOperands - 1 - OpNo)
  281. moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
  282. --NumOperands;
  283. }
  284. void MachineInstr::dropMemRefs(MachineFunction &MF) {
  285. if (memoperands_empty())
  286. return;
  287. // See if we can just drop all of our extra info.
  288. if (!getPreInstrSymbol() && !getPostInstrSymbol()) {
  289. Info.clear();
  290. return;
  291. }
  292. if (!getPostInstrSymbol()) {
  293. Info.set<EIIK_PreInstrSymbol>(getPreInstrSymbol());
  294. return;
  295. }
  296. if (!getPreInstrSymbol()) {
  297. Info.set<EIIK_PostInstrSymbol>(getPostInstrSymbol());
  298. return;
  299. }
  300. // Otherwise allocate a fresh extra info with just these symbols.
  301. Info.set<EIIK_OutOfLine>(
  302. MF.createMIExtraInfo({}, getPreInstrSymbol(), getPostInstrSymbol()));
  303. }
  304. void MachineInstr::setMemRefs(MachineFunction &MF,
  305. ArrayRef<MachineMemOperand *> MMOs) {
  306. if (MMOs.empty()) {
  307. dropMemRefs(MF);
  308. return;
  309. }
  310. // Try to store a single MMO inline.
  311. if (MMOs.size() == 1 && !getPreInstrSymbol() && !getPostInstrSymbol()) {
  312. Info.set<EIIK_MMO>(MMOs[0]);
  313. return;
  314. }
  315. // Otherwise create an extra info struct with all of our info.
  316. Info.set<EIIK_OutOfLine>(
  317. MF.createMIExtraInfo(MMOs, getPreInstrSymbol(), getPostInstrSymbol()));
  318. }
  319. void MachineInstr::addMemOperand(MachineFunction &MF,
  320. MachineMemOperand *MO) {
  321. SmallVector<MachineMemOperand *, 2> MMOs;
  322. MMOs.append(memoperands_begin(), memoperands_end());
  323. MMOs.push_back(MO);
  324. setMemRefs(MF, MMOs);
  325. }
  326. void MachineInstr::cloneMemRefs(MachineFunction &MF, const MachineInstr &MI) {
  327. if (this == &MI)
  328. // Nothing to do for a self-clone!
  329. return;
  330. assert(&MF == MI.getMF() &&
  331. "Invalid machine functions when cloning memory refrences!");
  332. // See if we can just steal the extra info already allocated for the
  333. // instruction. We can do this whenever the pre- and post-instruction symbols
  334. // are the same (including null).
  335. if (getPreInstrSymbol() == MI.getPreInstrSymbol() &&
  336. getPostInstrSymbol() == MI.getPostInstrSymbol()) {
  337. Info = MI.Info;
  338. return;
  339. }
  340. // Otherwise, fall back on a copy-based clone.
  341. setMemRefs(MF, MI.memoperands());
  342. }
  343. /// Check to see if the MMOs pointed to by the two MemRefs arrays are
  344. /// identical.
  345. static bool hasIdenticalMMOs(ArrayRef<MachineMemOperand *> LHS,
  346. ArrayRef<MachineMemOperand *> RHS) {
  347. if (LHS.size() != RHS.size())
  348. return false;
  349. auto LHSPointees = make_pointee_range(LHS);
  350. auto RHSPointees = make_pointee_range(RHS);
  351. return std::equal(LHSPointees.begin(), LHSPointees.end(),
  352. RHSPointees.begin());
  353. }
  354. void MachineInstr::cloneMergedMemRefs(MachineFunction &MF,
  355. ArrayRef<const MachineInstr *> MIs) {
  356. // Try handling easy numbers of MIs with simpler mechanisms.
  357. if (MIs.empty()) {
  358. dropMemRefs(MF);
  359. return;
  360. }
  361. if (MIs.size() == 1) {
  362. cloneMemRefs(MF, *MIs[0]);
  363. return;
  364. }
  365. // Because an empty memoperands list provides *no* information and must be
  366. // handled conservatively (assuming the instruction can do anything), the only
  367. // way to merge with it is to drop all other memoperands.
  368. if (MIs[0]->memoperands_empty()) {
  369. dropMemRefs(MF);
  370. return;
  371. }
  372. // Handle the general case.
  373. SmallVector<MachineMemOperand *, 2> MergedMMOs;
  374. // Start with the first instruction.
  375. assert(&MF == MIs[0]->getMF() &&
  376. "Invalid machine functions when cloning memory references!");
  377. MergedMMOs.append(MIs[0]->memoperands_begin(), MIs[0]->memoperands_end());
  378. // Now walk all the other instructions and accumulate any different MMOs.
  379. for (const MachineInstr &MI : make_pointee_range(MIs.slice(1))) {
  380. assert(&MF == MI.getMF() &&
  381. "Invalid machine functions when cloning memory references!");
  382. // Skip MIs with identical operands to the first. This is a somewhat
  383. // arbitrary hack but will catch common cases without being quadratic.
  384. // TODO: We could fully implement merge semantics here if needed.
  385. if (hasIdenticalMMOs(MIs[0]->memoperands(), MI.memoperands()))
  386. continue;
  387. // Because an empty memoperands list provides *no* information and must be
  388. // handled conservatively (assuming the instruction can do anything), the
  389. // only way to merge with it is to drop all other memoperands.
  390. if (MI.memoperands_empty()) {
  391. dropMemRefs(MF);
  392. return;
  393. }
  394. // Otherwise accumulate these into our temporary buffer of the merged state.
  395. MergedMMOs.append(MI.memoperands_begin(), MI.memoperands_end());
  396. }
  397. setMemRefs(MF, MergedMMOs);
  398. }
  399. void MachineInstr::setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
  400. MCSymbol *OldSymbol = getPreInstrSymbol();
  401. if (OldSymbol == Symbol)
  402. return;
  403. if (OldSymbol && !Symbol) {
  404. // We're removing a symbol rather than adding one. Try to clean up any
  405. // extra info carried around.
  406. if (Info.is<EIIK_PreInstrSymbol>()) {
  407. Info.clear();
  408. return;
  409. }
  410. if (memoperands_empty()) {
  411. assert(getPostInstrSymbol() &&
  412. "Should never have only a single symbol allocated out-of-line!");
  413. Info.set<EIIK_PostInstrSymbol>(getPostInstrSymbol());
  414. return;
  415. }
  416. // Otherwise fallback on the generic update.
  417. } else if (!Info || Info.is<EIIK_PreInstrSymbol>()) {
  418. // If we don't have any other extra info, we can store this inline.
  419. Info.set<EIIK_PreInstrSymbol>(Symbol);
  420. return;
  421. }
  422. // Otherwise, allocate a full new set of extra info.
  423. // FIXME: Maybe we should make the symbols in the extra info mutable?
  424. Info.set<EIIK_OutOfLine>(
  425. MF.createMIExtraInfo(memoperands(), Symbol, getPostInstrSymbol()));
  426. }
  427. void MachineInstr::setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
  428. MCSymbol *OldSymbol = getPostInstrSymbol();
  429. if (OldSymbol == Symbol)
  430. return;
  431. if (OldSymbol && !Symbol) {
  432. // We're removing a symbol rather than adding one. Try to clean up any
  433. // extra info carried around.
  434. if (Info.is<EIIK_PostInstrSymbol>()) {
  435. Info.clear();
  436. return;
  437. }
  438. if (memoperands_empty()) {
  439. assert(getPreInstrSymbol() &&
  440. "Should never have only a single symbol allocated out-of-line!");
  441. Info.set<EIIK_PreInstrSymbol>(getPreInstrSymbol());
  442. return;
  443. }
  444. // Otherwise fallback on the generic update.
  445. } else if (!Info || Info.is<EIIK_PostInstrSymbol>()) {
  446. // If we don't have any other extra info, we can store this inline.
  447. Info.set<EIIK_PostInstrSymbol>(Symbol);
  448. return;
  449. }
  450. // Otherwise, allocate a full new set of extra info.
  451. // FIXME: Maybe we should make the symbols in the extra info mutable?
  452. Info.set<EIIK_OutOfLine>(
  453. MF.createMIExtraInfo(memoperands(), getPreInstrSymbol(), Symbol));
  454. }
  455. uint16_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
  456. // For now, the just return the union of the flags. If the flags get more
  457. // complicated over time, we might need more logic here.
  458. return getFlags() | Other.getFlags();
  459. }
  460. uint16_t MachineInstr::copyFlagsFromInstruction(const Instruction &I) {
  461. uint16_t MIFlags = 0;
  462. // Copy the wrapping flags.
  463. if (const OverflowingBinaryOperator *OB =
  464. dyn_cast<OverflowingBinaryOperator>(&I)) {
  465. if (OB->hasNoSignedWrap())
  466. MIFlags |= MachineInstr::MIFlag::NoSWrap;
  467. if (OB->hasNoUnsignedWrap())
  468. MIFlags |= MachineInstr::MIFlag::NoUWrap;
  469. }
  470. // Copy the exact flag.
  471. if (const PossiblyExactOperator *PE = dyn_cast<PossiblyExactOperator>(&I))
  472. if (PE->isExact())
  473. MIFlags |= MachineInstr::MIFlag::IsExact;
  474. // Copy the fast-math flags.
  475. if (const FPMathOperator *FP = dyn_cast<FPMathOperator>(&I)) {
  476. const FastMathFlags Flags = FP->getFastMathFlags();
  477. if (Flags.noNaNs())
  478. MIFlags |= MachineInstr::MIFlag::FmNoNans;
  479. if (Flags.noInfs())
  480. MIFlags |= MachineInstr::MIFlag::FmNoInfs;
  481. if (Flags.noSignedZeros())
  482. MIFlags |= MachineInstr::MIFlag::FmNsz;
  483. if (Flags.allowReciprocal())
  484. MIFlags |= MachineInstr::MIFlag::FmArcp;
  485. if (Flags.allowContract())
  486. MIFlags |= MachineInstr::MIFlag::FmContract;
  487. if (Flags.approxFunc())
  488. MIFlags |= MachineInstr::MIFlag::FmAfn;
  489. if (Flags.allowReassoc())
  490. MIFlags |= MachineInstr::MIFlag::FmReassoc;
  491. }
  492. return MIFlags;
  493. }
  494. void MachineInstr::copyIRFlags(const Instruction &I) {
  495. Flags = copyFlagsFromInstruction(I);
  496. }
  497. bool MachineInstr::hasPropertyInBundle(uint64_t Mask, QueryType Type) const {
  498. assert(!isBundledWithPred() && "Must be called on bundle header");
  499. for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
  500. if (MII->getDesc().getFlags() & Mask) {
  501. if (Type == AnyInBundle)
  502. return true;
  503. } else {
  504. if (Type == AllInBundle && !MII->isBundle())
  505. return false;
  506. }
  507. // This was the last instruction in the bundle.
  508. if (!MII->isBundledWithSucc())
  509. return Type == AllInBundle;
  510. }
  511. }
  512. bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
  513. MICheckType Check) const {
  514. // If opcodes or number of operands are not the same then the two
  515. // instructions are obviously not identical.
  516. if (Other.getOpcode() != getOpcode() ||
  517. Other.getNumOperands() != getNumOperands())
  518. return false;
  519. if (isBundle()) {
  520. // We have passed the test above that both instructions have the same
  521. // opcode, so we know that both instructions are bundles here. Let's compare
  522. // MIs inside the bundle.
  523. assert(Other.isBundle() && "Expected that both instructions are bundles.");
  524. MachineBasicBlock::const_instr_iterator I1 = getIterator();
  525. MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
  526. // Loop until we analysed the last intruction inside at least one of the
  527. // bundles.
  528. while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
  529. ++I1;
  530. ++I2;
  531. if (!I1->isIdenticalTo(*I2, Check))
  532. return false;
  533. }
  534. // If we've reached the end of just one of the two bundles, but not both,
  535. // the instructions are not identical.
  536. if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
  537. return false;
  538. }
  539. // Check operands to make sure they match.
  540. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  541. const MachineOperand &MO = getOperand(i);
  542. const MachineOperand &OMO = Other.getOperand(i);
  543. if (!MO.isReg()) {
  544. if (!MO.isIdenticalTo(OMO))
  545. return false;
  546. continue;
  547. }
  548. // Clients may or may not want to ignore defs when testing for equality.
  549. // For example, machine CSE pass only cares about finding common
  550. // subexpressions, so it's safe to ignore virtual register defs.
  551. if (MO.isDef()) {
  552. if (Check == IgnoreDefs)
  553. continue;
  554. else if (Check == IgnoreVRegDefs) {
  555. if (!TargetRegisterInfo::isVirtualRegister(MO.getReg()) ||
  556. !TargetRegisterInfo::isVirtualRegister(OMO.getReg()))
  557. if (!MO.isIdenticalTo(OMO))
  558. return false;
  559. } else {
  560. if (!MO.isIdenticalTo(OMO))
  561. return false;
  562. if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
  563. return false;
  564. }
  565. } else {
  566. if (!MO.isIdenticalTo(OMO))
  567. return false;
  568. if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
  569. return false;
  570. }
  571. }
  572. // If DebugLoc does not match then two debug instructions are not identical.
  573. if (isDebugInstr())
  574. if (getDebugLoc() && Other.getDebugLoc() &&
  575. getDebugLoc() != Other.getDebugLoc())
  576. return false;
  577. return true;
  578. }
  579. const MachineFunction *MachineInstr::getMF() const {
  580. return getParent()->getParent();
  581. }
  582. MachineInstr *MachineInstr::removeFromParent() {
  583. assert(getParent() && "Not embedded in a basic block!");
  584. return getParent()->remove(this);
  585. }
  586. MachineInstr *MachineInstr::removeFromBundle() {
  587. assert(getParent() && "Not embedded in a basic block!");
  588. return getParent()->remove_instr(this);
  589. }
  590. void MachineInstr::eraseFromParent() {
  591. assert(getParent() && "Not embedded in a basic block!");
  592. getParent()->erase(this);
  593. }
  594. void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
  595. assert(getParent() && "Not embedded in a basic block!");
  596. MachineBasicBlock *MBB = getParent();
  597. MachineFunction *MF = MBB->getParent();
  598. assert(MF && "Not embedded in a function!");
  599. MachineInstr *MI = (MachineInstr *)this;
  600. MachineRegisterInfo &MRI = MF->getRegInfo();
  601. for (const MachineOperand &MO : MI->operands()) {
  602. if (!MO.isReg() || !MO.isDef())
  603. continue;
  604. unsigned Reg = MO.getReg();
  605. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  606. continue;
  607. MRI.markUsesInDebugValueAsUndef(Reg);
  608. }
  609. MI->eraseFromParent();
  610. }
  611. void MachineInstr::eraseFromBundle() {
  612. assert(getParent() && "Not embedded in a basic block!");
  613. getParent()->erase_instr(this);
  614. }
  615. unsigned MachineInstr::getNumExplicitOperands() const {
  616. unsigned NumOperands = MCID->getNumOperands();
  617. if (!MCID->isVariadic())
  618. return NumOperands;
  619. for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) {
  620. const MachineOperand &MO = getOperand(I);
  621. // The operands must always be in the following order:
  622. // - explicit reg defs,
  623. // - other explicit operands (reg uses, immediates, etc.),
  624. // - implicit reg defs
  625. // - implicit reg uses
  626. if (MO.isReg() && MO.isImplicit())
  627. break;
  628. ++NumOperands;
  629. }
  630. return NumOperands;
  631. }
  632. unsigned MachineInstr::getNumExplicitDefs() const {
  633. unsigned NumDefs = MCID->getNumDefs();
  634. if (!MCID->isVariadic())
  635. return NumDefs;
  636. for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) {
  637. const MachineOperand &MO = getOperand(I);
  638. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  639. break;
  640. ++NumDefs;
  641. }
  642. return NumDefs;
  643. }
  644. void MachineInstr::bundleWithPred() {
  645. assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
  646. setFlag(BundledPred);
  647. MachineBasicBlock::instr_iterator Pred = getIterator();
  648. --Pred;
  649. assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  650. Pred->setFlag(BundledSucc);
  651. }
  652. void MachineInstr::bundleWithSucc() {
  653. assert(!isBundledWithSucc() && "MI is already bundled with its successor");
  654. setFlag(BundledSucc);
  655. MachineBasicBlock::instr_iterator Succ = getIterator();
  656. ++Succ;
  657. assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
  658. Succ->setFlag(BundledPred);
  659. }
  660. void MachineInstr::unbundleFromPred() {
  661. assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
  662. clearFlag(BundledPred);
  663. MachineBasicBlock::instr_iterator Pred = getIterator();
  664. --Pred;
  665. assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  666. Pred->clearFlag(BundledSucc);
  667. }
  668. void MachineInstr::unbundleFromSucc() {
  669. assert(isBundledWithSucc() && "MI isn't bundled with its successor");
  670. clearFlag(BundledSucc);
  671. MachineBasicBlock::instr_iterator Succ = getIterator();
  672. ++Succ;
  673. assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
  674. Succ->clearFlag(BundledPred);
  675. }
  676. bool MachineInstr::isStackAligningInlineAsm() const {
  677. if (isInlineAsm()) {
  678. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  679. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  680. return true;
  681. }
  682. return false;
  683. }
  684. InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
  685. assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
  686. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  687. return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
  688. }
  689. int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
  690. unsigned *GroupNo) const {
  691. assert(isInlineAsm() && "Expected an inline asm instruction");
  692. assert(OpIdx < getNumOperands() && "OpIdx out of range");
  693. // Ignore queries about the initial operands.
  694. if (OpIdx < InlineAsm::MIOp_FirstOperand)
  695. return -1;
  696. unsigned Group = 0;
  697. unsigned NumOps;
  698. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  699. i += NumOps) {
  700. const MachineOperand &FlagMO = getOperand(i);
  701. // If we reach the implicit register operands, stop looking.
  702. if (!FlagMO.isImm())
  703. return -1;
  704. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  705. if (i + NumOps > OpIdx) {
  706. if (GroupNo)
  707. *GroupNo = Group;
  708. return i;
  709. }
  710. ++Group;
  711. }
  712. return -1;
  713. }
  714. const DILabel *MachineInstr::getDebugLabel() const {
  715. assert(isDebugLabel() && "not a DBG_LABEL");
  716. return cast<DILabel>(getOperand(0).getMetadata());
  717. }
  718. const DILocalVariable *MachineInstr::getDebugVariable() const {
  719. assert(isDebugValue() && "not a DBG_VALUE");
  720. return cast<DILocalVariable>(getOperand(2).getMetadata());
  721. }
  722. const DIExpression *MachineInstr::getDebugExpression() const {
  723. assert(isDebugValue() && "not a DBG_VALUE");
  724. return cast<DIExpression>(getOperand(3).getMetadata());
  725. }
  726. const TargetRegisterClass*
  727. MachineInstr::getRegClassConstraint(unsigned OpIdx,
  728. const TargetInstrInfo *TII,
  729. const TargetRegisterInfo *TRI) const {
  730. assert(getParent() && "Can't have an MBB reference here!");
  731. assert(getMF() && "Can't have an MF reference here!");
  732. const MachineFunction &MF = *getMF();
  733. // Most opcodes have fixed constraints in their MCInstrDesc.
  734. if (!isInlineAsm())
  735. return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
  736. if (!getOperand(OpIdx).isReg())
  737. return nullptr;
  738. // For tied uses on inline asm, get the constraint from the def.
  739. unsigned DefIdx;
  740. if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
  741. OpIdx = DefIdx;
  742. // Inline asm stores register class constraints in the flag word.
  743. int FlagIdx = findInlineAsmFlagIdx(OpIdx);
  744. if (FlagIdx < 0)
  745. return nullptr;
  746. unsigned Flag = getOperand(FlagIdx).getImm();
  747. unsigned RCID;
  748. if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
  749. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
  750. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
  751. InlineAsm::hasRegClassConstraint(Flag, RCID))
  752. return TRI->getRegClass(RCID);
  753. // Assume that all registers in a memory operand are pointers.
  754. if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
  755. return TRI->getPointerRegClass(MF);
  756. return nullptr;
  757. }
  758. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
  759. unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
  760. const TargetRegisterInfo *TRI, bool ExploreBundle) const {
  761. // Check every operands inside the bundle if we have
  762. // been asked to.
  763. if (ExploreBundle)
  764. for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
  765. ++OpndIt)
  766. CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
  767. OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
  768. else
  769. // Otherwise, just check the current operands.
  770. for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
  771. CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
  772. return CurRC;
  773. }
  774. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
  775. unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
  776. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  777. assert(CurRC && "Invalid initial register class");
  778. // Check if Reg is constrained by some of its use/def from MI.
  779. const MachineOperand &MO = getOperand(OpIdx);
  780. if (!MO.isReg() || MO.getReg() != Reg)
  781. return CurRC;
  782. // If yes, accumulate the constraints through the operand.
  783. return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
  784. }
  785. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
  786. unsigned OpIdx, const TargetRegisterClass *CurRC,
  787. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  788. const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
  789. const MachineOperand &MO = getOperand(OpIdx);
  790. assert(MO.isReg() &&
  791. "Cannot get register constraints for non-register operand");
  792. assert(CurRC && "Invalid initial register class");
  793. if (unsigned SubIdx = MO.getSubReg()) {
  794. if (OpRC)
  795. CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
  796. else
  797. CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
  798. } else if (OpRC)
  799. CurRC = TRI->getCommonSubClass(CurRC, OpRC);
  800. return CurRC;
  801. }
  802. /// Return the number of instructions inside the MI bundle, not counting the
  803. /// header instruction.
  804. unsigned MachineInstr::getBundleSize() const {
  805. MachineBasicBlock::const_instr_iterator I = getIterator();
  806. unsigned Size = 0;
  807. while (I->isBundledWithSucc()) {
  808. ++Size;
  809. ++I;
  810. }
  811. return Size;
  812. }
  813. /// Returns true if the MachineInstr has an implicit-use operand of exactly
  814. /// the given register (not considering sub/super-registers).
  815. bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
  816. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  817. const MachineOperand &MO = getOperand(i);
  818. if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
  819. return true;
  820. }
  821. return false;
  822. }
  823. /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
  824. /// the specific register or -1 if it is not found. It further tightens
  825. /// the search criteria to a use that kills the register if isKill is true.
  826. int MachineInstr::findRegisterUseOperandIdx(
  827. unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
  828. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  829. const MachineOperand &MO = getOperand(i);
  830. if (!MO.isReg() || !MO.isUse())
  831. continue;
  832. unsigned MOReg = MO.getReg();
  833. if (!MOReg)
  834. continue;
  835. if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg)))
  836. if (!isKill || MO.isKill())
  837. return i;
  838. }
  839. return -1;
  840. }
  841. /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
  842. /// indicating if this instruction reads or writes Reg. This also considers
  843. /// partial defines.
  844. std::pair<bool,bool>
  845. MachineInstr::readsWritesVirtualRegister(unsigned Reg,
  846. SmallVectorImpl<unsigned> *Ops) const {
  847. bool PartDef = false; // Partial redefine.
  848. bool FullDef = false; // Full define.
  849. bool Use = false;
  850. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  851. const MachineOperand &MO = getOperand(i);
  852. if (!MO.isReg() || MO.getReg() != Reg)
  853. continue;
  854. if (Ops)
  855. Ops->push_back(i);
  856. if (MO.isUse())
  857. Use |= !MO.isUndef();
  858. else if (MO.getSubReg() && !MO.isUndef())
  859. // A partial def undef doesn't count as reading the register.
  860. PartDef = true;
  861. else
  862. FullDef = true;
  863. }
  864. // A partial redefine uses Reg unless there is also a full define.
  865. return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
  866. }
  867. /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
  868. /// the specified register or -1 if it is not found. If isDead is true, defs
  869. /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
  870. /// also checks if there is a def of a super-register.
  871. int
  872. MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
  873. const TargetRegisterInfo *TRI) const {
  874. bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
  875. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  876. const MachineOperand &MO = getOperand(i);
  877. // Accept regmask operands when Overlap is set.
  878. // Ignore them when looking for a specific def operand (Overlap == false).
  879. if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
  880. return i;
  881. if (!MO.isReg() || !MO.isDef())
  882. continue;
  883. unsigned MOReg = MO.getReg();
  884. bool Found = (MOReg == Reg);
  885. if (!Found && TRI && isPhys &&
  886. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  887. if (Overlap)
  888. Found = TRI->regsOverlap(MOReg, Reg);
  889. else
  890. Found = TRI->isSubRegister(MOReg, Reg);
  891. }
  892. if (Found && (!isDead || MO.isDead()))
  893. return i;
  894. }
  895. return -1;
  896. }
  897. /// findFirstPredOperandIdx() - Find the index of the first operand in the
  898. /// operand list that is used to represent the predicate. It returns -1 if
  899. /// none is found.
  900. int MachineInstr::findFirstPredOperandIdx() const {
  901. // Don't call MCID.findFirstPredOperandIdx() because this variant
  902. // is sometimes called on an instruction that's not yet complete, and
  903. // so the number of operands is less than the MCID indicates. In
  904. // particular, the PTX target does this.
  905. const MCInstrDesc &MCID = getDesc();
  906. if (MCID.isPredicable()) {
  907. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  908. if (MCID.OpInfo[i].isPredicate())
  909. return i;
  910. }
  911. return -1;
  912. }
  913. // MachineOperand::TiedTo is 4 bits wide.
  914. const unsigned TiedMax = 15;
  915. /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
  916. ///
  917. /// Use and def operands can be tied together, indicated by a non-zero TiedTo
  918. /// field. TiedTo can have these values:
  919. ///
  920. /// 0: Operand is not tied to anything.
  921. /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
  922. /// TiedMax: Tied to an operand >= TiedMax-1.
  923. ///
  924. /// The tied def must be one of the first TiedMax operands on a normal
  925. /// instruction. INLINEASM instructions allow more tied defs.
  926. ///
  927. void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
  928. MachineOperand &DefMO = getOperand(DefIdx);
  929. MachineOperand &UseMO = getOperand(UseIdx);
  930. assert(DefMO.isDef() && "DefIdx must be a def operand");
  931. assert(UseMO.isUse() && "UseIdx must be a use operand");
  932. assert(!DefMO.isTied() && "Def is already tied to another use");
  933. assert(!UseMO.isTied() && "Use is already tied to another def");
  934. if (DefIdx < TiedMax)
  935. UseMO.TiedTo = DefIdx + 1;
  936. else {
  937. // Inline asm can use the group descriptors to find tied operands, but on
  938. // normal instruction, the tied def must be within the first TiedMax
  939. // operands.
  940. assert(isInlineAsm() && "DefIdx out of range");
  941. UseMO.TiedTo = TiedMax;
  942. }
  943. // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
  944. DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
  945. }
  946. /// Given the index of a tied register operand, find the operand it is tied to.
  947. /// Defs are tied to uses and vice versa. Returns the index of the tied operand
  948. /// which must exist.
  949. unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
  950. const MachineOperand &MO = getOperand(OpIdx);
  951. assert(MO.isTied() && "Operand isn't tied");
  952. // Normally TiedTo is in range.
  953. if (MO.TiedTo < TiedMax)
  954. return MO.TiedTo - 1;
  955. // Uses on normal instructions can be out of range.
  956. if (!isInlineAsm()) {
  957. // Normal tied defs must be in the 0..TiedMax-1 range.
  958. if (MO.isUse())
  959. return TiedMax - 1;
  960. // MO is a def. Search for the tied use.
  961. for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
  962. const MachineOperand &UseMO = getOperand(i);
  963. if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
  964. return i;
  965. }
  966. llvm_unreachable("Can't find tied use");
  967. }
  968. // Now deal with inline asm by parsing the operand group descriptor flags.
  969. // Find the beginning of each operand group.
  970. SmallVector<unsigned, 8> GroupIdx;
  971. unsigned OpIdxGroup = ~0u;
  972. unsigned NumOps;
  973. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  974. i += NumOps) {
  975. const MachineOperand &FlagMO = getOperand(i);
  976. assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
  977. unsigned CurGroup = GroupIdx.size();
  978. GroupIdx.push_back(i);
  979. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  980. // OpIdx belongs to this operand group.
  981. if (OpIdx > i && OpIdx < i + NumOps)
  982. OpIdxGroup = CurGroup;
  983. unsigned TiedGroup;
  984. if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
  985. continue;
  986. // Operands in this group are tied to operands in TiedGroup which must be
  987. // earlier. Find the number of operands between the two groups.
  988. unsigned Delta = i - GroupIdx[TiedGroup];
  989. // OpIdx is a use tied to TiedGroup.
  990. if (OpIdxGroup == CurGroup)
  991. return OpIdx - Delta;
  992. // OpIdx is a def tied to this use group.
  993. if (OpIdxGroup == TiedGroup)
  994. return OpIdx + Delta;
  995. }
  996. llvm_unreachable("Invalid tied operand on inline asm");
  997. }
  998. /// clearKillInfo - Clears kill flags on all operands.
  999. ///
  1000. void MachineInstr::clearKillInfo() {
  1001. for (MachineOperand &MO : operands()) {
  1002. if (MO.isReg() && MO.isUse())
  1003. MO.setIsKill(false);
  1004. }
  1005. }
  1006. void MachineInstr::substituteRegister(unsigned FromReg, unsigned ToReg,
  1007. unsigned SubIdx,
  1008. const TargetRegisterInfo &RegInfo) {
  1009. if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
  1010. if (SubIdx)
  1011. ToReg = RegInfo.getSubReg(ToReg, SubIdx);
  1012. for (MachineOperand &MO : operands()) {
  1013. if (!MO.isReg() || MO.getReg() != FromReg)
  1014. continue;
  1015. MO.substPhysReg(ToReg, RegInfo);
  1016. }
  1017. } else {
  1018. for (MachineOperand &MO : operands()) {
  1019. if (!MO.isReg() || MO.getReg() != FromReg)
  1020. continue;
  1021. MO.substVirtReg(ToReg, SubIdx, RegInfo);
  1022. }
  1023. }
  1024. }
  1025. /// isSafeToMove - Return true if it is safe to move this instruction. If
  1026. /// SawStore is set to true, it means that there is a store (or call) between
  1027. /// the instruction's location and its intended destination.
  1028. bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
  1029. // Ignore stuff that we obviously can't move.
  1030. //
  1031. // Treat volatile loads as stores. This is not strictly necessary for
  1032. // volatiles, but it is required for atomic loads. It is not allowed to move
  1033. // a load across an atomic load with Ordering > Monotonic.
  1034. if (mayStore() || isCall() || isPHI() ||
  1035. (mayLoad() && hasOrderedMemoryRef())) {
  1036. SawStore = true;
  1037. return false;
  1038. }
  1039. if (isPosition() || isDebugInstr() || isTerminator() ||
  1040. hasUnmodeledSideEffects())
  1041. return false;
  1042. // See if this instruction does a load. If so, we have to guarantee that the
  1043. // loaded value doesn't change between the load and the its intended
  1044. // destination. The check for isInvariantLoad gives the targe the chance to
  1045. // classify the load as always returning a constant, e.g. a constant pool
  1046. // load.
  1047. if (mayLoad() && !isDereferenceableInvariantLoad(AA))
  1048. // Otherwise, this is a real load. If there is a store between the load and
  1049. // end of block, we can't move it.
  1050. return !SawStore;
  1051. return true;
  1052. }
  1053. bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
  1054. bool UseTBAA) {
  1055. const MachineFunction *MF = getMF();
  1056. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1057. const MachineFrameInfo &MFI = MF->getFrameInfo();
  1058. // If neither instruction stores to memory, they can't alias in any
  1059. // meaningful way, even if they read from the same address.
  1060. if (!mayStore() && !Other.mayStore())
  1061. return false;
  1062. // Let the target decide if memory accesses cannot possibly overlap.
  1063. if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
  1064. return false;
  1065. // FIXME: Need to handle multiple memory operands to support all targets.
  1066. if (!hasOneMemOperand() || !Other.hasOneMemOperand())
  1067. return true;
  1068. MachineMemOperand *MMOa = *memoperands_begin();
  1069. MachineMemOperand *MMOb = *Other.memoperands_begin();
  1070. // The following interface to AA is fashioned after DAGCombiner::isAlias
  1071. // and operates with MachineMemOperand offset with some important
  1072. // assumptions:
  1073. // - LLVM fundamentally assumes flat address spaces.
  1074. // - MachineOperand offset can *only* result from legalization and
  1075. // cannot affect queries other than the trivial case of overlap
  1076. // checking.
  1077. // - These offsets never wrap and never step outside
  1078. // of allocated objects.
  1079. // - There should never be any negative offsets here.
  1080. //
  1081. // FIXME: Modify API to hide this math from "user"
  1082. // Even before we go to AA we can reason locally about some
  1083. // memory objects. It can save compile time, and possibly catch some
  1084. // corner cases not currently covered.
  1085. int64_t OffsetA = MMOa->getOffset();
  1086. int64_t OffsetB = MMOb->getOffset();
  1087. int64_t MinOffset = std::min(OffsetA, OffsetB);
  1088. uint64_t WidthA = MMOa->getSize();
  1089. uint64_t WidthB = MMOb->getSize();
  1090. bool KnownWidthA = WidthA != MemoryLocation::UnknownSize;
  1091. bool KnownWidthB = WidthB != MemoryLocation::UnknownSize;
  1092. const Value *ValA = MMOa->getValue();
  1093. const Value *ValB = MMOb->getValue();
  1094. bool SameVal = (ValA && ValB && (ValA == ValB));
  1095. if (!SameVal) {
  1096. const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
  1097. const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
  1098. if (PSVa && ValB && !PSVa->mayAlias(&MFI))
  1099. return false;
  1100. if (PSVb && ValA && !PSVb->mayAlias(&MFI))
  1101. return false;
  1102. if (PSVa && PSVb && (PSVa == PSVb))
  1103. SameVal = true;
  1104. }
  1105. if (SameVal) {
  1106. if (!KnownWidthA || !KnownWidthB)
  1107. return true;
  1108. int64_t MaxOffset = std::max(OffsetA, OffsetB);
  1109. int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
  1110. return (MinOffset + LowWidth > MaxOffset);
  1111. }
  1112. if (!AA)
  1113. return true;
  1114. if (!ValA || !ValB)
  1115. return true;
  1116. assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
  1117. assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
  1118. int64_t OverlapA = KnownWidthA ? WidthA + OffsetA - MinOffset
  1119. : MemoryLocation::UnknownSize;
  1120. int64_t OverlapB = KnownWidthB ? WidthB + OffsetB - MinOffset
  1121. : MemoryLocation::UnknownSize;
  1122. AliasResult AAResult = AA->alias(
  1123. MemoryLocation(ValA, OverlapA,
  1124. UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
  1125. MemoryLocation(ValB, OverlapB,
  1126. UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
  1127. return (AAResult != NoAlias);
  1128. }
  1129. /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
  1130. /// or volatile memory reference, or if the information describing the memory
  1131. /// reference is not available. Return false if it is known to have no ordered
  1132. /// memory references.
  1133. bool MachineInstr::hasOrderedMemoryRef() const {
  1134. // An instruction known never to access memory won't have a volatile access.
  1135. if (!mayStore() &&
  1136. !mayLoad() &&
  1137. !isCall() &&
  1138. !hasUnmodeledSideEffects())
  1139. return false;
  1140. // Otherwise, if the instruction has no memory reference information,
  1141. // conservatively assume it wasn't preserved.
  1142. if (memoperands_empty())
  1143. return true;
  1144. // Check if any of our memory operands are ordered.
  1145. return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
  1146. return !MMO->isUnordered();
  1147. });
  1148. }
  1149. /// isDereferenceableInvariantLoad - Return true if this instruction will never
  1150. /// trap and is loading from a location whose value is invariant across a run of
  1151. /// this function.
  1152. bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
  1153. // If the instruction doesn't load at all, it isn't an invariant load.
  1154. if (!mayLoad())
  1155. return false;
  1156. // If the instruction has lost its memoperands, conservatively assume that
  1157. // it may not be an invariant load.
  1158. if (memoperands_empty())
  1159. return false;
  1160. const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
  1161. for (MachineMemOperand *MMO : memoperands()) {
  1162. if (MMO->isVolatile()) return false;
  1163. // TODO: Figure out whether isAtomic is really necessary (see D57601).
  1164. if (MMO->isAtomic()) return false;
  1165. if (MMO->isStore()) return false;
  1166. if (MMO->isInvariant() && MMO->isDereferenceable())
  1167. continue;
  1168. // A load from a constant PseudoSourceValue is invariant.
  1169. if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
  1170. if (PSV->isConstant(&MFI))
  1171. continue;
  1172. if (const Value *V = MMO->getValue()) {
  1173. // If we have an AliasAnalysis, ask it whether the memory is constant.
  1174. if (AA &&
  1175. AA->pointsToConstantMemory(
  1176. MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
  1177. continue;
  1178. }
  1179. // Otherwise assume conservatively.
  1180. return false;
  1181. }
  1182. // Everything checks out.
  1183. return true;
  1184. }
  1185. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1186. /// merges together the same virtual register, return the register, otherwise
  1187. /// return 0.
  1188. unsigned MachineInstr::isConstantValuePHI() const {
  1189. if (!isPHI())
  1190. return 0;
  1191. assert(getNumOperands() >= 3 &&
  1192. "It's illegal to have a PHI without source operands");
  1193. unsigned Reg = getOperand(1).getReg();
  1194. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1195. if (getOperand(i).getReg() != Reg)
  1196. return 0;
  1197. return Reg;
  1198. }
  1199. bool MachineInstr::hasUnmodeledSideEffects() const {
  1200. if (hasProperty(MCID::UnmodeledSideEffects))
  1201. return true;
  1202. if (isInlineAsm()) {
  1203. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1204. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1205. return true;
  1206. }
  1207. return false;
  1208. }
  1209. bool MachineInstr::isLoadFoldBarrier() const {
  1210. return mayStore() || isCall() || hasUnmodeledSideEffects();
  1211. }
  1212. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1213. ///
  1214. bool MachineInstr::allDefsAreDead() const {
  1215. for (const MachineOperand &MO : operands()) {
  1216. if (!MO.isReg() || MO.isUse())
  1217. continue;
  1218. if (!MO.isDead())
  1219. return false;
  1220. }
  1221. return true;
  1222. }
  1223. /// copyImplicitOps - Copy implicit register operands from specified
  1224. /// instruction to this instruction.
  1225. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1226. const MachineInstr &MI) {
  1227. for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
  1228. i != e; ++i) {
  1229. const MachineOperand &MO = MI.getOperand(i);
  1230. if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
  1231. addOperand(MF, MO);
  1232. }
  1233. }
  1234. bool MachineInstr::hasComplexRegisterTies() const {
  1235. const MCInstrDesc &MCID = getDesc();
  1236. for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
  1237. const auto &Operand = getOperand(I);
  1238. if (!Operand.isReg() || Operand.isDef())
  1239. // Ignore the defined registers as MCID marks only the uses as tied.
  1240. continue;
  1241. int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
  1242. int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
  1243. if (ExpectedTiedIdx != TiedIdx)
  1244. return true;
  1245. }
  1246. return false;
  1247. }
  1248. LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
  1249. const MachineRegisterInfo &MRI) const {
  1250. const MachineOperand &Op = getOperand(OpIdx);
  1251. if (!Op.isReg())
  1252. return LLT{};
  1253. if (isVariadic() || OpIdx >= getNumExplicitOperands())
  1254. return MRI.getType(Op.getReg());
  1255. auto &OpInfo = getDesc().OpInfo[OpIdx];
  1256. if (!OpInfo.isGenericType())
  1257. return MRI.getType(Op.getReg());
  1258. if (PrintedTypes[OpInfo.getGenericTypeIndex()])
  1259. return LLT{};
  1260. LLT TypeToPrint = MRI.getType(Op.getReg());
  1261. // Don't mark the type index printed if it wasn't actually printed: maybe
  1262. // another operand with the same type index has an actual type attached:
  1263. if (TypeToPrint.isValid())
  1264. PrintedTypes.set(OpInfo.getGenericTypeIndex());
  1265. return TypeToPrint;
  1266. }
  1267. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1268. LLVM_DUMP_METHOD void MachineInstr::dump() const {
  1269. dbgs() << " ";
  1270. print(dbgs());
  1271. }
  1272. #endif
  1273. void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
  1274. bool SkipDebugLoc, bool AddNewLine,
  1275. const TargetInstrInfo *TII) const {
  1276. const Module *M = nullptr;
  1277. const Function *F = nullptr;
  1278. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1279. F = &MF->getFunction();
  1280. M = F->getParent();
  1281. if (!TII)
  1282. TII = MF->getSubtarget().getInstrInfo();
  1283. }
  1284. ModuleSlotTracker MST(M);
  1285. if (F)
  1286. MST.incorporateFunction(*F);
  1287. print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, TII);
  1288. }
  1289. void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
  1290. bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
  1291. bool AddNewLine, const TargetInstrInfo *TII) const {
  1292. // We can be a bit tidier if we know the MachineFunction.
  1293. const MachineFunction *MF = nullptr;
  1294. const TargetRegisterInfo *TRI = nullptr;
  1295. const MachineRegisterInfo *MRI = nullptr;
  1296. const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
  1297. tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
  1298. if (isCFIInstruction())
  1299. assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
  1300. SmallBitVector PrintedTypes(8);
  1301. bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies();
  1302. auto getTiedOperandIdx = [&](unsigned OpIdx) {
  1303. if (!ShouldPrintRegisterTies)
  1304. return 0U;
  1305. const MachineOperand &MO = getOperand(OpIdx);
  1306. if (MO.isReg() && MO.isTied() && !MO.isDef())
  1307. return findTiedOperandIdx(OpIdx);
  1308. return 0U;
  1309. };
  1310. unsigned StartOp = 0;
  1311. unsigned e = getNumOperands();
  1312. // Print explicitly defined operands on the left of an assignment syntax.
  1313. while (StartOp < e) {
  1314. const MachineOperand &MO = getOperand(StartOp);
  1315. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  1316. break;
  1317. if (StartOp != 0)
  1318. OS << ", ";
  1319. LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
  1320. unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
  1321. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/false, IsStandalone,
  1322. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1323. ++StartOp;
  1324. }
  1325. if (StartOp != 0)
  1326. OS << " = ";
  1327. if (getFlag(MachineInstr::FrameSetup))
  1328. OS << "frame-setup ";
  1329. if (getFlag(MachineInstr::FrameDestroy))
  1330. OS << "frame-destroy ";
  1331. if (getFlag(MachineInstr::FmNoNans))
  1332. OS << "nnan ";
  1333. if (getFlag(MachineInstr::FmNoInfs))
  1334. OS << "ninf ";
  1335. if (getFlag(MachineInstr::FmNsz))
  1336. OS << "nsz ";
  1337. if (getFlag(MachineInstr::FmArcp))
  1338. OS << "arcp ";
  1339. if (getFlag(MachineInstr::FmContract))
  1340. OS << "contract ";
  1341. if (getFlag(MachineInstr::FmAfn))
  1342. OS << "afn ";
  1343. if (getFlag(MachineInstr::FmReassoc))
  1344. OS << "reassoc ";
  1345. if (getFlag(MachineInstr::NoUWrap))
  1346. OS << "nuw ";
  1347. if (getFlag(MachineInstr::NoSWrap))
  1348. OS << "nsw ";
  1349. if (getFlag(MachineInstr::IsExact))
  1350. OS << "exact ";
  1351. // Print the opcode name.
  1352. if (TII)
  1353. OS << TII->getName(getOpcode());
  1354. else
  1355. OS << "UNKNOWN";
  1356. if (SkipOpers)
  1357. return;
  1358. // Print the rest of the operands.
  1359. bool FirstOp = true;
  1360. unsigned AsmDescOp = ~0u;
  1361. unsigned AsmOpCount = 0;
  1362. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1363. // Print asm string.
  1364. OS << " ";
  1365. const unsigned OpIdx = InlineAsm::MIOp_AsmString;
  1366. LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
  1367. unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
  1368. getOperand(OpIdx).print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1369. ShouldPrintRegisterTies, TiedOperandIdx, TRI,
  1370. IntrinsicInfo);
  1371. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1372. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1373. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1374. OS << " [sideeffect]";
  1375. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1376. OS << " [mayload]";
  1377. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1378. OS << " [maystore]";
  1379. if (ExtraInfo & InlineAsm::Extra_IsConvergent)
  1380. OS << " [isconvergent]";
  1381. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1382. OS << " [alignstack]";
  1383. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1384. OS << " [attdialect]";
  1385. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1386. OS << " [inteldialect]";
  1387. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1388. FirstOp = false;
  1389. }
  1390. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1391. const MachineOperand &MO = getOperand(i);
  1392. if (FirstOp) FirstOp = false; else OS << ",";
  1393. OS << " ";
  1394. if (isDebugValue() && MO.isMetadata()) {
  1395. // Pretty print DBG_VALUE instructions.
  1396. auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
  1397. if (DIV && !DIV->getName().empty())
  1398. OS << "!\"" << DIV->getName() << '\"';
  1399. else {
  1400. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1401. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1402. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1403. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1404. }
  1405. } else if (isDebugLabel() && MO.isMetadata()) {
  1406. // Pretty print DBG_LABEL instructions.
  1407. auto *DIL = dyn_cast<DILabel>(MO.getMetadata());
  1408. if (DIL && !DIL->getName().empty())
  1409. OS << "\"" << DIL->getName() << '\"';
  1410. else {
  1411. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1412. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1413. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1414. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1415. }
  1416. } else if (i == AsmDescOp && MO.isImm()) {
  1417. // Pretty print the inline asm operand descriptor.
  1418. OS << '$' << AsmOpCount++;
  1419. unsigned Flag = MO.getImm();
  1420. switch (InlineAsm::getKind(Flag)) {
  1421. case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
  1422. case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
  1423. case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
  1424. case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
  1425. case InlineAsm::Kind_Imm: OS << ":[imm"; break;
  1426. case InlineAsm::Kind_Mem: OS << ":[mem"; break;
  1427. default: OS << ":[??" << InlineAsm::getKind(Flag); break;
  1428. }
  1429. unsigned RCID = 0;
  1430. if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
  1431. InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1432. if (TRI) {
  1433. OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
  1434. } else
  1435. OS << ":RC" << RCID;
  1436. }
  1437. if (InlineAsm::isMemKind(Flag)) {
  1438. unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
  1439. switch (MCID) {
  1440. case InlineAsm::Constraint_es: OS << ":es"; break;
  1441. case InlineAsm::Constraint_i: OS << ":i"; break;
  1442. case InlineAsm::Constraint_m: OS << ":m"; break;
  1443. case InlineAsm::Constraint_o: OS << ":o"; break;
  1444. case InlineAsm::Constraint_v: OS << ":v"; break;
  1445. case InlineAsm::Constraint_Q: OS << ":Q"; break;
  1446. case InlineAsm::Constraint_R: OS << ":R"; break;
  1447. case InlineAsm::Constraint_S: OS << ":S"; break;
  1448. case InlineAsm::Constraint_T: OS << ":T"; break;
  1449. case InlineAsm::Constraint_Um: OS << ":Um"; break;
  1450. case InlineAsm::Constraint_Un: OS << ":Un"; break;
  1451. case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
  1452. case InlineAsm::Constraint_Us: OS << ":Us"; break;
  1453. case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
  1454. case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
  1455. case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
  1456. case InlineAsm::Constraint_X: OS << ":X"; break;
  1457. case InlineAsm::Constraint_Z: OS << ":Z"; break;
  1458. case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
  1459. case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
  1460. default: OS << ":?"; break;
  1461. }
  1462. }
  1463. unsigned TiedTo = 0;
  1464. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1465. OS << " tiedto:$" << TiedTo;
  1466. OS << ']';
  1467. // Compute the index of the next operand descriptor.
  1468. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1469. } else {
  1470. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1471. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1472. if (MO.isImm() && isOperandSubregIdx(i))
  1473. MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
  1474. else
  1475. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1476. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1477. }
  1478. }
  1479. // Print any optional symbols attached to this instruction as-if they were
  1480. // operands.
  1481. if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) {
  1482. if (!FirstOp) {
  1483. FirstOp = false;
  1484. OS << ',';
  1485. }
  1486. OS << " pre-instr-symbol ";
  1487. MachineOperand::printSymbol(OS, *PreInstrSymbol);
  1488. }
  1489. if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) {
  1490. if (!FirstOp) {
  1491. FirstOp = false;
  1492. OS << ',';
  1493. }
  1494. OS << " post-instr-symbol ";
  1495. MachineOperand::printSymbol(OS, *PostInstrSymbol);
  1496. }
  1497. if (!SkipDebugLoc) {
  1498. if (const DebugLoc &DL = getDebugLoc()) {
  1499. if (!FirstOp)
  1500. OS << ',';
  1501. OS << " debug-location ";
  1502. DL->printAsOperand(OS, MST);
  1503. }
  1504. }
  1505. if (!memoperands_empty()) {
  1506. SmallVector<StringRef, 0> SSNs;
  1507. const LLVMContext *Context = nullptr;
  1508. std::unique_ptr<LLVMContext> CtxPtr;
  1509. const MachineFrameInfo *MFI = nullptr;
  1510. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1511. MFI = &MF->getFrameInfo();
  1512. Context = &MF->getFunction().getContext();
  1513. } else {
  1514. CtxPtr = llvm::make_unique<LLVMContext>();
  1515. Context = CtxPtr.get();
  1516. }
  1517. OS << " :: ";
  1518. bool NeedComma = false;
  1519. for (const MachineMemOperand *Op : memoperands()) {
  1520. if (NeedComma)
  1521. OS << ", ";
  1522. Op->print(OS, MST, SSNs, *Context, MFI, TII);
  1523. NeedComma = true;
  1524. }
  1525. }
  1526. if (SkipDebugLoc)
  1527. return;
  1528. bool HaveSemi = false;
  1529. // Print debug location information.
  1530. if (const DebugLoc &DL = getDebugLoc()) {
  1531. if (!HaveSemi) {
  1532. OS << ';';
  1533. HaveSemi = true;
  1534. }
  1535. OS << ' ';
  1536. DL.print(OS);
  1537. }
  1538. // Print extra comments for DEBUG_VALUE.
  1539. if (isDebugValue() && getOperand(e - 2).isMetadata()) {
  1540. if (!HaveSemi) {
  1541. OS << ";";
  1542. HaveSemi = true;
  1543. }
  1544. auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
  1545. OS << " line no:" << DV->getLine();
  1546. if (auto *InlinedAt = debugLoc->getInlinedAt()) {
  1547. DebugLoc InlinedAtDL(InlinedAt);
  1548. if (InlinedAtDL && MF) {
  1549. OS << " inlined @[ ";
  1550. InlinedAtDL.print(OS);
  1551. OS << " ]";
  1552. }
  1553. }
  1554. if (isIndirectDebugValue())
  1555. OS << " indirect";
  1556. }
  1557. // TODO: DBG_LABEL
  1558. if (AddNewLine)
  1559. OS << '\n';
  1560. }
  1561. bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
  1562. const TargetRegisterInfo *RegInfo,
  1563. bool AddIfNotFound) {
  1564. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
  1565. bool hasAliases = isPhysReg &&
  1566. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1567. bool Found = false;
  1568. SmallVector<unsigned,4> DeadOps;
  1569. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1570. MachineOperand &MO = getOperand(i);
  1571. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1572. continue;
  1573. // DEBUG_VALUE nodes do not contribute to code generation and should
  1574. // always be ignored. Failure to do so may result in trying to modify
  1575. // KILL flags on DEBUG_VALUE nodes.
  1576. if (MO.isDebug())
  1577. continue;
  1578. unsigned Reg = MO.getReg();
  1579. if (!Reg)
  1580. continue;
  1581. if (Reg == IncomingReg) {
  1582. if (!Found) {
  1583. if (MO.isKill())
  1584. // The register is already marked kill.
  1585. return true;
  1586. if (isPhysReg && isRegTiedToDefOperand(i))
  1587. // Two-address uses of physregs must not be marked kill.
  1588. return true;
  1589. MO.setIsKill();
  1590. Found = true;
  1591. }
  1592. } else if (hasAliases && MO.isKill() &&
  1593. TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1594. // A super-register kill already exists.
  1595. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1596. return true;
  1597. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1598. DeadOps.push_back(i);
  1599. }
  1600. }
  1601. // Trim unneeded kill operands.
  1602. while (!DeadOps.empty()) {
  1603. unsigned OpIdx = DeadOps.back();
  1604. if (getOperand(OpIdx).isImplicit() &&
  1605. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1606. RemoveOperand(OpIdx);
  1607. else
  1608. getOperand(OpIdx).setIsKill(false);
  1609. DeadOps.pop_back();
  1610. }
  1611. // If not found, this means an alias of one of the operands is killed. Add a
  1612. // new implicit operand if required.
  1613. if (!Found && AddIfNotFound) {
  1614. addOperand(MachineOperand::CreateReg(IncomingReg,
  1615. false /*IsDef*/,
  1616. true /*IsImp*/,
  1617. true /*IsKill*/));
  1618. return true;
  1619. }
  1620. return Found;
  1621. }
  1622. void MachineInstr::clearRegisterKills(unsigned Reg,
  1623. const TargetRegisterInfo *RegInfo) {
  1624. if (!TargetRegisterInfo::isPhysicalRegister(Reg))
  1625. RegInfo = nullptr;
  1626. for (MachineOperand &MO : operands()) {
  1627. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1628. continue;
  1629. unsigned OpReg = MO.getReg();
  1630. if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
  1631. MO.setIsKill(false);
  1632. }
  1633. }
  1634. bool MachineInstr::addRegisterDead(unsigned Reg,
  1635. const TargetRegisterInfo *RegInfo,
  1636. bool AddIfNotFound) {
  1637. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
  1638. bool hasAliases = isPhysReg &&
  1639. MCRegAliasIterator(Reg, RegInfo, false).isValid();
  1640. bool Found = false;
  1641. SmallVector<unsigned,4> DeadOps;
  1642. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1643. MachineOperand &MO = getOperand(i);
  1644. if (!MO.isReg() || !MO.isDef())
  1645. continue;
  1646. unsigned MOReg = MO.getReg();
  1647. if (!MOReg)
  1648. continue;
  1649. if (MOReg == Reg) {
  1650. MO.setIsDead();
  1651. Found = true;
  1652. } else if (hasAliases && MO.isDead() &&
  1653. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  1654. // There exists a super-register that's marked dead.
  1655. if (RegInfo->isSuperRegister(Reg, MOReg))
  1656. return true;
  1657. if (RegInfo->isSubRegister(Reg, MOReg))
  1658. DeadOps.push_back(i);
  1659. }
  1660. }
  1661. // Trim unneeded dead operands.
  1662. while (!DeadOps.empty()) {
  1663. unsigned OpIdx = DeadOps.back();
  1664. if (getOperand(OpIdx).isImplicit() &&
  1665. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1666. RemoveOperand(OpIdx);
  1667. else
  1668. getOperand(OpIdx).setIsDead(false);
  1669. DeadOps.pop_back();
  1670. }
  1671. // If not found, this means an alias of one of the operands is dead. Add a
  1672. // new implicit operand if required.
  1673. if (Found || !AddIfNotFound)
  1674. return Found;
  1675. addOperand(MachineOperand::CreateReg(Reg,
  1676. true /*IsDef*/,
  1677. true /*IsImp*/,
  1678. false /*IsKill*/,
  1679. true /*IsDead*/));
  1680. return true;
  1681. }
  1682. void MachineInstr::clearRegisterDeads(unsigned Reg) {
  1683. for (MachineOperand &MO : operands()) {
  1684. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
  1685. continue;
  1686. MO.setIsDead(false);
  1687. }
  1688. }
  1689. void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
  1690. for (MachineOperand &MO : operands()) {
  1691. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
  1692. continue;
  1693. MO.setIsUndef(IsUndef);
  1694. }
  1695. }
  1696. void MachineInstr::addRegisterDefined(unsigned Reg,
  1697. const TargetRegisterInfo *RegInfo) {
  1698. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1699. MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
  1700. if (MO)
  1701. return;
  1702. } else {
  1703. for (const MachineOperand &MO : operands()) {
  1704. if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
  1705. MO.getSubReg() == 0)
  1706. return;
  1707. }
  1708. }
  1709. addOperand(MachineOperand::CreateReg(Reg,
  1710. true /*IsDef*/,
  1711. true /*IsImp*/));
  1712. }
  1713. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
  1714. const TargetRegisterInfo &TRI) {
  1715. bool HasRegMask = false;
  1716. for (MachineOperand &MO : operands()) {
  1717. if (MO.isRegMask()) {
  1718. HasRegMask = true;
  1719. continue;
  1720. }
  1721. if (!MO.isReg() || !MO.isDef()) continue;
  1722. unsigned Reg = MO.getReg();
  1723. if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  1724. // If there are no uses, including partial uses, the def is dead.
  1725. if (llvm::none_of(UsedRegs,
  1726. [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
  1727. MO.setIsDead();
  1728. }
  1729. // This is a call with a register mask operand.
  1730. // Mask clobbers are always dead, so add defs for the non-dead defines.
  1731. if (HasRegMask)
  1732. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1733. I != E; ++I)
  1734. addRegisterDefined(*I, &TRI);
  1735. }
  1736. unsigned
  1737. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  1738. // Build up a buffer of hash code components.
  1739. SmallVector<size_t, 8> HashComponents;
  1740. HashComponents.reserve(MI->getNumOperands() + 1);
  1741. HashComponents.push_back(MI->getOpcode());
  1742. for (const MachineOperand &MO : MI->operands()) {
  1743. if (MO.isReg() && MO.isDef() &&
  1744. TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1745. continue; // Skip virtual register defs.
  1746. HashComponents.push_back(hash_value(MO));
  1747. }
  1748. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  1749. }
  1750. void MachineInstr::emitError(StringRef Msg) const {
  1751. // Find the source location cookie.
  1752. unsigned LocCookie = 0;
  1753. const MDNode *LocMD = nullptr;
  1754. for (unsigned i = getNumOperands(); i != 0; --i) {
  1755. if (getOperand(i-1).isMetadata() &&
  1756. (LocMD = getOperand(i-1).getMetadata()) &&
  1757. LocMD->getNumOperands() != 0) {
  1758. if (const ConstantInt *CI =
  1759. mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
  1760. LocCookie = CI->getZExtValue();
  1761. break;
  1762. }
  1763. }
  1764. }
  1765. if (const MachineBasicBlock *MBB = getParent())
  1766. if (const MachineFunction *MF = MBB->getParent())
  1767. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  1768. report_fatal_error(Msg);
  1769. }
  1770. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1771. const MCInstrDesc &MCID, bool IsIndirect,
  1772. unsigned Reg, const MDNode *Variable,
  1773. const MDNode *Expr) {
  1774. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1775. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1776. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1777. "Expected inlined-at fields to agree");
  1778. auto MIB = BuildMI(MF, DL, MCID).addReg(Reg, RegState::Debug);
  1779. if (IsIndirect)
  1780. MIB.addImm(0U);
  1781. else
  1782. MIB.addReg(0U, RegState::Debug);
  1783. return MIB.addMetadata(Variable).addMetadata(Expr);
  1784. }
  1785. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1786. const MCInstrDesc &MCID, bool IsIndirect,
  1787. MachineOperand &MO, const MDNode *Variable,
  1788. const MDNode *Expr) {
  1789. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1790. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1791. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1792. "Expected inlined-at fields to agree");
  1793. if (MO.isReg())
  1794. return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr);
  1795. auto MIB = BuildMI(MF, DL, MCID).add(MO);
  1796. if (IsIndirect)
  1797. MIB.addImm(0U);
  1798. else
  1799. MIB.addReg(0U, RegState::Debug);
  1800. return MIB.addMetadata(Variable).addMetadata(Expr);
  1801. }
  1802. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1803. MachineBasicBlock::iterator I,
  1804. const DebugLoc &DL, const MCInstrDesc &MCID,
  1805. bool IsIndirect, unsigned Reg,
  1806. const MDNode *Variable, const MDNode *Expr) {
  1807. MachineFunction &MF = *BB.getParent();
  1808. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
  1809. BB.insert(I, MI);
  1810. return MachineInstrBuilder(MF, MI);
  1811. }
  1812. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1813. MachineBasicBlock::iterator I,
  1814. const DebugLoc &DL, const MCInstrDesc &MCID,
  1815. bool IsIndirect, MachineOperand &MO,
  1816. const MDNode *Variable, const MDNode *Expr) {
  1817. MachineFunction &MF = *BB.getParent();
  1818. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr);
  1819. BB.insert(I, MI);
  1820. return MachineInstrBuilder(MF, *MI);
  1821. }
  1822. /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
  1823. /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
  1824. static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
  1825. assert(MI.getOperand(0).isReg() && "can't spill non-register");
  1826. assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
  1827. "Expected inlined-at fields to agree");
  1828. const DIExpression *Expr = MI.getDebugExpression();
  1829. if (MI.isIndirectDebugValue()) {
  1830. assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
  1831. Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
  1832. }
  1833. return Expr;
  1834. }
  1835. MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
  1836. MachineBasicBlock::iterator I,
  1837. const MachineInstr &Orig,
  1838. int FrameIndex) {
  1839. const DIExpression *Expr = computeExprForSpill(Orig);
  1840. return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
  1841. .addFrameIndex(FrameIndex)
  1842. .addImm(0U)
  1843. .addMetadata(Orig.getDebugVariable())
  1844. .addMetadata(Expr);
  1845. }
  1846. void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
  1847. const DIExpression *Expr = computeExprForSpill(Orig);
  1848. Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
  1849. Orig.getOperand(1).ChangeToImmediate(0U);
  1850. Orig.getOperand(3).setMetadata(Expr);
  1851. }
  1852. void MachineInstr::collectDebugValues(
  1853. SmallVectorImpl<MachineInstr *> &DbgValues) {
  1854. MachineInstr &MI = *this;
  1855. if (!MI.getOperand(0).isReg())
  1856. return;
  1857. MachineBasicBlock::iterator DI = MI; ++DI;
  1858. for (MachineBasicBlock::iterator DE = MI.getParent()->end();
  1859. DI != DE; ++DI) {
  1860. if (!DI->isDebugValue())
  1861. return;
  1862. if (DI->getOperand(0).isReg() &&
  1863. DI->getOperand(0).getReg() == MI.getOperand(0).getReg())
  1864. DbgValues.push_back(&*DI);
  1865. }
  1866. }
  1867. void MachineInstr::changeDebugValuesDefReg(unsigned Reg) {
  1868. // Collect matching debug values.
  1869. SmallVector<MachineInstr *, 2> DbgValues;
  1870. collectDebugValues(DbgValues);
  1871. // Propagate Reg to debug value instructions.
  1872. for (auto *DBI : DbgValues)
  1873. DBI->getOperand(0).setReg(Reg);
  1874. }
  1875. using MMOList = SmallVector<const MachineMemOperand *, 2>;
  1876. static unsigned getSpillSlotSize(MMOList &Accesses,
  1877. const MachineFrameInfo &MFI) {
  1878. unsigned Size = 0;
  1879. for (auto A : Accesses)
  1880. if (MFI.isSpillSlotObjectIndex(
  1881. cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
  1882. ->getFrameIndex()))
  1883. Size += A->getSize();
  1884. return Size;
  1885. }
  1886. Optional<unsigned>
  1887. MachineInstr::getSpillSize(const TargetInstrInfo *TII) const {
  1888. int FI;
  1889. if (TII->isStoreToStackSlotPostFE(*this, FI)) {
  1890. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  1891. if (MFI.isSpillSlotObjectIndex(FI))
  1892. return (*memoperands_begin())->getSize();
  1893. }
  1894. return None;
  1895. }
  1896. Optional<unsigned>
  1897. MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const {
  1898. MMOList Accesses;
  1899. if (TII->hasStoreToStackSlot(*this, Accesses))
  1900. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  1901. return None;
  1902. }
  1903. Optional<unsigned>
  1904. MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const {
  1905. int FI;
  1906. if (TII->isLoadFromStackSlotPostFE(*this, FI)) {
  1907. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  1908. if (MFI.isSpillSlotObjectIndex(FI))
  1909. return (*memoperands_begin())->getSize();
  1910. }
  1911. return None;
  1912. }
  1913. Optional<unsigned>
  1914. MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const {
  1915. MMOList Accesses;
  1916. if (TII->hasLoadFromStackSlot(*this, Accesses))
  1917. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  1918. return None;
  1919. }