MachineInstr.cpp 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165
  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, const MachineInstr &Other,
  1054. bool UseTBAA) const {
  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->isUnordered())
  1163. // If the memory operand has ordering side effects, we can't move the
  1164. // instruction. Such an instruction is technically an invariant load,
  1165. // but the caller code would need updated to expect that.
  1166. return false;
  1167. if (MMO->isStore()) return false;
  1168. if (MMO->isInvariant() && MMO->isDereferenceable())
  1169. continue;
  1170. // A load from a constant PseudoSourceValue is invariant.
  1171. if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
  1172. if (PSV->isConstant(&MFI))
  1173. continue;
  1174. if (const Value *V = MMO->getValue()) {
  1175. // If we have an AliasAnalysis, ask it whether the memory is constant.
  1176. if (AA &&
  1177. AA->pointsToConstantMemory(
  1178. MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
  1179. continue;
  1180. }
  1181. // Otherwise assume conservatively.
  1182. return false;
  1183. }
  1184. // Everything checks out.
  1185. return true;
  1186. }
  1187. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1188. /// merges together the same virtual register, return the register, otherwise
  1189. /// return 0.
  1190. unsigned MachineInstr::isConstantValuePHI() const {
  1191. if (!isPHI())
  1192. return 0;
  1193. assert(getNumOperands() >= 3 &&
  1194. "It's illegal to have a PHI without source operands");
  1195. unsigned Reg = getOperand(1).getReg();
  1196. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1197. if (getOperand(i).getReg() != Reg)
  1198. return 0;
  1199. return Reg;
  1200. }
  1201. bool MachineInstr::hasUnmodeledSideEffects() const {
  1202. if (hasProperty(MCID::UnmodeledSideEffects))
  1203. return true;
  1204. if (isInlineAsm()) {
  1205. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1206. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1207. return true;
  1208. }
  1209. return false;
  1210. }
  1211. bool MachineInstr::isLoadFoldBarrier() const {
  1212. return mayStore() || isCall() || hasUnmodeledSideEffects();
  1213. }
  1214. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1215. ///
  1216. bool MachineInstr::allDefsAreDead() const {
  1217. for (const MachineOperand &MO : operands()) {
  1218. if (!MO.isReg() || MO.isUse())
  1219. continue;
  1220. if (!MO.isDead())
  1221. return false;
  1222. }
  1223. return true;
  1224. }
  1225. /// copyImplicitOps - Copy implicit register operands from specified
  1226. /// instruction to this instruction.
  1227. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1228. const MachineInstr &MI) {
  1229. for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
  1230. i != e; ++i) {
  1231. const MachineOperand &MO = MI.getOperand(i);
  1232. if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
  1233. addOperand(MF, MO);
  1234. }
  1235. }
  1236. bool MachineInstr::hasComplexRegisterTies() const {
  1237. const MCInstrDesc &MCID = getDesc();
  1238. for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
  1239. const auto &Operand = getOperand(I);
  1240. if (!Operand.isReg() || Operand.isDef())
  1241. // Ignore the defined registers as MCID marks only the uses as tied.
  1242. continue;
  1243. int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
  1244. int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
  1245. if (ExpectedTiedIdx != TiedIdx)
  1246. return true;
  1247. }
  1248. return false;
  1249. }
  1250. LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
  1251. const MachineRegisterInfo &MRI) const {
  1252. const MachineOperand &Op = getOperand(OpIdx);
  1253. if (!Op.isReg())
  1254. return LLT{};
  1255. if (isVariadic() || OpIdx >= getNumExplicitOperands())
  1256. return MRI.getType(Op.getReg());
  1257. auto &OpInfo = getDesc().OpInfo[OpIdx];
  1258. if (!OpInfo.isGenericType())
  1259. return MRI.getType(Op.getReg());
  1260. if (PrintedTypes[OpInfo.getGenericTypeIndex()])
  1261. return LLT{};
  1262. LLT TypeToPrint = MRI.getType(Op.getReg());
  1263. // Don't mark the type index printed if it wasn't actually printed: maybe
  1264. // another operand with the same type index has an actual type attached:
  1265. if (TypeToPrint.isValid())
  1266. PrintedTypes.set(OpInfo.getGenericTypeIndex());
  1267. return TypeToPrint;
  1268. }
  1269. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1270. LLVM_DUMP_METHOD void MachineInstr::dump() const {
  1271. dbgs() << " ";
  1272. print(dbgs());
  1273. }
  1274. #endif
  1275. void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
  1276. bool SkipDebugLoc, bool AddNewLine,
  1277. const TargetInstrInfo *TII) const {
  1278. const Module *M = nullptr;
  1279. const Function *F = nullptr;
  1280. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1281. F = &MF->getFunction();
  1282. M = F->getParent();
  1283. if (!TII)
  1284. TII = MF->getSubtarget().getInstrInfo();
  1285. }
  1286. ModuleSlotTracker MST(M);
  1287. if (F)
  1288. MST.incorporateFunction(*F);
  1289. print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, TII);
  1290. }
  1291. void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
  1292. bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
  1293. bool AddNewLine, const TargetInstrInfo *TII) const {
  1294. // We can be a bit tidier if we know the MachineFunction.
  1295. const MachineFunction *MF = nullptr;
  1296. const TargetRegisterInfo *TRI = nullptr;
  1297. const MachineRegisterInfo *MRI = nullptr;
  1298. const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
  1299. tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
  1300. if (isCFIInstruction())
  1301. assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
  1302. SmallBitVector PrintedTypes(8);
  1303. bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies();
  1304. auto getTiedOperandIdx = [&](unsigned OpIdx) {
  1305. if (!ShouldPrintRegisterTies)
  1306. return 0U;
  1307. const MachineOperand &MO = getOperand(OpIdx);
  1308. if (MO.isReg() && MO.isTied() && !MO.isDef())
  1309. return findTiedOperandIdx(OpIdx);
  1310. return 0U;
  1311. };
  1312. unsigned StartOp = 0;
  1313. unsigned e = getNumOperands();
  1314. // Print explicitly defined operands on the left of an assignment syntax.
  1315. while (StartOp < e) {
  1316. const MachineOperand &MO = getOperand(StartOp);
  1317. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  1318. break;
  1319. if (StartOp != 0)
  1320. OS << ", ";
  1321. LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
  1322. unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
  1323. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/false, IsStandalone,
  1324. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1325. ++StartOp;
  1326. }
  1327. if (StartOp != 0)
  1328. OS << " = ";
  1329. if (getFlag(MachineInstr::FrameSetup))
  1330. OS << "frame-setup ";
  1331. if (getFlag(MachineInstr::FrameDestroy))
  1332. OS << "frame-destroy ";
  1333. if (getFlag(MachineInstr::FmNoNans))
  1334. OS << "nnan ";
  1335. if (getFlag(MachineInstr::FmNoInfs))
  1336. OS << "ninf ";
  1337. if (getFlag(MachineInstr::FmNsz))
  1338. OS << "nsz ";
  1339. if (getFlag(MachineInstr::FmArcp))
  1340. OS << "arcp ";
  1341. if (getFlag(MachineInstr::FmContract))
  1342. OS << "contract ";
  1343. if (getFlag(MachineInstr::FmAfn))
  1344. OS << "afn ";
  1345. if (getFlag(MachineInstr::FmReassoc))
  1346. OS << "reassoc ";
  1347. if (getFlag(MachineInstr::NoUWrap))
  1348. OS << "nuw ";
  1349. if (getFlag(MachineInstr::NoSWrap))
  1350. OS << "nsw ";
  1351. if (getFlag(MachineInstr::IsExact))
  1352. OS << "exact ";
  1353. // Print the opcode name.
  1354. if (TII)
  1355. OS << TII->getName(getOpcode());
  1356. else
  1357. OS << "UNKNOWN";
  1358. if (SkipOpers)
  1359. return;
  1360. // Print the rest of the operands.
  1361. bool FirstOp = true;
  1362. unsigned AsmDescOp = ~0u;
  1363. unsigned AsmOpCount = 0;
  1364. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1365. // Print asm string.
  1366. OS << " ";
  1367. const unsigned OpIdx = InlineAsm::MIOp_AsmString;
  1368. LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
  1369. unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
  1370. getOperand(OpIdx).print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1371. ShouldPrintRegisterTies, TiedOperandIdx, TRI,
  1372. IntrinsicInfo);
  1373. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1374. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1375. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1376. OS << " [sideeffect]";
  1377. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1378. OS << " [mayload]";
  1379. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1380. OS << " [maystore]";
  1381. if (ExtraInfo & InlineAsm::Extra_IsConvergent)
  1382. OS << " [isconvergent]";
  1383. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1384. OS << " [alignstack]";
  1385. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1386. OS << " [attdialect]";
  1387. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1388. OS << " [inteldialect]";
  1389. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1390. FirstOp = false;
  1391. }
  1392. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1393. const MachineOperand &MO = getOperand(i);
  1394. if (FirstOp) FirstOp = false; else OS << ",";
  1395. OS << " ";
  1396. if (isDebugValue() && MO.isMetadata()) {
  1397. // Pretty print DBG_VALUE instructions.
  1398. auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
  1399. if (DIV && !DIV->getName().empty())
  1400. OS << "!\"" << DIV->getName() << '\"';
  1401. else {
  1402. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1403. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1404. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1405. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1406. }
  1407. } else if (isDebugLabel() && MO.isMetadata()) {
  1408. // Pretty print DBG_LABEL instructions.
  1409. auto *DIL = dyn_cast<DILabel>(MO.getMetadata());
  1410. if (DIL && !DIL->getName().empty())
  1411. OS << "\"" << DIL->getName() << '\"';
  1412. else {
  1413. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1414. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1415. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1416. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1417. }
  1418. } else if (i == AsmDescOp && MO.isImm()) {
  1419. // Pretty print the inline asm operand descriptor.
  1420. OS << '$' << AsmOpCount++;
  1421. unsigned Flag = MO.getImm();
  1422. switch (InlineAsm::getKind(Flag)) {
  1423. case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
  1424. case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
  1425. case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
  1426. case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
  1427. case InlineAsm::Kind_Imm: OS << ":[imm"; break;
  1428. case InlineAsm::Kind_Mem: OS << ":[mem"; break;
  1429. default: OS << ":[??" << InlineAsm::getKind(Flag); break;
  1430. }
  1431. unsigned RCID = 0;
  1432. if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
  1433. InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1434. if (TRI) {
  1435. OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
  1436. } else
  1437. OS << ":RC" << RCID;
  1438. }
  1439. if (InlineAsm::isMemKind(Flag)) {
  1440. unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
  1441. switch (MCID) {
  1442. case InlineAsm::Constraint_es: OS << ":es"; break;
  1443. case InlineAsm::Constraint_i: OS << ":i"; break;
  1444. case InlineAsm::Constraint_m: OS << ":m"; break;
  1445. case InlineAsm::Constraint_o: OS << ":o"; break;
  1446. case InlineAsm::Constraint_v: OS << ":v"; break;
  1447. case InlineAsm::Constraint_Q: OS << ":Q"; break;
  1448. case InlineAsm::Constraint_R: OS << ":R"; break;
  1449. case InlineAsm::Constraint_S: OS << ":S"; break;
  1450. case InlineAsm::Constraint_T: OS << ":T"; break;
  1451. case InlineAsm::Constraint_Um: OS << ":Um"; break;
  1452. case InlineAsm::Constraint_Un: OS << ":Un"; break;
  1453. case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
  1454. case InlineAsm::Constraint_Us: OS << ":Us"; break;
  1455. case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
  1456. case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
  1457. case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
  1458. case InlineAsm::Constraint_X: OS << ":X"; break;
  1459. case InlineAsm::Constraint_Z: OS << ":Z"; break;
  1460. case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
  1461. case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
  1462. default: OS << ":?"; break;
  1463. }
  1464. }
  1465. unsigned TiedTo = 0;
  1466. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1467. OS << " tiedto:$" << TiedTo;
  1468. OS << ']';
  1469. // Compute the index of the next operand descriptor.
  1470. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1471. } else {
  1472. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1473. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1474. if (MO.isImm() && isOperandSubregIdx(i))
  1475. MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
  1476. else
  1477. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1478. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1479. }
  1480. }
  1481. // Print any optional symbols attached to this instruction as-if they were
  1482. // operands.
  1483. if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) {
  1484. if (!FirstOp) {
  1485. FirstOp = false;
  1486. OS << ',';
  1487. }
  1488. OS << " pre-instr-symbol ";
  1489. MachineOperand::printSymbol(OS, *PreInstrSymbol);
  1490. }
  1491. if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) {
  1492. if (!FirstOp) {
  1493. FirstOp = false;
  1494. OS << ',';
  1495. }
  1496. OS << " post-instr-symbol ";
  1497. MachineOperand::printSymbol(OS, *PostInstrSymbol);
  1498. }
  1499. if (!SkipDebugLoc) {
  1500. if (const DebugLoc &DL = getDebugLoc()) {
  1501. if (!FirstOp)
  1502. OS << ',';
  1503. OS << " debug-location ";
  1504. DL->printAsOperand(OS, MST);
  1505. }
  1506. }
  1507. if (!memoperands_empty()) {
  1508. SmallVector<StringRef, 0> SSNs;
  1509. const LLVMContext *Context = nullptr;
  1510. std::unique_ptr<LLVMContext> CtxPtr;
  1511. const MachineFrameInfo *MFI = nullptr;
  1512. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1513. MFI = &MF->getFrameInfo();
  1514. Context = &MF->getFunction().getContext();
  1515. } else {
  1516. CtxPtr = llvm::make_unique<LLVMContext>();
  1517. Context = CtxPtr.get();
  1518. }
  1519. OS << " :: ";
  1520. bool NeedComma = false;
  1521. for (const MachineMemOperand *Op : memoperands()) {
  1522. if (NeedComma)
  1523. OS << ", ";
  1524. Op->print(OS, MST, SSNs, *Context, MFI, TII);
  1525. NeedComma = true;
  1526. }
  1527. }
  1528. if (SkipDebugLoc)
  1529. return;
  1530. bool HaveSemi = false;
  1531. // Print debug location information.
  1532. if (const DebugLoc &DL = getDebugLoc()) {
  1533. if (!HaveSemi) {
  1534. OS << ';';
  1535. HaveSemi = true;
  1536. }
  1537. OS << ' ';
  1538. DL.print(OS);
  1539. }
  1540. // Print extra comments for DEBUG_VALUE.
  1541. if (isDebugValue() && getOperand(e - 2).isMetadata()) {
  1542. if (!HaveSemi) {
  1543. OS << ";";
  1544. HaveSemi = true;
  1545. }
  1546. auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
  1547. OS << " line no:" << DV->getLine();
  1548. if (auto *InlinedAt = debugLoc->getInlinedAt()) {
  1549. DebugLoc InlinedAtDL(InlinedAt);
  1550. if (InlinedAtDL && MF) {
  1551. OS << " inlined @[ ";
  1552. InlinedAtDL.print(OS);
  1553. OS << " ]";
  1554. }
  1555. }
  1556. if (isIndirectDebugValue())
  1557. OS << " indirect";
  1558. }
  1559. // TODO: DBG_LABEL
  1560. if (AddNewLine)
  1561. OS << '\n';
  1562. }
  1563. bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
  1564. const TargetRegisterInfo *RegInfo,
  1565. bool AddIfNotFound) {
  1566. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
  1567. bool hasAliases = isPhysReg &&
  1568. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1569. bool Found = false;
  1570. SmallVector<unsigned,4> DeadOps;
  1571. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1572. MachineOperand &MO = getOperand(i);
  1573. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1574. continue;
  1575. // DEBUG_VALUE nodes do not contribute to code generation and should
  1576. // always be ignored. Failure to do so may result in trying to modify
  1577. // KILL flags on DEBUG_VALUE nodes.
  1578. if (MO.isDebug())
  1579. continue;
  1580. unsigned Reg = MO.getReg();
  1581. if (!Reg)
  1582. continue;
  1583. if (Reg == IncomingReg) {
  1584. if (!Found) {
  1585. if (MO.isKill())
  1586. // The register is already marked kill.
  1587. return true;
  1588. if (isPhysReg && isRegTiedToDefOperand(i))
  1589. // Two-address uses of physregs must not be marked kill.
  1590. return true;
  1591. MO.setIsKill();
  1592. Found = true;
  1593. }
  1594. } else if (hasAliases && MO.isKill() &&
  1595. TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1596. // A super-register kill already exists.
  1597. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1598. return true;
  1599. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1600. DeadOps.push_back(i);
  1601. }
  1602. }
  1603. // Trim unneeded kill operands.
  1604. while (!DeadOps.empty()) {
  1605. unsigned OpIdx = DeadOps.back();
  1606. if (getOperand(OpIdx).isImplicit() &&
  1607. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1608. RemoveOperand(OpIdx);
  1609. else
  1610. getOperand(OpIdx).setIsKill(false);
  1611. DeadOps.pop_back();
  1612. }
  1613. // If not found, this means an alias of one of the operands is killed. Add a
  1614. // new implicit operand if required.
  1615. if (!Found && AddIfNotFound) {
  1616. addOperand(MachineOperand::CreateReg(IncomingReg,
  1617. false /*IsDef*/,
  1618. true /*IsImp*/,
  1619. true /*IsKill*/));
  1620. return true;
  1621. }
  1622. return Found;
  1623. }
  1624. void MachineInstr::clearRegisterKills(unsigned Reg,
  1625. const TargetRegisterInfo *RegInfo) {
  1626. if (!TargetRegisterInfo::isPhysicalRegister(Reg))
  1627. RegInfo = nullptr;
  1628. for (MachineOperand &MO : operands()) {
  1629. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1630. continue;
  1631. unsigned OpReg = MO.getReg();
  1632. if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
  1633. MO.setIsKill(false);
  1634. }
  1635. }
  1636. bool MachineInstr::addRegisterDead(unsigned Reg,
  1637. const TargetRegisterInfo *RegInfo,
  1638. bool AddIfNotFound) {
  1639. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
  1640. bool hasAliases = isPhysReg &&
  1641. MCRegAliasIterator(Reg, RegInfo, false).isValid();
  1642. bool Found = false;
  1643. SmallVector<unsigned,4> DeadOps;
  1644. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1645. MachineOperand &MO = getOperand(i);
  1646. if (!MO.isReg() || !MO.isDef())
  1647. continue;
  1648. unsigned MOReg = MO.getReg();
  1649. if (!MOReg)
  1650. continue;
  1651. if (MOReg == Reg) {
  1652. MO.setIsDead();
  1653. Found = true;
  1654. } else if (hasAliases && MO.isDead() &&
  1655. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  1656. // There exists a super-register that's marked dead.
  1657. if (RegInfo->isSuperRegister(Reg, MOReg))
  1658. return true;
  1659. if (RegInfo->isSubRegister(Reg, MOReg))
  1660. DeadOps.push_back(i);
  1661. }
  1662. }
  1663. // Trim unneeded dead operands.
  1664. while (!DeadOps.empty()) {
  1665. unsigned OpIdx = DeadOps.back();
  1666. if (getOperand(OpIdx).isImplicit() &&
  1667. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1668. RemoveOperand(OpIdx);
  1669. else
  1670. getOperand(OpIdx).setIsDead(false);
  1671. DeadOps.pop_back();
  1672. }
  1673. // If not found, this means an alias of one of the operands is dead. Add a
  1674. // new implicit operand if required.
  1675. if (Found || !AddIfNotFound)
  1676. return Found;
  1677. addOperand(MachineOperand::CreateReg(Reg,
  1678. true /*IsDef*/,
  1679. true /*IsImp*/,
  1680. false /*IsKill*/,
  1681. true /*IsDead*/));
  1682. return true;
  1683. }
  1684. void MachineInstr::clearRegisterDeads(unsigned Reg) {
  1685. for (MachineOperand &MO : operands()) {
  1686. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
  1687. continue;
  1688. MO.setIsDead(false);
  1689. }
  1690. }
  1691. void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
  1692. for (MachineOperand &MO : operands()) {
  1693. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
  1694. continue;
  1695. MO.setIsUndef(IsUndef);
  1696. }
  1697. }
  1698. void MachineInstr::addRegisterDefined(unsigned Reg,
  1699. const TargetRegisterInfo *RegInfo) {
  1700. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1701. MachineOperand *MO = findRegisterDefOperand(Reg, false, false, RegInfo);
  1702. if (MO)
  1703. return;
  1704. } else {
  1705. for (const MachineOperand &MO : operands()) {
  1706. if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
  1707. MO.getSubReg() == 0)
  1708. return;
  1709. }
  1710. }
  1711. addOperand(MachineOperand::CreateReg(Reg,
  1712. true /*IsDef*/,
  1713. true /*IsImp*/));
  1714. }
  1715. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
  1716. const TargetRegisterInfo &TRI) {
  1717. bool HasRegMask = false;
  1718. for (MachineOperand &MO : operands()) {
  1719. if (MO.isRegMask()) {
  1720. HasRegMask = true;
  1721. continue;
  1722. }
  1723. if (!MO.isReg() || !MO.isDef()) continue;
  1724. unsigned Reg = MO.getReg();
  1725. if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  1726. // If there are no uses, including partial uses, the def is dead.
  1727. if (llvm::none_of(UsedRegs,
  1728. [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
  1729. MO.setIsDead();
  1730. }
  1731. // This is a call with a register mask operand.
  1732. // Mask clobbers are always dead, so add defs for the non-dead defines.
  1733. if (HasRegMask)
  1734. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1735. I != E; ++I)
  1736. addRegisterDefined(*I, &TRI);
  1737. }
  1738. unsigned
  1739. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  1740. // Build up a buffer of hash code components.
  1741. SmallVector<size_t, 8> HashComponents;
  1742. HashComponents.reserve(MI->getNumOperands() + 1);
  1743. HashComponents.push_back(MI->getOpcode());
  1744. for (const MachineOperand &MO : MI->operands()) {
  1745. if (MO.isReg() && MO.isDef() &&
  1746. TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1747. continue; // Skip virtual register defs.
  1748. HashComponents.push_back(hash_value(MO));
  1749. }
  1750. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  1751. }
  1752. void MachineInstr::emitError(StringRef Msg) const {
  1753. // Find the source location cookie.
  1754. unsigned LocCookie = 0;
  1755. const MDNode *LocMD = nullptr;
  1756. for (unsigned i = getNumOperands(); i != 0; --i) {
  1757. if (getOperand(i-1).isMetadata() &&
  1758. (LocMD = getOperand(i-1).getMetadata()) &&
  1759. LocMD->getNumOperands() != 0) {
  1760. if (const ConstantInt *CI =
  1761. mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
  1762. LocCookie = CI->getZExtValue();
  1763. break;
  1764. }
  1765. }
  1766. }
  1767. if (const MachineBasicBlock *MBB = getParent())
  1768. if (const MachineFunction *MF = MBB->getParent())
  1769. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  1770. report_fatal_error(Msg);
  1771. }
  1772. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1773. const MCInstrDesc &MCID, bool IsIndirect,
  1774. unsigned Reg, const MDNode *Variable,
  1775. const MDNode *Expr) {
  1776. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1777. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1778. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1779. "Expected inlined-at fields to agree");
  1780. auto MIB = BuildMI(MF, DL, MCID).addReg(Reg, RegState::Debug);
  1781. if (IsIndirect)
  1782. MIB.addImm(0U);
  1783. else
  1784. MIB.addReg(0U, RegState::Debug);
  1785. return MIB.addMetadata(Variable).addMetadata(Expr);
  1786. }
  1787. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1788. const MCInstrDesc &MCID, bool IsIndirect,
  1789. MachineOperand &MO, const MDNode *Variable,
  1790. const MDNode *Expr) {
  1791. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1792. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1793. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1794. "Expected inlined-at fields to agree");
  1795. if (MO.isReg())
  1796. return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr);
  1797. auto MIB = BuildMI(MF, DL, MCID).add(MO);
  1798. if (IsIndirect)
  1799. MIB.addImm(0U);
  1800. else
  1801. MIB.addReg(0U, RegState::Debug);
  1802. return MIB.addMetadata(Variable).addMetadata(Expr);
  1803. }
  1804. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1805. MachineBasicBlock::iterator I,
  1806. const DebugLoc &DL, const MCInstrDesc &MCID,
  1807. bool IsIndirect, unsigned Reg,
  1808. const MDNode *Variable, const MDNode *Expr) {
  1809. MachineFunction &MF = *BB.getParent();
  1810. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
  1811. BB.insert(I, MI);
  1812. return MachineInstrBuilder(MF, MI);
  1813. }
  1814. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1815. MachineBasicBlock::iterator I,
  1816. const DebugLoc &DL, const MCInstrDesc &MCID,
  1817. bool IsIndirect, MachineOperand &MO,
  1818. const MDNode *Variable, const MDNode *Expr) {
  1819. MachineFunction &MF = *BB.getParent();
  1820. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr);
  1821. BB.insert(I, MI);
  1822. return MachineInstrBuilder(MF, *MI);
  1823. }
  1824. /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
  1825. /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
  1826. static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
  1827. assert(MI.getOperand(0).isReg() && "can't spill non-register");
  1828. assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
  1829. "Expected inlined-at fields to agree");
  1830. const DIExpression *Expr = MI.getDebugExpression();
  1831. if (MI.isIndirectDebugValue()) {
  1832. assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
  1833. Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
  1834. }
  1835. return Expr;
  1836. }
  1837. MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
  1838. MachineBasicBlock::iterator I,
  1839. const MachineInstr &Orig,
  1840. int FrameIndex) {
  1841. const DIExpression *Expr = computeExprForSpill(Orig);
  1842. return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
  1843. .addFrameIndex(FrameIndex)
  1844. .addImm(0U)
  1845. .addMetadata(Orig.getDebugVariable())
  1846. .addMetadata(Expr);
  1847. }
  1848. void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
  1849. const DIExpression *Expr = computeExprForSpill(Orig);
  1850. Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
  1851. Orig.getOperand(1).ChangeToImmediate(0U);
  1852. Orig.getOperand(3).setMetadata(Expr);
  1853. }
  1854. void MachineInstr::collectDebugValues(
  1855. SmallVectorImpl<MachineInstr *> &DbgValues) {
  1856. MachineInstr &MI = *this;
  1857. if (!MI.getOperand(0).isReg())
  1858. return;
  1859. MachineBasicBlock::iterator DI = MI; ++DI;
  1860. for (MachineBasicBlock::iterator DE = MI.getParent()->end();
  1861. DI != DE; ++DI) {
  1862. if (!DI->isDebugValue())
  1863. return;
  1864. if (DI->getOperand(0).isReg() &&
  1865. DI->getOperand(0).getReg() == MI.getOperand(0).getReg())
  1866. DbgValues.push_back(&*DI);
  1867. }
  1868. }
  1869. void MachineInstr::changeDebugValuesDefReg(unsigned Reg) {
  1870. // Collect matching debug values.
  1871. SmallVector<MachineInstr *, 2> DbgValues;
  1872. collectDebugValues(DbgValues);
  1873. // Propagate Reg to debug value instructions.
  1874. for (auto *DBI : DbgValues)
  1875. DBI->getOperand(0).setReg(Reg);
  1876. }
  1877. using MMOList = SmallVector<const MachineMemOperand *, 2>;
  1878. static unsigned getSpillSlotSize(MMOList &Accesses,
  1879. const MachineFrameInfo &MFI) {
  1880. unsigned Size = 0;
  1881. for (auto A : Accesses)
  1882. if (MFI.isSpillSlotObjectIndex(
  1883. cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
  1884. ->getFrameIndex()))
  1885. Size += A->getSize();
  1886. return Size;
  1887. }
  1888. Optional<unsigned>
  1889. MachineInstr::getSpillSize(const TargetInstrInfo *TII) const {
  1890. int FI;
  1891. if (TII->isStoreToStackSlotPostFE(*this, FI)) {
  1892. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  1893. if (MFI.isSpillSlotObjectIndex(FI))
  1894. return (*memoperands_begin())->getSize();
  1895. }
  1896. return None;
  1897. }
  1898. Optional<unsigned>
  1899. MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const {
  1900. MMOList Accesses;
  1901. if (TII->hasStoreToStackSlot(*this, Accesses))
  1902. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  1903. return None;
  1904. }
  1905. Optional<unsigned>
  1906. MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const {
  1907. int FI;
  1908. if (TII->isLoadFromStackSlotPostFE(*this, FI)) {
  1909. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  1910. if (MFI.isSpillSlotObjectIndex(FI))
  1911. return (*memoperands_begin())->getSize();
  1912. }
  1913. return None;
  1914. }
  1915. Optional<unsigned>
  1916. MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const {
  1917. MMOList Accesses;
  1918. if (TII->hasLoadFromStackSlot(*this, Accesses))
  1919. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  1920. return None;
  1921. }