MachineInstr.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  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. void MachineInstr::cloneInstrSymbols(MachineFunction &MF,
  456. const MachineInstr &MI) {
  457. if (this == &MI)
  458. // Nothing to do for a self-clone!
  459. return;
  460. assert(&MF == MI.getMF() &&
  461. "Invalid machine functions when cloning instruction symbols!");
  462. setPreInstrSymbol(MF, MI.getPreInstrSymbol());
  463. setPostInstrSymbol(MF, MI.getPostInstrSymbol());
  464. }
  465. uint16_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
  466. // For now, the just return the union of the flags. If the flags get more
  467. // complicated over time, we might need more logic here.
  468. return getFlags() | Other.getFlags();
  469. }
  470. uint16_t MachineInstr::copyFlagsFromInstruction(const Instruction &I) {
  471. uint16_t MIFlags = 0;
  472. // Copy the wrapping flags.
  473. if (const OverflowingBinaryOperator *OB =
  474. dyn_cast<OverflowingBinaryOperator>(&I)) {
  475. if (OB->hasNoSignedWrap())
  476. MIFlags |= MachineInstr::MIFlag::NoSWrap;
  477. if (OB->hasNoUnsignedWrap())
  478. MIFlags |= MachineInstr::MIFlag::NoUWrap;
  479. }
  480. // Copy the exact flag.
  481. if (const PossiblyExactOperator *PE = dyn_cast<PossiblyExactOperator>(&I))
  482. if (PE->isExact())
  483. MIFlags |= MachineInstr::MIFlag::IsExact;
  484. // Copy the fast-math flags.
  485. if (const FPMathOperator *FP = dyn_cast<FPMathOperator>(&I)) {
  486. const FastMathFlags Flags = FP->getFastMathFlags();
  487. if (Flags.noNaNs())
  488. MIFlags |= MachineInstr::MIFlag::FmNoNans;
  489. if (Flags.noInfs())
  490. MIFlags |= MachineInstr::MIFlag::FmNoInfs;
  491. if (Flags.noSignedZeros())
  492. MIFlags |= MachineInstr::MIFlag::FmNsz;
  493. if (Flags.allowReciprocal())
  494. MIFlags |= MachineInstr::MIFlag::FmArcp;
  495. if (Flags.allowContract())
  496. MIFlags |= MachineInstr::MIFlag::FmContract;
  497. if (Flags.approxFunc())
  498. MIFlags |= MachineInstr::MIFlag::FmAfn;
  499. if (Flags.allowReassoc())
  500. MIFlags |= MachineInstr::MIFlag::FmReassoc;
  501. }
  502. return MIFlags;
  503. }
  504. void MachineInstr::copyIRFlags(const Instruction &I) {
  505. Flags = copyFlagsFromInstruction(I);
  506. }
  507. bool MachineInstr::hasPropertyInBundle(uint64_t Mask, QueryType Type) const {
  508. assert(!isBundledWithPred() && "Must be called on bundle header");
  509. for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
  510. if (MII->getDesc().getFlags() & Mask) {
  511. if (Type == AnyInBundle)
  512. return true;
  513. } else {
  514. if (Type == AllInBundle && !MII->isBundle())
  515. return false;
  516. }
  517. // This was the last instruction in the bundle.
  518. if (!MII->isBundledWithSucc())
  519. return Type == AllInBundle;
  520. }
  521. }
  522. bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
  523. MICheckType Check) const {
  524. // If opcodes or number of operands are not the same then the two
  525. // instructions are obviously not identical.
  526. if (Other.getOpcode() != getOpcode() ||
  527. Other.getNumOperands() != getNumOperands())
  528. return false;
  529. if (isBundle()) {
  530. // We have passed the test above that both instructions have the same
  531. // opcode, so we know that both instructions are bundles here. Let's compare
  532. // MIs inside the bundle.
  533. assert(Other.isBundle() && "Expected that both instructions are bundles.");
  534. MachineBasicBlock::const_instr_iterator I1 = getIterator();
  535. MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
  536. // Loop until we analysed the last intruction inside at least one of the
  537. // bundles.
  538. while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
  539. ++I1;
  540. ++I2;
  541. if (!I1->isIdenticalTo(*I2, Check))
  542. return false;
  543. }
  544. // If we've reached the end of just one of the two bundles, but not both,
  545. // the instructions are not identical.
  546. if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
  547. return false;
  548. }
  549. // Check operands to make sure they match.
  550. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  551. const MachineOperand &MO = getOperand(i);
  552. const MachineOperand &OMO = Other.getOperand(i);
  553. if (!MO.isReg()) {
  554. if (!MO.isIdenticalTo(OMO))
  555. return false;
  556. continue;
  557. }
  558. // Clients may or may not want to ignore defs when testing for equality.
  559. // For example, machine CSE pass only cares about finding common
  560. // subexpressions, so it's safe to ignore virtual register defs.
  561. if (MO.isDef()) {
  562. if (Check == IgnoreDefs)
  563. continue;
  564. else if (Check == IgnoreVRegDefs) {
  565. if (!Register::isVirtualRegister(MO.getReg()) ||
  566. !Register::isVirtualRegister(OMO.getReg()))
  567. if (!MO.isIdenticalTo(OMO))
  568. return false;
  569. } else {
  570. if (!MO.isIdenticalTo(OMO))
  571. return false;
  572. if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
  573. return false;
  574. }
  575. } else {
  576. if (!MO.isIdenticalTo(OMO))
  577. return false;
  578. if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
  579. return false;
  580. }
  581. }
  582. // If DebugLoc does not match then two debug instructions are not identical.
  583. if (isDebugInstr())
  584. if (getDebugLoc() && Other.getDebugLoc() &&
  585. getDebugLoc() != Other.getDebugLoc())
  586. return false;
  587. return true;
  588. }
  589. const MachineFunction *MachineInstr::getMF() const {
  590. return getParent()->getParent();
  591. }
  592. MachineInstr *MachineInstr::removeFromParent() {
  593. assert(getParent() && "Not embedded in a basic block!");
  594. return getParent()->remove(this);
  595. }
  596. MachineInstr *MachineInstr::removeFromBundle() {
  597. assert(getParent() && "Not embedded in a basic block!");
  598. return getParent()->remove_instr(this);
  599. }
  600. void MachineInstr::eraseFromParent() {
  601. assert(getParent() && "Not embedded in a basic block!");
  602. getParent()->erase(this);
  603. }
  604. void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
  605. assert(getParent() && "Not embedded in a basic block!");
  606. MachineBasicBlock *MBB = getParent();
  607. MachineFunction *MF = MBB->getParent();
  608. assert(MF && "Not embedded in a function!");
  609. MachineInstr *MI = (MachineInstr *)this;
  610. MachineRegisterInfo &MRI = MF->getRegInfo();
  611. for (const MachineOperand &MO : MI->operands()) {
  612. if (!MO.isReg() || !MO.isDef())
  613. continue;
  614. Register Reg = MO.getReg();
  615. if (!Reg.isVirtual())
  616. continue;
  617. MRI.markUsesInDebugValueAsUndef(Reg);
  618. }
  619. MI->eraseFromParent();
  620. }
  621. void MachineInstr::eraseFromBundle() {
  622. assert(getParent() && "Not embedded in a basic block!");
  623. getParent()->erase_instr(this);
  624. }
  625. unsigned MachineInstr::getNumExplicitOperands() const {
  626. unsigned NumOperands = MCID->getNumOperands();
  627. if (!MCID->isVariadic())
  628. return NumOperands;
  629. for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) {
  630. const MachineOperand &MO = getOperand(I);
  631. // The operands must always be in the following order:
  632. // - explicit reg defs,
  633. // - other explicit operands (reg uses, immediates, etc.),
  634. // - implicit reg defs
  635. // - implicit reg uses
  636. if (MO.isReg() && MO.isImplicit())
  637. break;
  638. ++NumOperands;
  639. }
  640. return NumOperands;
  641. }
  642. unsigned MachineInstr::getNumExplicitDefs() const {
  643. unsigned NumDefs = MCID->getNumDefs();
  644. if (!MCID->isVariadic())
  645. return NumDefs;
  646. for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) {
  647. const MachineOperand &MO = getOperand(I);
  648. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  649. break;
  650. ++NumDefs;
  651. }
  652. return NumDefs;
  653. }
  654. void MachineInstr::bundleWithPred() {
  655. assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
  656. setFlag(BundledPred);
  657. MachineBasicBlock::instr_iterator Pred = getIterator();
  658. --Pred;
  659. assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  660. Pred->setFlag(BundledSucc);
  661. }
  662. void MachineInstr::bundleWithSucc() {
  663. assert(!isBundledWithSucc() && "MI is already bundled with its successor");
  664. setFlag(BundledSucc);
  665. MachineBasicBlock::instr_iterator Succ = getIterator();
  666. ++Succ;
  667. assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
  668. Succ->setFlag(BundledPred);
  669. }
  670. void MachineInstr::unbundleFromPred() {
  671. assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
  672. clearFlag(BundledPred);
  673. MachineBasicBlock::instr_iterator Pred = getIterator();
  674. --Pred;
  675. assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  676. Pred->clearFlag(BundledSucc);
  677. }
  678. void MachineInstr::unbundleFromSucc() {
  679. assert(isBundledWithSucc() && "MI isn't bundled with its successor");
  680. clearFlag(BundledSucc);
  681. MachineBasicBlock::instr_iterator Succ = getIterator();
  682. ++Succ;
  683. assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
  684. Succ->clearFlag(BundledPred);
  685. }
  686. bool MachineInstr::isStackAligningInlineAsm() const {
  687. if (isInlineAsm()) {
  688. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  689. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  690. return true;
  691. }
  692. return false;
  693. }
  694. InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
  695. assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
  696. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  697. return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
  698. }
  699. int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
  700. unsigned *GroupNo) const {
  701. assert(isInlineAsm() && "Expected an inline asm instruction");
  702. assert(OpIdx < getNumOperands() && "OpIdx out of range");
  703. // Ignore queries about the initial operands.
  704. if (OpIdx < InlineAsm::MIOp_FirstOperand)
  705. return -1;
  706. unsigned Group = 0;
  707. unsigned NumOps;
  708. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  709. i += NumOps) {
  710. const MachineOperand &FlagMO = getOperand(i);
  711. // If we reach the implicit register operands, stop looking.
  712. if (!FlagMO.isImm())
  713. return -1;
  714. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  715. if (i + NumOps > OpIdx) {
  716. if (GroupNo)
  717. *GroupNo = Group;
  718. return i;
  719. }
  720. ++Group;
  721. }
  722. return -1;
  723. }
  724. const DILabel *MachineInstr::getDebugLabel() const {
  725. assert(isDebugLabel() && "not a DBG_LABEL");
  726. return cast<DILabel>(getOperand(0).getMetadata());
  727. }
  728. const DILocalVariable *MachineInstr::getDebugVariable() const {
  729. assert(isDebugValue() && "not a DBG_VALUE");
  730. return cast<DILocalVariable>(getOperand(2).getMetadata());
  731. }
  732. const DIExpression *MachineInstr::getDebugExpression() const {
  733. assert(isDebugValue() && "not a DBG_VALUE");
  734. return cast<DIExpression>(getOperand(3).getMetadata());
  735. }
  736. const TargetRegisterClass*
  737. MachineInstr::getRegClassConstraint(unsigned OpIdx,
  738. const TargetInstrInfo *TII,
  739. const TargetRegisterInfo *TRI) const {
  740. assert(getParent() && "Can't have an MBB reference here!");
  741. assert(getMF() && "Can't have an MF reference here!");
  742. const MachineFunction &MF = *getMF();
  743. // Most opcodes have fixed constraints in their MCInstrDesc.
  744. if (!isInlineAsm())
  745. return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
  746. if (!getOperand(OpIdx).isReg())
  747. return nullptr;
  748. // For tied uses on inline asm, get the constraint from the def.
  749. unsigned DefIdx;
  750. if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
  751. OpIdx = DefIdx;
  752. // Inline asm stores register class constraints in the flag word.
  753. int FlagIdx = findInlineAsmFlagIdx(OpIdx);
  754. if (FlagIdx < 0)
  755. return nullptr;
  756. unsigned Flag = getOperand(FlagIdx).getImm();
  757. unsigned RCID;
  758. if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
  759. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
  760. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
  761. InlineAsm::hasRegClassConstraint(Flag, RCID))
  762. return TRI->getRegClass(RCID);
  763. // Assume that all registers in a memory operand are pointers.
  764. if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
  765. return TRI->getPointerRegClass(MF);
  766. return nullptr;
  767. }
  768. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
  769. Register Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
  770. const TargetRegisterInfo *TRI, bool ExploreBundle) const {
  771. // Check every operands inside the bundle if we have
  772. // been asked to.
  773. if (ExploreBundle)
  774. for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
  775. ++OpndIt)
  776. CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
  777. OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
  778. else
  779. // Otherwise, just check the current operands.
  780. for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
  781. CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
  782. return CurRC;
  783. }
  784. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
  785. unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
  786. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  787. assert(CurRC && "Invalid initial register class");
  788. // Check if Reg is constrained by some of its use/def from MI.
  789. const MachineOperand &MO = getOperand(OpIdx);
  790. if (!MO.isReg() || MO.getReg() != Reg)
  791. return CurRC;
  792. // If yes, accumulate the constraints through the operand.
  793. return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
  794. }
  795. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
  796. unsigned OpIdx, const TargetRegisterClass *CurRC,
  797. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  798. const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
  799. const MachineOperand &MO = getOperand(OpIdx);
  800. assert(MO.isReg() &&
  801. "Cannot get register constraints for non-register operand");
  802. assert(CurRC && "Invalid initial register class");
  803. if (unsigned SubIdx = MO.getSubReg()) {
  804. if (OpRC)
  805. CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
  806. else
  807. CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
  808. } else if (OpRC)
  809. CurRC = TRI->getCommonSubClass(CurRC, OpRC);
  810. return CurRC;
  811. }
  812. /// Return the number of instructions inside the MI bundle, not counting the
  813. /// header instruction.
  814. unsigned MachineInstr::getBundleSize() const {
  815. MachineBasicBlock::const_instr_iterator I = getIterator();
  816. unsigned Size = 0;
  817. while (I->isBundledWithSucc()) {
  818. ++Size;
  819. ++I;
  820. }
  821. return Size;
  822. }
  823. /// Returns true if the MachineInstr has an implicit-use operand of exactly
  824. /// the given register (not considering sub/super-registers).
  825. bool MachineInstr::hasRegisterImplicitUseOperand(Register Reg) const {
  826. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  827. const MachineOperand &MO = getOperand(i);
  828. if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
  829. return true;
  830. }
  831. return false;
  832. }
  833. /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
  834. /// the specific register or -1 if it is not found. It further tightens
  835. /// the search criteria to a use that kills the register if isKill is true.
  836. int MachineInstr::findRegisterUseOperandIdx(
  837. Register Reg, bool isKill, const TargetRegisterInfo *TRI) const {
  838. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  839. const MachineOperand &MO = getOperand(i);
  840. if (!MO.isReg() || !MO.isUse())
  841. continue;
  842. Register MOReg = MO.getReg();
  843. if (!MOReg)
  844. continue;
  845. if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg)))
  846. if (!isKill || MO.isKill())
  847. return i;
  848. }
  849. return -1;
  850. }
  851. /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
  852. /// indicating if this instruction reads or writes Reg. This also considers
  853. /// partial defines.
  854. std::pair<bool,bool>
  855. MachineInstr::readsWritesVirtualRegister(Register Reg,
  856. SmallVectorImpl<unsigned> *Ops) const {
  857. bool PartDef = false; // Partial redefine.
  858. bool FullDef = false; // Full define.
  859. bool Use = false;
  860. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  861. const MachineOperand &MO = getOperand(i);
  862. if (!MO.isReg() || MO.getReg() != Reg)
  863. continue;
  864. if (Ops)
  865. Ops->push_back(i);
  866. if (MO.isUse())
  867. Use |= !MO.isUndef();
  868. else if (MO.getSubReg() && !MO.isUndef())
  869. // A partial def undef doesn't count as reading the register.
  870. PartDef = true;
  871. else
  872. FullDef = true;
  873. }
  874. // A partial redefine uses Reg unless there is also a full define.
  875. return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
  876. }
  877. /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
  878. /// the specified register or -1 if it is not found. If isDead is true, defs
  879. /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
  880. /// also checks if there is a def of a super-register.
  881. int
  882. MachineInstr::findRegisterDefOperandIdx(Register Reg, bool isDead, bool Overlap,
  883. const TargetRegisterInfo *TRI) const {
  884. bool isPhys = Register::isPhysicalRegister(Reg);
  885. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  886. const MachineOperand &MO = getOperand(i);
  887. // Accept regmask operands when Overlap is set.
  888. // Ignore them when looking for a specific def operand (Overlap == false).
  889. if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
  890. return i;
  891. if (!MO.isReg() || !MO.isDef())
  892. continue;
  893. Register MOReg = MO.getReg();
  894. bool Found = (MOReg == Reg);
  895. if (!Found && TRI && isPhys && Register::isPhysicalRegister(MOReg)) {
  896. if (Overlap)
  897. Found = TRI->regsOverlap(MOReg, Reg);
  898. else
  899. Found = TRI->isSubRegister(MOReg, Reg);
  900. }
  901. if (Found && (!isDead || MO.isDead()))
  902. return i;
  903. }
  904. return -1;
  905. }
  906. /// findFirstPredOperandIdx() - Find the index of the first operand in the
  907. /// operand list that is used to represent the predicate. It returns -1 if
  908. /// none is found.
  909. int MachineInstr::findFirstPredOperandIdx() const {
  910. // Don't call MCID.findFirstPredOperandIdx() because this variant
  911. // is sometimes called on an instruction that's not yet complete, and
  912. // so the number of operands is less than the MCID indicates. In
  913. // particular, the PTX target does this.
  914. const MCInstrDesc &MCID = getDesc();
  915. if (MCID.isPredicable()) {
  916. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  917. if (MCID.OpInfo[i].isPredicate())
  918. return i;
  919. }
  920. return -1;
  921. }
  922. // MachineOperand::TiedTo is 4 bits wide.
  923. const unsigned TiedMax = 15;
  924. /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
  925. ///
  926. /// Use and def operands can be tied together, indicated by a non-zero TiedTo
  927. /// field. TiedTo can have these values:
  928. ///
  929. /// 0: Operand is not tied to anything.
  930. /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
  931. /// TiedMax: Tied to an operand >= TiedMax-1.
  932. ///
  933. /// The tied def must be one of the first TiedMax operands on a normal
  934. /// instruction. INLINEASM instructions allow more tied defs.
  935. ///
  936. void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
  937. MachineOperand &DefMO = getOperand(DefIdx);
  938. MachineOperand &UseMO = getOperand(UseIdx);
  939. assert(DefMO.isDef() && "DefIdx must be a def operand");
  940. assert(UseMO.isUse() && "UseIdx must be a use operand");
  941. assert(!DefMO.isTied() && "Def is already tied to another use");
  942. assert(!UseMO.isTied() && "Use is already tied to another def");
  943. if (DefIdx < TiedMax)
  944. UseMO.TiedTo = DefIdx + 1;
  945. else {
  946. // Inline asm can use the group descriptors to find tied operands, but on
  947. // normal instruction, the tied def must be within the first TiedMax
  948. // operands.
  949. assert(isInlineAsm() && "DefIdx out of range");
  950. UseMO.TiedTo = TiedMax;
  951. }
  952. // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
  953. DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
  954. }
  955. /// Given the index of a tied register operand, find the operand it is tied to.
  956. /// Defs are tied to uses and vice versa. Returns the index of the tied operand
  957. /// which must exist.
  958. unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
  959. const MachineOperand &MO = getOperand(OpIdx);
  960. assert(MO.isTied() && "Operand isn't tied");
  961. // Normally TiedTo is in range.
  962. if (MO.TiedTo < TiedMax)
  963. return MO.TiedTo - 1;
  964. // Uses on normal instructions can be out of range.
  965. if (!isInlineAsm()) {
  966. // Normal tied defs must be in the 0..TiedMax-1 range.
  967. if (MO.isUse())
  968. return TiedMax - 1;
  969. // MO is a def. Search for the tied use.
  970. for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
  971. const MachineOperand &UseMO = getOperand(i);
  972. if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
  973. return i;
  974. }
  975. llvm_unreachable("Can't find tied use");
  976. }
  977. // Now deal with inline asm by parsing the operand group descriptor flags.
  978. // Find the beginning of each operand group.
  979. SmallVector<unsigned, 8> GroupIdx;
  980. unsigned OpIdxGroup = ~0u;
  981. unsigned NumOps;
  982. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  983. i += NumOps) {
  984. const MachineOperand &FlagMO = getOperand(i);
  985. assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
  986. unsigned CurGroup = GroupIdx.size();
  987. GroupIdx.push_back(i);
  988. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  989. // OpIdx belongs to this operand group.
  990. if (OpIdx > i && OpIdx < i + NumOps)
  991. OpIdxGroup = CurGroup;
  992. unsigned TiedGroup;
  993. if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
  994. continue;
  995. // Operands in this group are tied to operands in TiedGroup which must be
  996. // earlier. Find the number of operands between the two groups.
  997. unsigned Delta = i - GroupIdx[TiedGroup];
  998. // OpIdx is a use tied to TiedGroup.
  999. if (OpIdxGroup == CurGroup)
  1000. return OpIdx - Delta;
  1001. // OpIdx is a def tied to this use group.
  1002. if (OpIdxGroup == TiedGroup)
  1003. return OpIdx + Delta;
  1004. }
  1005. llvm_unreachable("Invalid tied operand on inline asm");
  1006. }
  1007. /// clearKillInfo - Clears kill flags on all operands.
  1008. ///
  1009. void MachineInstr::clearKillInfo() {
  1010. for (MachineOperand &MO : operands()) {
  1011. if (MO.isReg() && MO.isUse())
  1012. MO.setIsKill(false);
  1013. }
  1014. }
  1015. void MachineInstr::substituteRegister(Register FromReg, Register ToReg,
  1016. unsigned SubIdx,
  1017. const TargetRegisterInfo &RegInfo) {
  1018. if (Register::isPhysicalRegister(ToReg)) {
  1019. if (SubIdx)
  1020. ToReg = RegInfo.getSubReg(ToReg, SubIdx);
  1021. for (MachineOperand &MO : operands()) {
  1022. if (!MO.isReg() || MO.getReg() != FromReg)
  1023. continue;
  1024. MO.substPhysReg(ToReg, RegInfo);
  1025. }
  1026. } else {
  1027. for (MachineOperand &MO : operands()) {
  1028. if (!MO.isReg() || MO.getReg() != FromReg)
  1029. continue;
  1030. MO.substVirtReg(ToReg, SubIdx, RegInfo);
  1031. }
  1032. }
  1033. }
  1034. /// isSafeToMove - Return true if it is safe to move this instruction. If
  1035. /// SawStore is set to true, it means that there is a store (or call) between
  1036. /// the instruction's location and its intended destination.
  1037. bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
  1038. // Ignore stuff that we obviously can't move.
  1039. //
  1040. // Treat volatile loads as stores. This is not strictly necessary for
  1041. // volatiles, but it is required for atomic loads. It is not allowed to move
  1042. // a load across an atomic load with Ordering > Monotonic.
  1043. if (mayStore() || isCall() || isPHI() ||
  1044. (mayLoad() && hasOrderedMemoryRef())) {
  1045. SawStore = true;
  1046. return false;
  1047. }
  1048. if (isPosition() || isDebugInstr() || isTerminator() ||
  1049. mayRaiseFPException() || hasUnmodeledSideEffects())
  1050. return false;
  1051. // See if this instruction does a load. If so, we have to guarantee that the
  1052. // loaded value doesn't change between the load and the its intended
  1053. // destination. The check for isInvariantLoad gives the targe the chance to
  1054. // classify the load as always returning a constant, e.g. a constant pool
  1055. // load.
  1056. if (mayLoad() && !isDereferenceableInvariantLoad(AA))
  1057. // Otherwise, this is a real load. If there is a store between the load and
  1058. // end of block, we can't move it.
  1059. return !SawStore;
  1060. return true;
  1061. }
  1062. bool MachineInstr::mayAlias(AliasAnalysis *AA, const MachineInstr &Other,
  1063. bool UseTBAA) const {
  1064. const MachineFunction *MF = getMF();
  1065. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1066. const MachineFrameInfo &MFI = MF->getFrameInfo();
  1067. // If neither instruction stores to memory, they can't alias in any
  1068. // meaningful way, even if they read from the same address.
  1069. if (!mayStore() && !Other.mayStore())
  1070. return false;
  1071. // Let the target decide if memory accesses cannot possibly overlap.
  1072. if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
  1073. return false;
  1074. // FIXME: Need to handle multiple memory operands to support all targets.
  1075. if (!hasOneMemOperand() || !Other.hasOneMemOperand())
  1076. return true;
  1077. MachineMemOperand *MMOa = *memoperands_begin();
  1078. MachineMemOperand *MMOb = *Other.memoperands_begin();
  1079. // The following interface to AA is fashioned after DAGCombiner::isAlias
  1080. // and operates with MachineMemOperand offset with some important
  1081. // assumptions:
  1082. // - LLVM fundamentally assumes flat address spaces.
  1083. // - MachineOperand offset can *only* result from legalization and
  1084. // cannot affect queries other than the trivial case of overlap
  1085. // checking.
  1086. // - These offsets never wrap and never step outside
  1087. // of allocated objects.
  1088. // - There should never be any negative offsets here.
  1089. //
  1090. // FIXME: Modify API to hide this math from "user"
  1091. // Even before we go to AA we can reason locally about some
  1092. // memory objects. It can save compile time, and possibly catch some
  1093. // corner cases not currently covered.
  1094. int64_t OffsetA = MMOa->getOffset();
  1095. int64_t OffsetB = MMOb->getOffset();
  1096. int64_t MinOffset = std::min(OffsetA, OffsetB);
  1097. uint64_t WidthA = MMOa->getSize();
  1098. uint64_t WidthB = MMOb->getSize();
  1099. bool KnownWidthA = WidthA != MemoryLocation::UnknownSize;
  1100. bool KnownWidthB = WidthB != MemoryLocation::UnknownSize;
  1101. const Value *ValA = MMOa->getValue();
  1102. const Value *ValB = MMOb->getValue();
  1103. bool SameVal = (ValA && ValB && (ValA == ValB));
  1104. if (!SameVal) {
  1105. const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
  1106. const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
  1107. if (PSVa && ValB && !PSVa->mayAlias(&MFI))
  1108. return false;
  1109. if (PSVb && ValA && !PSVb->mayAlias(&MFI))
  1110. return false;
  1111. if (PSVa && PSVb && (PSVa == PSVb))
  1112. SameVal = true;
  1113. }
  1114. if (SameVal) {
  1115. if (!KnownWidthA || !KnownWidthB)
  1116. return true;
  1117. int64_t MaxOffset = std::max(OffsetA, OffsetB);
  1118. int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
  1119. return (MinOffset + LowWidth > MaxOffset);
  1120. }
  1121. if (!AA)
  1122. return true;
  1123. if (!ValA || !ValB)
  1124. return true;
  1125. assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
  1126. assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
  1127. int64_t OverlapA = KnownWidthA ? WidthA + OffsetA - MinOffset
  1128. : MemoryLocation::UnknownSize;
  1129. int64_t OverlapB = KnownWidthB ? WidthB + OffsetB - MinOffset
  1130. : MemoryLocation::UnknownSize;
  1131. AliasResult AAResult = AA->alias(
  1132. MemoryLocation(ValA, OverlapA,
  1133. UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
  1134. MemoryLocation(ValB, OverlapB,
  1135. UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
  1136. return (AAResult != NoAlias);
  1137. }
  1138. /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
  1139. /// or volatile memory reference, or if the information describing the memory
  1140. /// reference is not available. Return false if it is known to have no ordered
  1141. /// memory references.
  1142. bool MachineInstr::hasOrderedMemoryRef() const {
  1143. // An instruction known never to access memory won't have a volatile access.
  1144. if (!mayStore() &&
  1145. !mayLoad() &&
  1146. !isCall() &&
  1147. !hasUnmodeledSideEffects())
  1148. return false;
  1149. // Otherwise, if the instruction has no memory reference information,
  1150. // conservatively assume it wasn't preserved.
  1151. if (memoperands_empty())
  1152. return true;
  1153. // Check if any of our memory operands are ordered.
  1154. return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
  1155. return !MMO->isUnordered();
  1156. });
  1157. }
  1158. /// isDereferenceableInvariantLoad - Return true if this instruction will never
  1159. /// trap and is loading from a location whose value is invariant across a run of
  1160. /// this function.
  1161. bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
  1162. // If the instruction doesn't load at all, it isn't an invariant load.
  1163. if (!mayLoad())
  1164. return false;
  1165. // If the instruction has lost its memoperands, conservatively assume that
  1166. // it may not be an invariant load.
  1167. if (memoperands_empty())
  1168. return false;
  1169. const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
  1170. for (MachineMemOperand *MMO : memoperands()) {
  1171. if (!MMO->isUnordered())
  1172. // If the memory operand has ordering side effects, we can't move the
  1173. // instruction. Such an instruction is technically an invariant load,
  1174. // but the caller code would need updated to expect that.
  1175. return false;
  1176. if (MMO->isStore()) return false;
  1177. if (MMO->isInvariant() && MMO->isDereferenceable())
  1178. continue;
  1179. // A load from a constant PseudoSourceValue is invariant.
  1180. if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
  1181. if (PSV->isConstant(&MFI))
  1182. continue;
  1183. if (const Value *V = MMO->getValue()) {
  1184. // If we have an AliasAnalysis, ask it whether the memory is constant.
  1185. if (AA &&
  1186. AA->pointsToConstantMemory(
  1187. MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
  1188. continue;
  1189. }
  1190. // Otherwise assume conservatively.
  1191. return false;
  1192. }
  1193. // Everything checks out.
  1194. return true;
  1195. }
  1196. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1197. /// merges together the same virtual register, return the register, otherwise
  1198. /// return 0.
  1199. unsigned MachineInstr::isConstantValuePHI() const {
  1200. if (!isPHI())
  1201. return 0;
  1202. assert(getNumOperands() >= 3 &&
  1203. "It's illegal to have a PHI without source operands");
  1204. Register Reg = getOperand(1).getReg();
  1205. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1206. if (getOperand(i).getReg() != Reg)
  1207. return 0;
  1208. return Reg;
  1209. }
  1210. bool MachineInstr::hasUnmodeledSideEffects() const {
  1211. if (hasProperty(MCID::UnmodeledSideEffects))
  1212. return true;
  1213. if (isInlineAsm()) {
  1214. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1215. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1216. return true;
  1217. }
  1218. return false;
  1219. }
  1220. bool MachineInstr::isLoadFoldBarrier() const {
  1221. return mayStore() || isCall() || hasUnmodeledSideEffects();
  1222. }
  1223. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1224. ///
  1225. bool MachineInstr::allDefsAreDead() const {
  1226. for (const MachineOperand &MO : operands()) {
  1227. if (!MO.isReg() || MO.isUse())
  1228. continue;
  1229. if (!MO.isDead())
  1230. return false;
  1231. }
  1232. return true;
  1233. }
  1234. /// copyImplicitOps - Copy implicit register operands from specified
  1235. /// instruction to this instruction.
  1236. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1237. const MachineInstr &MI) {
  1238. for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
  1239. i != e; ++i) {
  1240. const MachineOperand &MO = MI.getOperand(i);
  1241. if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
  1242. addOperand(MF, MO);
  1243. }
  1244. }
  1245. bool MachineInstr::hasComplexRegisterTies() const {
  1246. const MCInstrDesc &MCID = getDesc();
  1247. for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
  1248. const auto &Operand = getOperand(I);
  1249. if (!Operand.isReg() || Operand.isDef())
  1250. // Ignore the defined registers as MCID marks only the uses as tied.
  1251. continue;
  1252. int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
  1253. int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
  1254. if (ExpectedTiedIdx != TiedIdx)
  1255. return true;
  1256. }
  1257. return false;
  1258. }
  1259. LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
  1260. const MachineRegisterInfo &MRI) const {
  1261. const MachineOperand &Op = getOperand(OpIdx);
  1262. if (!Op.isReg())
  1263. return LLT{};
  1264. if (isVariadic() || OpIdx >= getNumExplicitOperands())
  1265. return MRI.getType(Op.getReg());
  1266. auto &OpInfo = getDesc().OpInfo[OpIdx];
  1267. if (!OpInfo.isGenericType())
  1268. return MRI.getType(Op.getReg());
  1269. if (PrintedTypes[OpInfo.getGenericTypeIndex()])
  1270. return LLT{};
  1271. LLT TypeToPrint = MRI.getType(Op.getReg());
  1272. // Don't mark the type index printed if it wasn't actually printed: maybe
  1273. // another operand with the same type index has an actual type attached:
  1274. if (TypeToPrint.isValid())
  1275. PrintedTypes.set(OpInfo.getGenericTypeIndex());
  1276. return TypeToPrint;
  1277. }
  1278. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1279. LLVM_DUMP_METHOD void MachineInstr::dump() const {
  1280. dbgs() << " ";
  1281. print(dbgs());
  1282. }
  1283. #endif
  1284. void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
  1285. bool SkipDebugLoc, bool AddNewLine,
  1286. const TargetInstrInfo *TII) const {
  1287. const Module *M = nullptr;
  1288. const Function *F = nullptr;
  1289. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1290. F = &MF->getFunction();
  1291. M = F->getParent();
  1292. if (!TII)
  1293. TII = MF->getSubtarget().getInstrInfo();
  1294. }
  1295. ModuleSlotTracker MST(M);
  1296. if (F)
  1297. MST.incorporateFunction(*F);
  1298. print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, AddNewLine, TII);
  1299. }
  1300. void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
  1301. bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
  1302. bool AddNewLine, const TargetInstrInfo *TII) const {
  1303. // We can be a bit tidier if we know the MachineFunction.
  1304. const MachineFunction *MF = nullptr;
  1305. const TargetRegisterInfo *TRI = nullptr;
  1306. const MachineRegisterInfo *MRI = nullptr;
  1307. const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
  1308. tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
  1309. if (isCFIInstruction())
  1310. assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
  1311. SmallBitVector PrintedTypes(8);
  1312. bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies();
  1313. auto getTiedOperandIdx = [&](unsigned OpIdx) {
  1314. if (!ShouldPrintRegisterTies)
  1315. return 0U;
  1316. const MachineOperand &MO = getOperand(OpIdx);
  1317. if (MO.isReg() && MO.isTied() && !MO.isDef())
  1318. return findTiedOperandIdx(OpIdx);
  1319. return 0U;
  1320. };
  1321. unsigned StartOp = 0;
  1322. unsigned e = getNumOperands();
  1323. // Print explicitly defined operands on the left of an assignment syntax.
  1324. while (StartOp < e) {
  1325. const MachineOperand &MO = getOperand(StartOp);
  1326. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  1327. break;
  1328. if (StartOp != 0)
  1329. OS << ", ";
  1330. LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
  1331. unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
  1332. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/false, IsStandalone,
  1333. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1334. ++StartOp;
  1335. }
  1336. if (StartOp != 0)
  1337. OS << " = ";
  1338. if (getFlag(MachineInstr::FrameSetup))
  1339. OS << "frame-setup ";
  1340. if (getFlag(MachineInstr::FrameDestroy))
  1341. OS << "frame-destroy ";
  1342. if (getFlag(MachineInstr::FmNoNans))
  1343. OS << "nnan ";
  1344. if (getFlag(MachineInstr::FmNoInfs))
  1345. OS << "ninf ";
  1346. if (getFlag(MachineInstr::FmNsz))
  1347. OS << "nsz ";
  1348. if (getFlag(MachineInstr::FmArcp))
  1349. OS << "arcp ";
  1350. if (getFlag(MachineInstr::FmContract))
  1351. OS << "contract ";
  1352. if (getFlag(MachineInstr::FmAfn))
  1353. OS << "afn ";
  1354. if (getFlag(MachineInstr::FmReassoc))
  1355. OS << "reassoc ";
  1356. if (getFlag(MachineInstr::NoUWrap))
  1357. OS << "nuw ";
  1358. if (getFlag(MachineInstr::NoSWrap))
  1359. OS << "nsw ";
  1360. if (getFlag(MachineInstr::IsExact))
  1361. OS << "exact ";
  1362. if (getFlag(MachineInstr::FPExcept))
  1363. OS << "fpexcept ";
  1364. // Print the opcode name.
  1365. if (TII)
  1366. OS << TII->getName(getOpcode());
  1367. else
  1368. OS << "UNKNOWN";
  1369. if (SkipOpers)
  1370. return;
  1371. // Print the rest of the operands.
  1372. bool FirstOp = true;
  1373. unsigned AsmDescOp = ~0u;
  1374. unsigned AsmOpCount = 0;
  1375. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1376. // Print asm string.
  1377. OS << " ";
  1378. const unsigned OpIdx = InlineAsm::MIOp_AsmString;
  1379. LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
  1380. unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
  1381. getOperand(OpIdx).print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1382. ShouldPrintRegisterTies, TiedOperandIdx, TRI,
  1383. IntrinsicInfo);
  1384. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1385. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1386. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1387. OS << " [sideeffect]";
  1388. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1389. OS << " [mayload]";
  1390. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1391. OS << " [maystore]";
  1392. if (ExtraInfo & InlineAsm::Extra_IsConvergent)
  1393. OS << " [isconvergent]";
  1394. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1395. OS << " [alignstack]";
  1396. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1397. OS << " [attdialect]";
  1398. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1399. OS << " [inteldialect]";
  1400. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1401. FirstOp = false;
  1402. }
  1403. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1404. const MachineOperand &MO = getOperand(i);
  1405. if (FirstOp) FirstOp = false; else OS << ",";
  1406. OS << " ";
  1407. if (isDebugValue() && MO.isMetadata()) {
  1408. // Pretty print DBG_VALUE instructions.
  1409. auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
  1410. if (DIV && !DIV->getName().empty())
  1411. OS << "!\"" << DIV->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 (isDebugLabel() && MO.isMetadata()) {
  1419. // Pretty print DBG_LABEL instructions.
  1420. auto *DIL = dyn_cast<DILabel>(MO.getMetadata());
  1421. if (DIL && !DIL->getName().empty())
  1422. OS << "\"" << DIL->getName() << '\"';
  1423. else {
  1424. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1425. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1426. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1427. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1428. }
  1429. } else if (i == AsmDescOp && MO.isImm()) {
  1430. // Pretty print the inline asm operand descriptor.
  1431. OS << '$' << AsmOpCount++;
  1432. unsigned Flag = MO.getImm();
  1433. switch (InlineAsm::getKind(Flag)) {
  1434. case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
  1435. case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
  1436. case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
  1437. case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
  1438. case InlineAsm::Kind_Imm: OS << ":[imm"; break;
  1439. case InlineAsm::Kind_Mem: OS << ":[mem"; break;
  1440. default: OS << ":[??" << InlineAsm::getKind(Flag); break;
  1441. }
  1442. unsigned RCID = 0;
  1443. if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
  1444. InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1445. if (TRI) {
  1446. OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
  1447. } else
  1448. OS << ":RC" << RCID;
  1449. }
  1450. if (InlineAsm::isMemKind(Flag)) {
  1451. unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
  1452. switch (MCID) {
  1453. case InlineAsm::Constraint_es: OS << ":es"; break;
  1454. case InlineAsm::Constraint_i: OS << ":i"; break;
  1455. case InlineAsm::Constraint_m: OS << ":m"; break;
  1456. case InlineAsm::Constraint_o: OS << ":o"; break;
  1457. case InlineAsm::Constraint_v: OS << ":v"; break;
  1458. case InlineAsm::Constraint_Q: OS << ":Q"; break;
  1459. case InlineAsm::Constraint_R: OS << ":R"; break;
  1460. case InlineAsm::Constraint_S: OS << ":S"; break;
  1461. case InlineAsm::Constraint_T: OS << ":T"; break;
  1462. case InlineAsm::Constraint_Um: OS << ":Um"; break;
  1463. case InlineAsm::Constraint_Un: OS << ":Un"; break;
  1464. case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
  1465. case InlineAsm::Constraint_Us: OS << ":Us"; break;
  1466. case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
  1467. case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
  1468. case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
  1469. case InlineAsm::Constraint_X: OS << ":X"; break;
  1470. case InlineAsm::Constraint_Z: OS << ":Z"; break;
  1471. case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
  1472. case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
  1473. default: OS << ":?"; break;
  1474. }
  1475. }
  1476. unsigned TiedTo = 0;
  1477. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1478. OS << " tiedto:$" << TiedTo;
  1479. OS << ']';
  1480. // Compute the index of the next operand descriptor.
  1481. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1482. } else {
  1483. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1484. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1485. if (MO.isImm() && isOperandSubregIdx(i))
  1486. MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
  1487. else
  1488. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1489. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1490. }
  1491. }
  1492. // Print any optional symbols attached to this instruction as-if they were
  1493. // operands.
  1494. if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) {
  1495. if (!FirstOp) {
  1496. FirstOp = false;
  1497. OS << ',';
  1498. }
  1499. OS << " pre-instr-symbol ";
  1500. MachineOperand::printSymbol(OS, *PreInstrSymbol);
  1501. }
  1502. if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) {
  1503. if (!FirstOp) {
  1504. FirstOp = false;
  1505. OS << ',';
  1506. }
  1507. OS << " post-instr-symbol ";
  1508. MachineOperand::printSymbol(OS, *PostInstrSymbol);
  1509. }
  1510. if (!SkipDebugLoc) {
  1511. if (const DebugLoc &DL = getDebugLoc()) {
  1512. if (!FirstOp)
  1513. OS << ',';
  1514. OS << " debug-location ";
  1515. DL->printAsOperand(OS, MST);
  1516. }
  1517. }
  1518. if (!memoperands_empty()) {
  1519. SmallVector<StringRef, 0> SSNs;
  1520. const LLVMContext *Context = nullptr;
  1521. std::unique_ptr<LLVMContext> CtxPtr;
  1522. const MachineFrameInfo *MFI = nullptr;
  1523. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1524. MFI = &MF->getFrameInfo();
  1525. Context = &MF->getFunction().getContext();
  1526. } else {
  1527. CtxPtr = std::make_unique<LLVMContext>();
  1528. Context = CtxPtr.get();
  1529. }
  1530. OS << " :: ";
  1531. bool NeedComma = false;
  1532. for (const MachineMemOperand *Op : memoperands()) {
  1533. if (NeedComma)
  1534. OS << ", ";
  1535. Op->print(OS, MST, SSNs, *Context, MFI, TII);
  1536. NeedComma = true;
  1537. }
  1538. }
  1539. if (SkipDebugLoc)
  1540. return;
  1541. bool HaveSemi = false;
  1542. // Print debug location information.
  1543. if (const DebugLoc &DL = getDebugLoc()) {
  1544. if (!HaveSemi) {
  1545. OS << ';';
  1546. HaveSemi = true;
  1547. }
  1548. OS << ' ';
  1549. DL.print(OS);
  1550. }
  1551. // Print extra comments for DEBUG_VALUE.
  1552. if (isDebugValue() && getOperand(e - 2).isMetadata()) {
  1553. if (!HaveSemi) {
  1554. OS << ";";
  1555. HaveSemi = true;
  1556. }
  1557. auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
  1558. OS << " line no:" << DV->getLine();
  1559. if (auto *InlinedAt = debugLoc->getInlinedAt()) {
  1560. DebugLoc InlinedAtDL(InlinedAt);
  1561. if (InlinedAtDL && MF) {
  1562. OS << " inlined @[ ";
  1563. InlinedAtDL.print(OS);
  1564. OS << " ]";
  1565. }
  1566. }
  1567. if (isIndirectDebugValue())
  1568. OS << " indirect";
  1569. }
  1570. // TODO: DBG_LABEL
  1571. if (AddNewLine)
  1572. OS << '\n';
  1573. }
  1574. bool MachineInstr::addRegisterKilled(Register IncomingReg,
  1575. const TargetRegisterInfo *RegInfo,
  1576. bool AddIfNotFound) {
  1577. bool isPhysReg = Register::isPhysicalRegister(IncomingReg);
  1578. bool hasAliases = isPhysReg &&
  1579. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1580. bool Found = false;
  1581. SmallVector<unsigned,4> DeadOps;
  1582. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1583. MachineOperand &MO = getOperand(i);
  1584. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1585. continue;
  1586. // DEBUG_VALUE nodes do not contribute to code generation and should
  1587. // always be ignored. Failure to do so may result in trying to modify
  1588. // KILL flags on DEBUG_VALUE nodes.
  1589. if (MO.isDebug())
  1590. continue;
  1591. Register Reg = MO.getReg();
  1592. if (!Reg)
  1593. continue;
  1594. if (Reg == IncomingReg) {
  1595. if (!Found) {
  1596. if (MO.isKill())
  1597. // The register is already marked kill.
  1598. return true;
  1599. if (isPhysReg && isRegTiedToDefOperand(i))
  1600. // Two-address uses of physregs must not be marked kill.
  1601. return true;
  1602. MO.setIsKill();
  1603. Found = true;
  1604. }
  1605. } else if (hasAliases && MO.isKill() && Register::isPhysicalRegister(Reg)) {
  1606. // A super-register kill already exists.
  1607. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1608. return true;
  1609. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1610. DeadOps.push_back(i);
  1611. }
  1612. }
  1613. // Trim unneeded kill operands.
  1614. while (!DeadOps.empty()) {
  1615. unsigned OpIdx = DeadOps.back();
  1616. if (getOperand(OpIdx).isImplicit() &&
  1617. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1618. RemoveOperand(OpIdx);
  1619. else
  1620. getOperand(OpIdx).setIsKill(false);
  1621. DeadOps.pop_back();
  1622. }
  1623. // If not found, this means an alias of one of the operands is killed. Add a
  1624. // new implicit operand if required.
  1625. if (!Found && AddIfNotFound) {
  1626. addOperand(MachineOperand::CreateReg(IncomingReg,
  1627. false /*IsDef*/,
  1628. true /*IsImp*/,
  1629. true /*IsKill*/));
  1630. return true;
  1631. }
  1632. return Found;
  1633. }
  1634. void MachineInstr::clearRegisterKills(Register Reg,
  1635. const TargetRegisterInfo *RegInfo) {
  1636. if (!Register::isPhysicalRegister(Reg))
  1637. RegInfo = nullptr;
  1638. for (MachineOperand &MO : operands()) {
  1639. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1640. continue;
  1641. Register OpReg = MO.getReg();
  1642. if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
  1643. MO.setIsKill(false);
  1644. }
  1645. }
  1646. bool MachineInstr::addRegisterDead(Register Reg,
  1647. const TargetRegisterInfo *RegInfo,
  1648. bool AddIfNotFound) {
  1649. bool isPhysReg = Register::isPhysicalRegister(Reg);
  1650. bool hasAliases = isPhysReg &&
  1651. MCRegAliasIterator(Reg, RegInfo, false).isValid();
  1652. bool Found = false;
  1653. SmallVector<unsigned,4> DeadOps;
  1654. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1655. MachineOperand &MO = getOperand(i);
  1656. if (!MO.isReg() || !MO.isDef())
  1657. continue;
  1658. Register MOReg = MO.getReg();
  1659. if (!MOReg)
  1660. continue;
  1661. if (MOReg == Reg) {
  1662. MO.setIsDead();
  1663. Found = true;
  1664. } else if (hasAliases && MO.isDead() &&
  1665. Register::isPhysicalRegister(MOReg)) {
  1666. // There exists a super-register that's marked dead.
  1667. if (RegInfo->isSuperRegister(Reg, MOReg))
  1668. return true;
  1669. if (RegInfo->isSubRegister(Reg, MOReg))
  1670. DeadOps.push_back(i);
  1671. }
  1672. }
  1673. // Trim unneeded dead operands.
  1674. while (!DeadOps.empty()) {
  1675. unsigned OpIdx = DeadOps.back();
  1676. if (getOperand(OpIdx).isImplicit() &&
  1677. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1678. RemoveOperand(OpIdx);
  1679. else
  1680. getOperand(OpIdx).setIsDead(false);
  1681. DeadOps.pop_back();
  1682. }
  1683. // If not found, this means an alias of one of the operands is dead. Add a
  1684. // new implicit operand if required.
  1685. if (Found || !AddIfNotFound)
  1686. return Found;
  1687. addOperand(MachineOperand::CreateReg(Reg,
  1688. true /*IsDef*/,
  1689. true /*IsImp*/,
  1690. false /*IsKill*/,
  1691. true /*IsDead*/));
  1692. return true;
  1693. }
  1694. void MachineInstr::clearRegisterDeads(Register Reg) {
  1695. for (MachineOperand &MO : operands()) {
  1696. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
  1697. continue;
  1698. MO.setIsDead(false);
  1699. }
  1700. }
  1701. void MachineInstr::setRegisterDefReadUndef(Register Reg, bool IsUndef) {
  1702. for (MachineOperand &MO : operands()) {
  1703. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
  1704. continue;
  1705. MO.setIsUndef(IsUndef);
  1706. }
  1707. }
  1708. void MachineInstr::addRegisterDefined(Register Reg,
  1709. const TargetRegisterInfo *RegInfo) {
  1710. if (Register::isPhysicalRegister(Reg)) {
  1711. MachineOperand *MO = findRegisterDefOperand(Reg, false, false, RegInfo);
  1712. if (MO)
  1713. return;
  1714. } else {
  1715. for (const MachineOperand &MO : operands()) {
  1716. if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
  1717. MO.getSubReg() == 0)
  1718. return;
  1719. }
  1720. }
  1721. addOperand(MachineOperand::CreateReg(Reg,
  1722. true /*IsDef*/,
  1723. true /*IsImp*/));
  1724. }
  1725. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
  1726. const TargetRegisterInfo &TRI) {
  1727. bool HasRegMask = false;
  1728. for (MachineOperand &MO : operands()) {
  1729. if (MO.isRegMask()) {
  1730. HasRegMask = true;
  1731. continue;
  1732. }
  1733. if (!MO.isReg() || !MO.isDef()) continue;
  1734. Register Reg = MO.getReg();
  1735. if (!Reg.isPhysical())
  1736. continue;
  1737. // If there are no uses, including partial uses, the def is dead.
  1738. if (llvm::none_of(UsedRegs,
  1739. [&](MCRegister Use) { return TRI.regsOverlap(Use, Reg); }))
  1740. MO.setIsDead();
  1741. }
  1742. // This is a call with a register mask operand.
  1743. // Mask clobbers are always dead, so add defs for the non-dead defines.
  1744. if (HasRegMask)
  1745. for (ArrayRef<Register>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1746. I != E; ++I)
  1747. addRegisterDefined(*I, &TRI);
  1748. }
  1749. unsigned
  1750. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  1751. // Build up a buffer of hash code components.
  1752. SmallVector<size_t, 8> HashComponents;
  1753. HashComponents.reserve(MI->getNumOperands() + 1);
  1754. HashComponents.push_back(MI->getOpcode());
  1755. for (const MachineOperand &MO : MI->operands()) {
  1756. if (MO.isReg() && MO.isDef() && Register::isVirtualRegister(MO.getReg()))
  1757. continue; // Skip virtual register defs.
  1758. HashComponents.push_back(hash_value(MO));
  1759. }
  1760. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  1761. }
  1762. void MachineInstr::emitError(StringRef Msg) const {
  1763. // Find the source location cookie.
  1764. unsigned LocCookie = 0;
  1765. const MDNode *LocMD = nullptr;
  1766. for (unsigned i = getNumOperands(); i != 0; --i) {
  1767. if (getOperand(i-1).isMetadata() &&
  1768. (LocMD = getOperand(i-1).getMetadata()) &&
  1769. LocMD->getNumOperands() != 0) {
  1770. if (const ConstantInt *CI =
  1771. mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
  1772. LocCookie = CI->getZExtValue();
  1773. break;
  1774. }
  1775. }
  1776. }
  1777. if (const MachineBasicBlock *MBB = getParent())
  1778. if (const MachineFunction *MF = MBB->getParent())
  1779. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  1780. report_fatal_error(Msg);
  1781. }
  1782. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1783. const MCInstrDesc &MCID, bool IsIndirect,
  1784. Register Reg, const MDNode *Variable,
  1785. const MDNode *Expr) {
  1786. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1787. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1788. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1789. "Expected inlined-at fields to agree");
  1790. auto MIB = BuildMI(MF, DL, MCID).addReg(Reg, RegState::Debug);
  1791. if (IsIndirect)
  1792. MIB.addImm(0U);
  1793. else
  1794. MIB.addReg(0U, RegState::Debug);
  1795. return MIB.addMetadata(Variable).addMetadata(Expr);
  1796. }
  1797. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1798. const MCInstrDesc &MCID, bool IsIndirect,
  1799. MachineOperand &MO, const MDNode *Variable,
  1800. const MDNode *Expr) {
  1801. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1802. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1803. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1804. "Expected inlined-at fields to agree");
  1805. if (MO.isReg())
  1806. return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr);
  1807. auto MIB = BuildMI(MF, DL, MCID).add(MO);
  1808. if (IsIndirect)
  1809. MIB.addImm(0U);
  1810. else
  1811. MIB.addReg(0U, RegState::Debug);
  1812. return MIB.addMetadata(Variable).addMetadata(Expr);
  1813. }
  1814. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1815. MachineBasicBlock::iterator I,
  1816. const DebugLoc &DL, const MCInstrDesc &MCID,
  1817. bool IsIndirect, Register Reg,
  1818. const MDNode *Variable, const MDNode *Expr) {
  1819. MachineFunction &MF = *BB.getParent();
  1820. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
  1821. BB.insert(I, MI);
  1822. return MachineInstrBuilder(MF, MI);
  1823. }
  1824. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1825. MachineBasicBlock::iterator I,
  1826. const DebugLoc &DL, const MCInstrDesc &MCID,
  1827. bool IsIndirect, MachineOperand &MO,
  1828. const MDNode *Variable, const MDNode *Expr) {
  1829. MachineFunction &MF = *BB.getParent();
  1830. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr);
  1831. BB.insert(I, MI);
  1832. return MachineInstrBuilder(MF, *MI);
  1833. }
  1834. /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
  1835. /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
  1836. static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
  1837. assert(MI.getOperand(0).isReg() && "can't spill non-register");
  1838. assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
  1839. "Expected inlined-at fields to agree");
  1840. const DIExpression *Expr = MI.getDebugExpression();
  1841. if (MI.isIndirectDebugValue()) {
  1842. assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
  1843. Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
  1844. }
  1845. return Expr;
  1846. }
  1847. MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
  1848. MachineBasicBlock::iterator I,
  1849. const MachineInstr &Orig,
  1850. int FrameIndex) {
  1851. const DIExpression *Expr = computeExprForSpill(Orig);
  1852. return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
  1853. .addFrameIndex(FrameIndex)
  1854. .addImm(0U)
  1855. .addMetadata(Orig.getDebugVariable())
  1856. .addMetadata(Expr);
  1857. }
  1858. void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
  1859. const DIExpression *Expr = computeExprForSpill(Orig);
  1860. Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
  1861. Orig.getOperand(1).ChangeToImmediate(0U);
  1862. Orig.getOperand(3).setMetadata(Expr);
  1863. }
  1864. void MachineInstr::collectDebugValues(
  1865. SmallVectorImpl<MachineInstr *> &DbgValues) {
  1866. MachineInstr &MI = *this;
  1867. if (!MI.getOperand(0).isReg())
  1868. return;
  1869. MachineBasicBlock::iterator DI = MI; ++DI;
  1870. for (MachineBasicBlock::iterator DE = MI.getParent()->end();
  1871. DI != DE; ++DI) {
  1872. if (!DI->isDebugValue())
  1873. return;
  1874. if (DI->getOperand(0).isReg() &&
  1875. DI->getOperand(0).getReg() == MI.getOperand(0).getReg())
  1876. DbgValues.push_back(&*DI);
  1877. }
  1878. }
  1879. void MachineInstr::changeDebugValuesDefReg(Register Reg) {
  1880. // Collect matching debug values.
  1881. SmallVector<MachineInstr *, 2> DbgValues;
  1882. if (!getOperand(0).isReg())
  1883. return;
  1884. unsigned DefReg = getOperand(0).getReg();
  1885. auto *MRI = getRegInfo();
  1886. for (auto &MO : MRI->use_operands(DefReg)) {
  1887. auto *DI = MO.getParent();
  1888. if (!DI->isDebugValue())
  1889. continue;
  1890. if (DI->getOperand(0).isReg() &&
  1891. DI->getOperand(0).getReg() == DefReg){
  1892. DbgValues.push_back(DI);
  1893. }
  1894. }
  1895. // Propagate Reg to debug value instructions.
  1896. for (auto *DBI : DbgValues)
  1897. DBI->getOperand(0).setReg(Reg);
  1898. }
  1899. using MMOList = SmallVector<const MachineMemOperand *, 2>;
  1900. static unsigned getSpillSlotSize(MMOList &Accesses,
  1901. const MachineFrameInfo &MFI) {
  1902. unsigned Size = 0;
  1903. for (auto A : Accesses)
  1904. if (MFI.isSpillSlotObjectIndex(
  1905. cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
  1906. ->getFrameIndex()))
  1907. Size += A->getSize();
  1908. return Size;
  1909. }
  1910. Optional<unsigned>
  1911. MachineInstr::getSpillSize(const TargetInstrInfo *TII) const {
  1912. int FI;
  1913. if (TII->isStoreToStackSlotPostFE(*this, FI)) {
  1914. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  1915. if (MFI.isSpillSlotObjectIndex(FI))
  1916. return (*memoperands_begin())->getSize();
  1917. }
  1918. return None;
  1919. }
  1920. Optional<unsigned>
  1921. MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const {
  1922. MMOList Accesses;
  1923. if (TII->hasStoreToStackSlot(*this, Accesses))
  1924. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  1925. return None;
  1926. }
  1927. Optional<unsigned>
  1928. MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const {
  1929. int FI;
  1930. if (TII->isLoadFromStackSlotPostFE(*this, FI)) {
  1931. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  1932. if (MFI.isSpillSlotObjectIndex(FI))
  1933. return (*memoperands_begin())->getSize();
  1934. }
  1935. return None;
  1936. }
  1937. Optional<unsigned>
  1938. MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const {
  1939. MMOList Accesses;
  1940. if (TII->hasLoadFromStackSlot(*this, Accesses))
  1941. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  1942. return None;
  1943. }