MachineInstr.cpp 73 KB

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