MachineInstr.cpp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363
  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/StackMaps.h"
  37. #include "llvm/CodeGen/TargetInstrInfo.h"
  38. #include "llvm/CodeGen/TargetRegisterInfo.h"
  39. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  40. #include "llvm/Config/llvm-config.h"
  41. #include "llvm/IR/Constants.h"
  42. #include "llvm/IR/DebugInfoMetadata.h"
  43. #include "llvm/IR/DebugLoc.h"
  44. #include "llvm/IR/DerivedTypes.h"
  45. #include "llvm/IR/Function.h"
  46. #include "llvm/IR/InlineAsm.h"
  47. #include "llvm/IR/InstrTypes.h"
  48. #include "llvm/IR/Intrinsics.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/Metadata.h"
  51. #include "llvm/IR/Module.h"
  52. #include "llvm/IR/ModuleSlotTracker.h"
  53. #include "llvm/IR/Operator.h"
  54. #include "llvm/IR/Type.h"
  55. #include "llvm/IR/Value.h"
  56. #include "llvm/MC/MCInstrDesc.h"
  57. #include "llvm/MC/MCRegisterInfo.h"
  58. #include "llvm/MC/MCSymbol.h"
  59. #include "llvm/Support/Casting.h"
  60. #include "llvm/Support/CommandLine.h"
  61. #include "llvm/Support/Compiler.h"
  62. #include "llvm/Support/Debug.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include "llvm/Support/FormattedStream.h"
  65. #include "llvm/Support/LowLevelTypeImpl.h"
  66. #include "llvm/Support/MathExtras.h"
  67. #include "llvm/Support/raw_ostream.h"
  68. #include "llvm/Target/TargetIntrinsicInfo.h"
  69. #include "llvm/Target/TargetMachine.h"
  70. #include <algorithm>
  71. #include <cassert>
  72. #include <cstddef>
  73. #include <cstdint>
  74. #include <cstring>
  75. #include <iterator>
  76. #include <utility>
  77. using namespace llvm;
  78. static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) {
  79. if (const MachineBasicBlock *MBB = MI.getParent())
  80. if (const MachineFunction *MF = MBB->getParent())
  81. return MF;
  82. return nullptr;
  83. }
  84. // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
  85. // it.
  86. static void tryToGetTargetInfo(const MachineInstr &MI,
  87. const TargetRegisterInfo *&TRI,
  88. const MachineRegisterInfo *&MRI,
  89. const TargetIntrinsicInfo *&IntrinsicInfo,
  90. const TargetInstrInfo *&TII) {
  91. if (const MachineFunction *MF = getMFIfAvailable(MI)) {
  92. TRI = MF->getSubtarget().getRegisterInfo();
  93. MRI = &MF->getRegInfo();
  94. IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
  95. TII = MF->getSubtarget().getInstrInfo();
  96. }
  97. }
  98. void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
  99. if (MCID->ImplicitDefs)
  100. for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
  101. ++ImpDefs)
  102. addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
  103. if (MCID->ImplicitUses)
  104. for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
  105. ++ImpUses)
  106. addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
  107. }
  108. /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
  109. /// implicit operands. It reserves space for the number of operands specified by
  110. /// the MCInstrDesc.
  111. MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &TID,
  112. DebugLoc DL, bool NoImp)
  113. : MCID(&TID), DbgLoc(std::move(DL)), DebugInstrNum(0) {
  114. assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor");
  115. // Reserve space for the expected number of operands.
  116. if (unsigned NumOps = MCID->getNumOperands() +
  117. MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
  118. CapOperands = OperandCapacity::get(NumOps);
  119. Operands = MF.allocateOperandArray(CapOperands);
  120. }
  121. if (!NoImp)
  122. addImplicitDefUseOperands(MF);
  123. }
  124. /// MachineInstr ctor - Copies MachineInstr arg exactly.
  125. /// Does not copy the number from debug instruction numbering, to preserve
  126. /// uniqueness.
  127. MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
  128. : MCID(&MI.getDesc()), Info(MI.Info), DbgLoc(MI.getDebugLoc()),
  129. DebugInstrNum(0) {
  130. assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor");
  131. CapOperands = OperandCapacity::get(MI.getNumOperands());
  132. Operands = MF.allocateOperandArray(CapOperands);
  133. // Copy operands.
  134. for (const MachineOperand &MO : MI.operands())
  135. addOperand(MF, MO);
  136. // Copy all the sensible flags.
  137. setFlags(MI.Flags);
  138. }
  139. void MachineInstr::moveBefore(MachineInstr *MovePos) {
  140. MovePos->getParent()->splice(MovePos, getParent(), getIterator());
  141. }
  142. /// getRegInfo - If this instruction is embedded into a MachineFunction,
  143. /// return the MachineRegisterInfo object for the current function, otherwise
  144. /// return null.
  145. MachineRegisterInfo *MachineInstr::getRegInfo() {
  146. if (MachineBasicBlock *MBB = getParent())
  147. return &MBB->getParent()->getRegInfo();
  148. return nullptr;
  149. }
  150. /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
  151. /// this instruction from their respective use lists. This requires that the
  152. /// operands already be on their use lists.
  153. void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
  154. for (MachineOperand &MO : operands())
  155. if (MO.isReg())
  156. MRI.removeRegOperandFromUseList(&MO);
  157. }
  158. /// AddRegOperandsToUseLists - Add all of the register operands in
  159. /// this instruction from their respective use lists. This requires that the
  160. /// operands not be on their use lists yet.
  161. void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
  162. for (MachineOperand &MO : operands())
  163. if (MO.isReg())
  164. MRI.addRegOperandToUseList(&MO);
  165. }
  166. void MachineInstr::addOperand(const MachineOperand &Op) {
  167. MachineBasicBlock *MBB = getParent();
  168. assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
  169. MachineFunction *MF = MBB->getParent();
  170. assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
  171. addOperand(*MF, Op);
  172. }
  173. /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
  174. /// ranges. If MRI is non-null also update use-def chains.
  175. static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
  176. unsigned NumOps, MachineRegisterInfo *MRI) {
  177. if (MRI)
  178. return MRI->moveOperands(Dst, Src, NumOps);
  179. // MachineOperand is a trivially copyable type so we can just use memmove.
  180. assert(Dst && Src && "Unknown operands");
  181. std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
  182. }
  183. /// addOperand - Add the specified operand to the instruction. If it is an
  184. /// implicit operand, it is added to the end of the operand list. If it is
  185. /// an explicit operand it is added at the end of the explicit operand list
  186. /// (before the first implicit operand).
  187. void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
  188. assert(MCID && "Cannot add operands before providing an instr descriptor");
  189. // Check if we're adding one of our existing operands.
  190. if (&Op >= Operands && &Op < Operands + NumOperands) {
  191. // This is unusual: MI->addOperand(MI->getOperand(i)).
  192. // If adding Op requires reallocating or moving existing operands around,
  193. // the Op reference could go stale. Support it by copying Op.
  194. MachineOperand CopyOp(Op);
  195. return addOperand(MF, CopyOp);
  196. }
  197. // Find the insert location for the new operand. Implicit registers go at
  198. // the end, everything else goes before the implicit regs.
  199. //
  200. // FIXME: Allow mixed explicit and implicit operands on inline asm.
  201. // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
  202. // implicit-defs, but they must not be moved around. See the FIXME in
  203. // InstrEmitter.cpp.
  204. unsigned OpNo = getNumOperands();
  205. bool isImpReg = Op.isReg() && Op.isImplicit();
  206. if (!isImpReg && !isInlineAsm()) {
  207. while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
  208. --OpNo;
  209. assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
  210. }
  211. }
  212. #ifndef NDEBUG
  213. bool isDebugOp = Op.getType() == MachineOperand::MO_Metadata ||
  214. Op.getType() == MachineOperand::MO_MCSymbol;
  215. // OpNo now points as the desired insertion point. Unless this is a variadic
  216. // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
  217. // RegMask operands go between the explicit and implicit operands.
  218. assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
  219. OpNo < MCID->getNumOperands() || isDebugOp) &&
  220. "Trying to add an operand to a machine instr that is already done!");
  221. #endif
  222. MachineRegisterInfo *MRI = getRegInfo();
  223. // Determine if the Operands array needs to be reallocated.
  224. // Save the old capacity and operand array.
  225. OperandCapacity OldCap = CapOperands;
  226. MachineOperand *OldOperands = Operands;
  227. if (!OldOperands || OldCap.getSize() == getNumOperands()) {
  228. CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
  229. Operands = MF.allocateOperandArray(CapOperands);
  230. // Move the operands before the insertion point.
  231. if (OpNo)
  232. moveOperands(Operands, OldOperands, OpNo, MRI);
  233. }
  234. // Move the operands following the insertion point.
  235. if (OpNo != NumOperands)
  236. moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
  237. MRI);
  238. ++NumOperands;
  239. // Deallocate the old operand array.
  240. if (OldOperands != Operands && OldOperands)
  241. MF.deallocateOperandArray(OldCap, OldOperands);
  242. // Copy Op into place. It still needs to be inserted into the MRI use lists.
  243. MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
  244. NewMO->ParentMI = this;
  245. // When adding a register operand, tell MRI about it.
  246. if (NewMO->isReg()) {
  247. // Ensure isOnRegUseList() returns false, regardless of Op's status.
  248. NewMO->Contents.Reg.Prev = nullptr;
  249. // Ignore existing ties. This is not a property that can be copied.
  250. NewMO->TiedTo = 0;
  251. // Add the new operand to MRI, but only for instructions in an MBB.
  252. if (MRI)
  253. MRI->addRegOperandToUseList(NewMO);
  254. // The MCID operand information isn't accurate until we start adding
  255. // explicit operands. The implicit operands are added first, then the
  256. // explicits are inserted before them.
  257. if (!isImpReg) {
  258. // Tie uses to defs as indicated in MCInstrDesc.
  259. if (NewMO->isUse()) {
  260. int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
  261. if (DefIdx != -1)
  262. tieOperands(DefIdx, OpNo);
  263. }
  264. // If the register operand is flagged as early, mark the operand as such.
  265. if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
  266. NewMO->setIsEarlyClobber(true);
  267. }
  268. // Ensure debug instructions set debug flag on register uses.
  269. if (NewMO->isUse() && isDebugInstr())
  270. NewMO->setIsDebug();
  271. }
  272. }
  273. /// RemoveOperand - Erase an operand from an instruction, leaving it with one
  274. /// fewer operand than it started with.
  275. ///
  276. void MachineInstr::RemoveOperand(unsigned OpNo) {
  277. assert(OpNo < getNumOperands() && "Invalid operand number");
  278. untieRegOperand(OpNo);
  279. #ifndef NDEBUG
  280. // Moving tied operands would break the ties.
  281. for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
  282. if (Operands[i].isReg())
  283. assert(!Operands[i].isTied() && "Cannot move tied operands");
  284. #endif
  285. MachineRegisterInfo *MRI = getRegInfo();
  286. if (MRI && Operands[OpNo].isReg())
  287. MRI->removeRegOperandFromUseList(Operands + OpNo);
  288. // Don't call the MachineOperand destructor. A lot of this code depends on
  289. // MachineOperand having a trivial destructor anyway, and adding a call here
  290. // wouldn't make it 'destructor-correct'.
  291. if (unsigned N = NumOperands - 1 - OpNo)
  292. moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
  293. --NumOperands;
  294. }
  295. void MachineInstr::setExtraInfo(MachineFunction &MF,
  296. ArrayRef<MachineMemOperand *> MMOs,
  297. MCSymbol *PreInstrSymbol,
  298. MCSymbol *PostInstrSymbol,
  299. MDNode *HeapAllocMarker) {
  300. bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
  301. bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
  302. bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
  303. int NumPointers =
  304. MMOs.size() + HasPreInstrSymbol + HasPostInstrSymbol + HasHeapAllocMarker;
  305. // Drop all extra info if there is none.
  306. if (NumPointers <= 0) {
  307. Info.clear();
  308. return;
  309. }
  310. // If more than one pointer, then store out of line. Store heap alloc markers
  311. // out of line because PointerSumType cannot hold more than 4 tag types with
  312. // 32-bit pointers.
  313. // FIXME: Maybe we should make the symbols in the extra info mutable?
  314. else if (NumPointers > 1 || HasHeapAllocMarker) {
  315. Info.set<EIIK_OutOfLine>(MF.createMIExtraInfo(
  316. MMOs, PreInstrSymbol, PostInstrSymbol, HeapAllocMarker));
  317. return;
  318. }
  319. // Otherwise store the single pointer inline.
  320. if (HasPreInstrSymbol)
  321. Info.set<EIIK_PreInstrSymbol>(PreInstrSymbol);
  322. else if (HasPostInstrSymbol)
  323. Info.set<EIIK_PostInstrSymbol>(PostInstrSymbol);
  324. else
  325. Info.set<EIIK_MMO>(MMOs[0]);
  326. }
  327. void MachineInstr::dropMemRefs(MachineFunction &MF) {
  328. if (memoperands_empty())
  329. return;
  330. setExtraInfo(MF, {}, getPreInstrSymbol(), getPostInstrSymbol(),
  331. getHeapAllocMarker());
  332. }
  333. void MachineInstr::setMemRefs(MachineFunction &MF,
  334. ArrayRef<MachineMemOperand *> MMOs) {
  335. if (MMOs.empty()) {
  336. dropMemRefs(MF);
  337. return;
  338. }
  339. setExtraInfo(MF, MMOs, getPreInstrSymbol(), getPostInstrSymbol(),
  340. getHeapAllocMarker());
  341. }
  342. void MachineInstr::addMemOperand(MachineFunction &MF,
  343. MachineMemOperand *MO) {
  344. SmallVector<MachineMemOperand *, 2> MMOs;
  345. MMOs.append(memoperands_begin(), memoperands_end());
  346. MMOs.push_back(MO);
  347. setMemRefs(MF, MMOs);
  348. }
  349. void MachineInstr::cloneMemRefs(MachineFunction &MF, const MachineInstr &MI) {
  350. if (this == &MI)
  351. // Nothing to do for a self-clone!
  352. return;
  353. assert(&MF == MI.getMF() &&
  354. "Invalid machine functions when cloning memory refrences!");
  355. // See if we can just steal the extra info already allocated for the
  356. // instruction. We can do this whenever the pre- and post-instruction symbols
  357. // are the same (including null).
  358. if (getPreInstrSymbol() == MI.getPreInstrSymbol() &&
  359. getPostInstrSymbol() == MI.getPostInstrSymbol() &&
  360. getHeapAllocMarker() == MI.getHeapAllocMarker()) {
  361. Info = MI.Info;
  362. return;
  363. }
  364. // Otherwise, fall back on a copy-based clone.
  365. setMemRefs(MF, MI.memoperands());
  366. }
  367. /// Check to see if the MMOs pointed to by the two MemRefs arrays are
  368. /// identical.
  369. static bool hasIdenticalMMOs(ArrayRef<MachineMemOperand *> LHS,
  370. ArrayRef<MachineMemOperand *> RHS) {
  371. if (LHS.size() != RHS.size())
  372. return false;
  373. auto LHSPointees = make_pointee_range(LHS);
  374. auto RHSPointees = make_pointee_range(RHS);
  375. return std::equal(LHSPointees.begin(), LHSPointees.end(),
  376. RHSPointees.begin());
  377. }
  378. void MachineInstr::cloneMergedMemRefs(MachineFunction &MF,
  379. ArrayRef<const MachineInstr *> MIs) {
  380. // Try handling easy numbers of MIs with simpler mechanisms.
  381. if (MIs.empty()) {
  382. dropMemRefs(MF);
  383. return;
  384. }
  385. if (MIs.size() == 1) {
  386. cloneMemRefs(MF, *MIs[0]);
  387. return;
  388. }
  389. // Because an empty memoperands list provides *no* information and must be
  390. // handled conservatively (assuming the instruction can do anything), the only
  391. // way to merge with it is to drop all other memoperands.
  392. if (MIs[0]->memoperands_empty()) {
  393. dropMemRefs(MF);
  394. return;
  395. }
  396. // Handle the general case.
  397. SmallVector<MachineMemOperand *, 2> MergedMMOs;
  398. // Start with the first instruction.
  399. assert(&MF == MIs[0]->getMF() &&
  400. "Invalid machine functions when cloning memory references!");
  401. MergedMMOs.append(MIs[0]->memoperands_begin(), MIs[0]->memoperands_end());
  402. // Now walk all the other instructions and accumulate any different MMOs.
  403. for (const MachineInstr &MI : make_pointee_range(MIs.slice(1))) {
  404. assert(&MF == MI.getMF() &&
  405. "Invalid machine functions when cloning memory references!");
  406. // Skip MIs with identical operands to the first. This is a somewhat
  407. // arbitrary hack but will catch common cases without being quadratic.
  408. // TODO: We could fully implement merge semantics here if needed.
  409. if (hasIdenticalMMOs(MIs[0]->memoperands(), MI.memoperands()))
  410. continue;
  411. // Because an empty memoperands list provides *no* information and must be
  412. // handled conservatively (assuming the instruction can do anything), the
  413. // only way to merge with it is to drop all other memoperands.
  414. if (MI.memoperands_empty()) {
  415. dropMemRefs(MF);
  416. return;
  417. }
  418. // Otherwise accumulate these into our temporary buffer of the merged state.
  419. MergedMMOs.append(MI.memoperands_begin(), MI.memoperands_end());
  420. }
  421. setMemRefs(MF, MergedMMOs);
  422. }
  423. void MachineInstr::setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
  424. // Do nothing if old and new symbols are the same.
  425. if (Symbol == getPreInstrSymbol())
  426. return;
  427. // If there was only one symbol and we're removing it, just clear info.
  428. if (!Symbol && Info.is<EIIK_PreInstrSymbol>()) {
  429. Info.clear();
  430. return;
  431. }
  432. setExtraInfo(MF, memoperands(), Symbol, getPostInstrSymbol(),
  433. getHeapAllocMarker());
  434. }
  435. void MachineInstr::setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
  436. // Do nothing if old and new symbols are the same.
  437. if (Symbol == getPostInstrSymbol())
  438. return;
  439. // If there was only one symbol and we're removing it, just clear info.
  440. if (!Symbol && Info.is<EIIK_PostInstrSymbol>()) {
  441. Info.clear();
  442. return;
  443. }
  444. setExtraInfo(MF, memoperands(), getPreInstrSymbol(), Symbol,
  445. getHeapAllocMarker());
  446. }
  447. void MachineInstr::setHeapAllocMarker(MachineFunction &MF, MDNode *Marker) {
  448. // Do nothing if old and new symbols are the same.
  449. if (Marker == getHeapAllocMarker())
  450. return;
  451. setExtraInfo(MF, memoperands(), getPreInstrSymbol(), getPostInstrSymbol(),
  452. Marker);
  453. }
  454. void MachineInstr::cloneInstrSymbols(MachineFunction &MF,
  455. const MachineInstr &MI) {
  456. if (this == &MI)
  457. // Nothing to do for a self-clone!
  458. return;
  459. assert(&MF == MI.getMF() &&
  460. "Invalid machine functions when cloning instruction symbols!");
  461. setPreInstrSymbol(MF, MI.getPreInstrSymbol());
  462. setPostInstrSymbol(MF, MI.getPostInstrSymbol());
  463. setHeapAllocMarker(MF, MI.getHeapAllocMarker());
  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::eraseFromBundle() {
  605. assert(getParent() && "Not embedded in a basic block!");
  606. getParent()->erase_instr(this);
  607. }
  608. bool MachineInstr::isCandidateForCallSiteEntry(QueryType Type) const {
  609. if (!isCall(Type))
  610. return false;
  611. switch (getOpcode()) {
  612. case TargetOpcode::PATCHPOINT:
  613. case TargetOpcode::STACKMAP:
  614. case TargetOpcode::STATEPOINT:
  615. case TargetOpcode::FENTRY_CALL:
  616. return false;
  617. }
  618. return true;
  619. }
  620. bool MachineInstr::shouldUpdateCallSiteInfo() const {
  621. if (isBundle())
  622. return isCandidateForCallSiteEntry(MachineInstr::AnyInBundle);
  623. return isCandidateForCallSiteEntry();
  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 MachineOperand &MachineInstr::getDebugVariableOp() const {
  729. assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*");
  730. unsigned VariableOp = isDebugValueList() ? 0 : 2;
  731. return getOperand(VariableOp);
  732. }
  733. MachineOperand &MachineInstr::getDebugVariableOp() {
  734. assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*");
  735. unsigned VariableOp = isDebugValueList() ? 0 : 2;
  736. return getOperand(VariableOp);
  737. }
  738. const DILocalVariable *MachineInstr::getDebugVariable() const {
  739. return cast<DILocalVariable>(getDebugVariableOp().getMetadata());
  740. }
  741. const MachineOperand &MachineInstr::getDebugExpressionOp() const {
  742. assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*");
  743. unsigned ExpressionOp = isDebugValueList() ? 1 : 3;
  744. return getOperand(ExpressionOp);
  745. }
  746. MachineOperand &MachineInstr::getDebugExpressionOp() {
  747. assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*");
  748. unsigned ExpressionOp = isDebugValueList() ? 1 : 3;
  749. return getOperand(ExpressionOp);
  750. }
  751. const DIExpression *MachineInstr::getDebugExpression() const {
  752. return cast<DIExpression>(getDebugExpressionOp().getMetadata());
  753. }
  754. bool MachineInstr::isDebugEntryValue() const {
  755. return isDebugValue() && getDebugExpression()->isEntryValue();
  756. }
  757. const TargetRegisterClass*
  758. MachineInstr::getRegClassConstraint(unsigned OpIdx,
  759. const TargetInstrInfo *TII,
  760. const TargetRegisterInfo *TRI) const {
  761. assert(getParent() && "Can't have an MBB reference here!");
  762. assert(getMF() && "Can't have an MF reference here!");
  763. const MachineFunction &MF = *getMF();
  764. // Most opcodes have fixed constraints in their MCInstrDesc.
  765. if (!isInlineAsm())
  766. return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
  767. if (!getOperand(OpIdx).isReg())
  768. return nullptr;
  769. // For tied uses on inline asm, get the constraint from the def.
  770. unsigned DefIdx;
  771. if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
  772. OpIdx = DefIdx;
  773. // Inline asm stores register class constraints in the flag word.
  774. int FlagIdx = findInlineAsmFlagIdx(OpIdx);
  775. if (FlagIdx < 0)
  776. return nullptr;
  777. unsigned Flag = getOperand(FlagIdx).getImm();
  778. unsigned RCID;
  779. if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
  780. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
  781. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
  782. InlineAsm::hasRegClassConstraint(Flag, RCID))
  783. return TRI->getRegClass(RCID);
  784. // Assume that all registers in a memory operand are pointers.
  785. if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
  786. return TRI->getPointerRegClass(MF);
  787. return nullptr;
  788. }
  789. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
  790. Register Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
  791. const TargetRegisterInfo *TRI, bool ExploreBundle) const {
  792. // Check every operands inside the bundle if we have
  793. // been asked to.
  794. if (ExploreBundle)
  795. for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
  796. ++OpndIt)
  797. CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
  798. OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
  799. else
  800. // Otherwise, just check the current operands.
  801. for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
  802. CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
  803. return CurRC;
  804. }
  805. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
  806. unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
  807. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  808. assert(CurRC && "Invalid initial register class");
  809. // Check if Reg is constrained by some of its use/def from MI.
  810. const MachineOperand &MO = getOperand(OpIdx);
  811. if (!MO.isReg() || MO.getReg() != Reg)
  812. return CurRC;
  813. // If yes, accumulate the constraints through the operand.
  814. return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
  815. }
  816. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
  817. unsigned OpIdx, const TargetRegisterClass *CurRC,
  818. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  819. const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
  820. const MachineOperand &MO = getOperand(OpIdx);
  821. assert(MO.isReg() &&
  822. "Cannot get register constraints for non-register operand");
  823. assert(CurRC && "Invalid initial register class");
  824. if (unsigned SubIdx = MO.getSubReg()) {
  825. if (OpRC)
  826. CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
  827. else
  828. CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
  829. } else if (OpRC)
  830. CurRC = TRI->getCommonSubClass(CurRC, OpRC);
  831. return CurRC;
  832. }
  833. /// Return the number of instructions inside the MI bundle, not counting the
  834. /// header instruction.
  835. unsigned MachineInstr::getBundleSize() const {
  836. MachineBasicBlock::const_instr_iterator I = getIterator();
  837. unsigned Size = 0;
  838. while (I->isBundledWithSucc()) {
  839. ++Size;
  840. ++I;
  841. }
  842. return Size;
  843. }
  844. /// Returns true if the MachineInstr has an implicit-use operand of exactly
  845. /// the given register (not considering sub/super-registers).
  846. bool MachineInstr::hasRegisterImplicitUseOperand(Register Reg) const {
  847. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  848. const MachineOperand &MO = getOperand(i);
  849. if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
  850. return true;
  851. }
  852. return false;
  853. }
  854. /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
  855. /// the specific register or -1 if it is not found. It further tightens
  856. /// the search criteria to a use that kills the register if isKill is true.
  857. int MachineInstr::findRegisterUseOperandIdx(
  858. Register Reg, bool isKill, const TargetRegisterInfo *TRI) const {
  859. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  860. const MachineOperand &MO = getOperand(i);
  861. if (!MO.isReg() || !MO.isUse())
  862. continue;
  863. Register MOReg = MO.getReg();
  864. if (!MOReg)
  865. continue;
  866. if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg)))
  867. if (!isKill || MO.isKill())
  868. return i;
  869. }
  870. return -1;
  871. }
  872. /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
  873. /// indicating if this instruction reads or writes Reg. This also considers
  874. /// partial defines.
  875. std::pair<bool,bool>
  876. MachineInstr::readsWritesVirtualRegister(Register Reg,
  877. SmallVectorImpl<unsigned> *Ops) const {
  878. bool PartDef = false; // Partial redefine.
  879. bool FullDef = false; // Full define.
  880. bool Use = false;
  881. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  882. const MachineOperand &MO = getOperand(i);
  883. if (!MO.isReg() || MO.getReg() != Reg)
  884. continue;
  885. if (Ops)
  886. Ops->push_back(i);
  887. if (MO.isUse())
  888. Use |= !MO.isUndef();
  889. else if (MO.getSubReg() && !MO.isUndef())
  890. // A partial def undef doesn't count as reading the register.
  891. PartDef = true;
  892. else
  893. FullDef = true;
  894. }
  895. // A partial redefine uses Reg unless there is also a full define.
  896. return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
  897. }
  898. /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
  899. /// the specified register or -1 if it is not found. If isDead is true, defs
  900. /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
  901. /// also checks if there is a def of a super-register.
  902. int
  903. MachineInstr::findRegisterDefOperandIdx(Register Reg, bool isDead, bool Overlap,
  904. const TargetRegisterInfo *TRI) const {
  905. bool isPhys = Register::isPhysicalRegister(Reg);
  906. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  907. const MachineOperand &MO = getOperand(i);
  908. // Accept regmask operands when Overlap is set.
  909. // Ignore them when looking for a specific def operand (Overlap == false).
  910. if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
  911. return i;
  912. if (!MO.isReg() || !MO.isDef())
  913. continue;
  914. Register MOReg = MO.getReg();
  915. bool Found = (MOReg == Reg);
  916. if (!Found && TRI && isPhys && Register::isPhysicalRegister(MOReg)) {
  917. if (Overlap)
  918. Found = TRI->regsOverlap(MOReg, Reg);
  919. else
  920. Found = TRI->isSubRegister(MOReg, Reg);
  921. }
  922. if (Found && (!isDead || MO.isDead()))
  923. return i;
  924. }
  925. return -1;
  926. }
  927. /// findFirstPredOperandIdx() - Find the index of the first operand in the
  928. /// operand list that is used to represent the predicate. It returns -1 if
  929. /// none is found.
  930. int MachineInstr::findFirstPredOperandIdx() const {
  931. // Don't call MCID.findFirstPredOperandIdx() because this variant
  932. // is sometimes called on an instruction that's not yet complete, and
  933. // so the number of operands is less than the MCID indicates. In
  934. // particular, the PTX target does this.
  935. const MCInstrDesc &MCID = getDesc();
  936. if (MCID.isPredicable()) {
  937. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  938. if (MCID.OpInfo[i].isPredicate())
  939. return i;
  940. }
  941. return -1;
  942. }
  943. // MachineOperand::TiedTo is 4 bits wide.
  944. const unsigned TiedMax = 15;
  945. /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
  946. ///
  947. /// Use and def operands can be tied together, indicated by a non-zero TiedTo
  948. /// field. TiedTo can have these values:
  949. ///
  950. /// 0: Operand is not tied to anything.
  951. /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
  952. /// TiedMax: Tied to an operand >= TiedMax-1.
  953. ///
  954. /// The tied def must be one of the first TiedMax operands on a normal
  955. /// instruction. INLINEASM instructions allow more tied defs.
  956. ///
  957. void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
  958. MachineOperand &DefMO = getOperand(DefIdx);
  959. MachineOperand &UseMO = getOperand(UseIdx);
  960. assert(DefMO.isDef() && "DefIdx must be a def operand");
  961. assert(UseMO.isUse() && "UseIdx must be a use operand");
  962. assert(!DefMO.isTied() && "Def is already tied to another use");
  963. assert(!UseMO.isTied() && "Use is already tied to another def");
  964. if (DefIdx < TiedMax)
  965. UseMO.TiedTo = DefIdx + 1;
  966. else {
  967. // Inline asm can use the group descriptors to find tied operands,
  968. // statepoint tied operands are trivial to match (1-1 reg def with reg use),
  969. // but on normal instruction, the tied def must be within the first TiedMax
  970. // operands.
  971. assert((isInlineAsm() || getOpcode() == TargetOpcode::STATEPOINT) &&
  972. "DefIdx out of range");
  973. UseMO.TiedTo = TiedMax;
  974. }
  975. // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
  976. DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
  977. }
  978. /// Given the index of a tied register operand, find the operand it is tied to.
  979. /// Defs are tied to uses and vice versa. Returns the index of the tied operand
  980. /// which must exist.
  981. unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
  982. const MachineOperand &MO = getOperand(OpIdx);
  983. assert(MO.isTied() && "Operand isn't tied");
  984. // Normally TiedTo is in range.
  985. if (MO.TiedTo < TiedMax)
  986. return MO.TiedTo - 1;
  987. // Uses on normal instructions can be out of range.
  988. if (!isInlineAsm() && getOpcode() != TargetOpcode::STATEPOINT) {
  989. // Normal tied defs must be in the 0..TiedMax-1 range.
  990. if (MO.isUse())
  991. return TiedMax - 1;
  992. // MO is a def. Search for the tied use.
  993. for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
  994. const MachineOperand &UseMO = getOperand(i);
  995. if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
  996. return i;
  997. }
  998. llvm_unreachable("Can't find tied use");
  999. }
  1000. if (getOpcode() == TargetOpcode::STATEPOINT) {
  1001. // In STATEPOINT defs correspond 1-1 to GC pointer operands passed
  1002. // on registers.
  1003. StatepointOpers SO(this);
  1004. unsigned CurUseIdx = SO.getFirstGCPtrIdx();
  1005. assert(CurUseIdx != -1U && "only gc pointer statepoint operands can be tied");
  1006. unsigned NumDefs = getNumDefs();
  1007. for (unsigned CurDefIdx = 0; CurDefIdx < NumDefs; ++CurDefIdx) {
  1008. while (!getOperand(CurUseIdx).isReg())
  1009. CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx);
  1010. if (OpIdx == CurDefIdx)
  1011. return CurUseIdx;
  1012. if (OpIdx == CurUseIdx)
  1013. return CurDefIdx;
  1014. CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx);
  1015. }
  1016. llvm_unreachable("Can't find tied use");
  1017. }
  1018. // Now deal with inline asm by parsing the operand group descriptor flags.
  1019. // Find the beginning of each operand group.
  1020. SmallVector<unsigned, 8> GroupIdx;
  1021. unsigned OpIdxGroup = ~0u;
  1022. unsigned NumOps;
  1023. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  1024. i += NumOps) {
  1025. const MachineOperand &FlagMO = getOperand(i);
  1026. assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
  1027. unsigned CurGroup = GroupIdx.size();
  1028. GroupIdx.push_back(i);
  1029. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  1030. // OpIdx belongs to this operand group.
  1031. if (OpIdx > i && OpIdx < i + NumOps)
  1032. OpIdxGroup = CurGroup;
  1033. unsigned TiedGroup;
  1034. if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
  1035. continue;
  1036. // Operands in this group are tied to operands in TiedGroup which must be
  1037. // earlier. Find the number of operands between the two groups.
  1038. unsigned Delta = i - GroupIdx[TiedGroup];
  1039. // OpIdx is a use tied to TiedGroup.
  1040. if (OpIdxGroup == CurGroup)
  1041. return OpIdx - Delta;
  1042. // OpIdx is a def tied to this use group.
  1043. if (OpIdxGroup == TiedGroup)
  1044. return OpIdx + Delta;
  1045. }
  1046. llvm_unreachable("Invalid tied operand on inline asm");
  1047. }
  1048. /// clearKillInfo - Clears kill flags on all operands.
  1049. ///
  1050. void MachineInstr::clearKillInfo() {
  1051. for (MachineOperand &MO : operands()) {
  1052. if (MO.isReg() && MO.isUse())
  1053. MO.setIsKill(false);
  1054. }
  1055. }
  1056. void MachineInstr::substituteRegister(Register FromReg, Register ToReg,
  1057. unsigned SubIdx,
  1058. const TargetRegisterInfo &RegInfo) {
  1059. if (Register::isPhysicalRegister(ToReg)) {
  1060. if (SubIdx)
  1061. ToReg = RegInfo.getSubReg(ToReg, SubIdx);
  1062. for (MachineOperand &MO : operands()) {
  1063. if (!MO.isReg() || MO.getReg() != FromReg)
  1064. continue;
  1065. MO.substPhysReg(ToReg, RegInfo);
  1066. }
  1067. } else {
  1068. for (MachineOperand &MO : operands()) {
  1069. if (!MO.isReg() || MO.getReg() != FromReg)
  1070. continue;
  1071. MO.substVirtReg(ToReg, SubIdx, RegInfo);
  1072. }
  1073. }
  1074. }
  1075. /// isSafeToMove - Return true if it is safe to move this instruction. If
  1076. /// SawStore is set to true, it means that there is a store (or call) between
  1077. /// the instruction's location and its intended destination.
  1078. bool MachineInstr::isSafeToMove(AAResults *AA, bool &SawStore) const {
  1079. // Ignore stuff that we obviously can't move.
  1080. //
  1081. // Treat volatile loads as stores. This is not strictly necessary for
  1082. // volatiles, but it is required for atomic loads. It is not allowed to move
  1083. // a load across an atomic load with Ordering > Monotonic.
  1084. if (mayStore() || isCall() || isPHI() ||
  1085. (mayLoad() && hasOrderedMemoryRef())) {
  1086. SawStore = true;
  1087. return false;
  1088. }
  1089. if (isPosition() || isDebugInstr() || isTerminator() ||
  1090. mayRaiseFPException() || hasUnmodeledSideEffects())
  1091. return false;
  1092. // See if this instruction does a load. If so, we have to guarantee that the
  1093. // loaded value doesn't change between the load and the its intended
  1094. // destination. The check for isInvariantLoad gives the target the chance to
  1095. // classify the load as always returning a constant, e.g. a constant pool
  1096. // load.
  1097. if (mayLoad() && !isDereferenceableInvariantLoad(AA))
  1098. // Otherwise, this is a real load. If there is a store between the load and
  1099. // end of block, we can't move it.
  1100. return !SawStore;
  1101. return true;
  1102. }
  1103. static bool MemOperandsHaveAlias(const MachineFrameInfo &MFI, AAResults *AA,
  1104. bool UseTBAA, const MachineMemOperand *MMOa,
  1105. const MachineMemOperand *MMOb) {
  1106. // The following interface to AA is fashioned after DAGCombiner::isAlias and
  1107. // operates with MachineMemOperand offset with some important assumptions:
  1108. // - LLVM fundamentally assumes flat address spaces.
  1109. // - MachineOperand offset can *only* result from legalization and cannot
  1110. // affect queries other than the trivial case of overlap checking.
  1111. // - These offsets never wrap and never step outside of allocated objects.
  1112. // - There should never be any negative offsets here.
  1113. //
  1114. // FIXME: Modify API to hide this math from "user"
  1115. // Even before we go to AA we can reason locally about some memory objects. It
  1116. // can save compile time, and possibly catch some corner cases not currently
  1117. // covered.
  1118. int64_t OffsetA = MMOa->getOffset();
  1119. int64_t OffsetB = MMOb->getOffset();
  1120. int64_t MinOffset = std::min(OffsetA, OffsetB);
  1121. uint64_t WidthA = MMOa->getSize();
  1122. uint64_t WidthB = MMOb->getSize();
  1123. bool KnownWidthA = WidthA != MemoryLocation::UnknownSize;
  1124. bool KnownWidthB = WidthB != MemoryLocation::UnknownSize;
  1125. const Value *ValA = MMOa->getValue();
  1126. const Value *ValB = MMOb->getValue();
  1127. bool SameVal = (ValA && ValB && (ValA == ValB));
  1128. if (!SameVal) {
  1129. const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
  1130. const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
  1131. if (PSVa && ValB && !PSVa->mayAlias(&MFI))
  1132. return false;
  1133. if (PSVb && ValA && !PSVb->mayAlias(&MFI))
  1134. return false;
  1135. if (PSVa && PSVb && (PSVa == PSVb))
  1136. SameVal = true;
  1137. }
  1138. if (SameVal) {
  1139. if (!KnownWidthA || !KnownWidthB)
  1140. return true;
  1141. int64_t MaxOffset = std::max(OffsetA, OffsetB);
  1142. int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
  1143. return (MinOffset + LowWidth > MaxOffset);
  1144. }
  1145. if (!AA)
  1146. return true;
  1147. if (!ValA || !ValB)
  1148. return true;
  1149. assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
  1150. assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
  1151. int64_t OverlapA =
  1152. KnownWidthA ? WidthA + OffsetA - MinOffset : MemoryLocation::UnknownSize;
  1153. int64_t OverlapB =
  1154. KnownWidthB ? WidthB + OffsetB - MinOffset : MemoryLocation::UnknownSize;
  1155. return !AA->isNoAlias(
  1156. MemoryLocation(ValA, OverlapA, UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
  1157. MemoryLocation(ValB, OverlapB,
  1158. UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
  1159. }
  1160. bool MachineInstr::mayAlias(AAResults *AA, const MachineInstr &Other,
  1161. bool UseTBAA) const {
  1162. const MachineFunction *MF = getMF();
  1163. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1164. const MachineFrameInfo &MFI = MF->getFrameInfo();
  1165. // Exclude call instruction which may alter the memory but can not be handled
  1166. // by this function.
  1167. if (isCall() || Other.isCall())
  1168. return true;
  1169. // If neither instruction stores to memory, they can't alias in any
  1170. // meaningful way, even if they read from the same address.
  1171. if (!mayStore() && !Other.mayStore())
  1172. return false;
  1173. // Both instructions must be memory operations to be able to alias.
  1174. if (!mayLoadOrStore() || !Other.mayLoadOrStore())
  1175. return false;
  1176. // Let the target decide if memory accesses cannot possibly overlap.
  1177. if (TII->areMemAccessesTriviallyDisjoint(*this, Other))
  1178. return false;
  1179. // Memory operations without memory operands may access anything. Be
  1180. // conservative and assume `MayAlias`.
  1181. if (memoperands_empty() || Other.memoperands_empty())
  1182. return true;
  1183. // Skip if there are too many memory operands.
  1184. auto NumChecks = getNumMemOperands() * Other.getNumMemOperands();
  1185. if (NumChecks > TII->getMemOperandAACheckLimit())
  1186. return true;
  1187. // Check each pair of memory operands from both instructions, which can't
  1188. // alias only if all pairs won't alias.
  1189. for (auto *MMOa : memoperands())
  1190. for (auto *MMOb : Other.memoperands())
  1191. if (MemOperandsHaveAlias(MFI, AA, UseTBAA, MMOa, MMOb))
  1192. return true;
  1193. return false;
  1194. }
  1195. /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
  1196. /// or volatile memory reference, or if the information describing the memory
  1197. /// reference is not available. Return false if it is known to have no ordered
  1198. /// memory references.
  1199. bool MachineInstr::hasOrderedMemoryRef() const {
  1200. // An instruction known never to access memory won't have a volatile access.
  1201. if (!mayStore() &&
  1202. !mayLoad() &&
  1203. !isCall() &&
  1204. !hasUnmodeledSideEffects())
  1205. return false;
  1206. // Otherwise, if the instruction has no memory reference information,
  1207. // conservatively assume it wasn't preserved.
  1208. if (memoperands_empty())
  1209. return true;
  1210. // Check if any of our memory operands are ordered.
  1211. return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
  1212. return !MMO->isUnordered();
  1213. });
  1214. }
  1215. /// isDereferenceableInvariantLoad - Return true if this instruction will never
  1216. /// trap and is loading from a location whose value is invariant across a run of
  1217. /// this function.
  1218. bool MachineInstr::isDereferenceableInvariantLoad(AAResults *AA) const {
  1219. // If the instruction doesn't load at all, it isn't an invariant load.
  1220. if (!mayLoad())
  1221. return false;
  1222. // If the instruction has lost its memoperands, conservatively assume that
  1223. // it may not be an invariant load.
  1224. if (memoperands_empty())
  1225. return false;
  1226. const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
  1227. for (MachineMemOperand *MMO : memoperands()) {
  1228. if (!MMO->isUnordered())
  1229. // If the memory operand has ordering side effects, we can't move the
  1230. // instruction. Such an instruction is technically an invariant load,
  1231. // but the caller code would need updated to expect that.
  1232. return false;
  1233. if (MMO->isStore()) return false;
  1234. if (MMO->isInvariant() && MMO->isDereferenceable())
  1235. continue;
  1236. // A load from a constant PseudoSourceValue is invariant.
  1237. if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
  1238. if (PSV->isConstant(&MFI))
  1239. continue;
  1240. if (const Value *V = MMO->getValue()) {
  1241. // If we have an AliasAnalysis, ask it whether the memory is constant.
  1242. if (AA &&
  1243. AA->pointsToConstantMemory(
  1244. MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
  1245. continue;
  1246. }
  1247. // Otherwise assume conservatively.
  1248. return false;
  1249. }
  1250. // Everything checks out.
  1251. return true;
  1252. }
  1253. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1254. /// merges together the same virtual register, return the register, otherwise
  1255. /// return 0.
  1256. unsigned MachineInstr::isConstantValuePHI() const {
  1257. if (!isPHI())
  1258. return 0;
  1259. assert(getNumOperands() >= 3 &&
  1260. "It's illegal to have a PHI without source operands");
  1261. Register Reg = getOperand(1).getReg();
  1262. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1263. if (getOperand(i).getReg() != Reg)
  1264. return 0;
  1265. return Reg;
  1266. }
  1267. bool MachineInstr::hasUnmodeledSideEffects() const {
  1268. if (hasProperty(MCID::UnmodeledSideEffects))
  1269. return true;
  1270. if (isInlineAsm()) {
  1271. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1272. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1273. return true;
  1274. }
  1275. return false;
  1276. }
  1277. bool MachineInstr::isLoadFoldBarrier() const {
  1278. return mayStore() || isCall() ||
  1279. (hasUnmodeledSideEffects() && !isPseudoProbe());
  1280. }
  1281. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1282. ///
  1283. bool MachineInstr::allDefsAreDead() const {
  1284. for (const MachineOperand &MO : operands()) {
  1285. if (!MO.isReg() || MO.isUse())
  1286. continue;
  1287. if (!MO.isDead())
  1288. return false;
  1289. }
  1290. return true;
  1291. }
  1292. /// copyImplicitOps - Copy implicit register operands from specified
  1293. /// instruction to this instruction.
  1294. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1295. const MachineInstr &MI) {
  1296. for (const MachineOperand &MO :
  1297. llvm::drop_begin(MI.operands(), MI.getDesc().getNumOperands()))
  1298. if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
  1299. addOperand(MF, MO);
  1300. }
  1301. bool MachineInstr::hasComplexRegisterTies() const {
  1302. const MCInstrDesc &MCID = getDesc();
  1303. if (MCID.Opcode == TargetOpcode::STATEPOINT)
  1304. return true;
  1305. for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
  1306. const auto &Operand = getOperand(I);
  1307. if (!Operand.isReg() || Operand.isDef())
  1308. // Ignore the defined registers as MCID marks only the uses as tied.
  1309. continue;
  1310. int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
  1311. int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
  1312. if (ExpectedTiedIdx != TiedIdx)
  1313. return true;
  1314. }
  1315. return false;
  1316. }
  1317. LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
  1318. const MachineRegisterInfo &MRI) const {
  1319. const MachineOperand &Op = getOperand(OpIdx);
  1320. if (!Op.isReg())
  1321. return LLT{};
  1322. if (isVariadic() || OpIdx >= getNumExplicitOperands())
  1323. return MRI.getType(Op.getReg());
  1324. auto &OpInfo = getDesc().OpInfo[OpIdx];
  1325. if (!OpInfo.isGenericType())
  1326. return MRI.getType(Op.getReg());
  1327. if (PrintedTypes[OpInfo.getGenericTypeIndex()])
  1328. return LLT{};
  1329. LLT TypeToPrint = MRI.getType(Op.getReg());
  1330. // Don't mark the type index printed if it wasn't actually printed: maybe
  1331. // another operand with the same type index has an actual type attached:
  1332. if (TypeToPrint.isValid())
  1333. PrintedTypes.set(OpInfo.getGenericTypeIndex());
  1334. return TypeToPrint;
  1335. }
  1336. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1337. LLVM_DUMP_METHOD void MachineInstr::dump() const {
  1338. dbgs() << " ";
  1339. print(dbgs());
  1340. }
  1341. LLVM_DUMP_METHOD void MachineInstr::dumprImpl(
  1342. const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
  1343. SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const {
  1344. if (Depth >= MaxDepth)
  1345. return;
  1346. if (!AlreadySeenInstrs.insert(this).second)
  1347. return;
  1348. // PadToColumn always inserts at least one space.
  1349. // Don't mess up the alignment if we don't want any space.
  1350. if (Depth)
  1351. fdbgs().PadToColumn(Depth * 2);
  1352. print(fdbgs());
  1353. for (const MachineOperand &MO : operands()) {
  1354. if (!MO.isReg() || MO.isDef())
  1355. continue;
  1356. Register Reg = MO.getReg();
  1357. if (Reg.isPhysical())
  1358. continue;
  1359. const MachineInstr *NewMI = MRI.getUniqueVRegDef(Reg);
  1360. if (NewMI == nullptr)
  1361. continue;
  1362. NewMI->dumprImpl(MRI, Depth + 1, MaxDepth, AlreadySeenInstrs);
  1363. }
  1364. }
  1365. LLVM_DUMP_METHOD void MachineInstr::dumpr(const MachineRegisterInfo &MRI,
  1366. unsigned MaxDepth) const {
  1367. SmallPtrSet<const MachineInstr *, 16> AlreadySeenInstrs;
  1368. dumprImpl(MRI, 0, MaxDepth, AlreadySeenInstrs);
  1369. }
  1370. #endif
  1371. void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
  1372. bool SkipDebugLoc, bool AddNewLine,
  1373. const TargetInstrInfo *TII) const {
  1374. const Module *M = nullptr;
  1375. const Function *F = nullptr;
  1376. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1377. F = &MF->getFunction();
  1378. M = F->getParent();
  1379. if (!TII)
  1380. TII = MF->getSubtarget().getInstrInfo();
  1381. }
  1382. ModuleSlotTracker MST(M);
  1383. if (F)
  1384. MST.incorporateFunction(*F);
  1385. print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, AddNewLine, TII);
  1386. }
  1387. void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
  1388. bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
  1389. bool AddNewLine, const TargetInstrInfo *TII) const {
  1390. // We can be a bit tidier if we know the MachineFunction.
  1391. const TargetRegisterInfo *TRI = nullptr;
  1392. const MachineRegisterInfo *MRI = nullptr;
  1393. const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
  1394. tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
  1395. if (isCFIInstruction())
  1396. assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
  1397. SmallBitVector PrintedTypes(8);
  1398. bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies();
  1399. auto getTiedOperandIdx = [&](unsigned OpIdx) {
  1400. if (!ShouldPrintRegisterTies)
  1401. return 0U;
  1402. const MachineOperand &MO = getOperand(OpIdx);
  1403. if (MO.isReg() && MO.isTied() && !MO.isDef())
  1404. return findTiedOperandIdx(OpIdx);
  1405. return 0U;
  1406. };
  1407. unsigned StartOp = 0;
  1408. unsigned e = getNumOperands();
  1409. // Print explicitly defined operands on the left of an assignment syntax.
  1410. while (StartOp < e) {
  1411. const MachineOperand &MO = getOperand(StartOp);
  1412. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  1413. break;
  1414. if (StartOp != 0)
  1415. OS << ", ";
  1416. LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
  1417. unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
  1418. MO.print(OS, MST, TypeToPrint, StartOp, /*PrintDef=*/false, IsStandalone,
  1419. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1420. ++StartOp;
  1421. }
  1422. if (StartOp != 0)
  1423. OS << " = ";
  1424. if (getFlag(MachineInstr::FrameSetup))
  1425. OS << "frame-setup ";
  1426. if (getFlag(MachineInstr::FrameDestroy))
  1427. OS << "frame-destroy ";
  1428. if (getFlag(MachineInstr::FmNoNans))
  1429. OS << "nnan ";
  1430. if (getFlag(MachineInstr::FmNoInfs))
  1431. OS << "ninf ";
  1432. if (getFlag(MachineInstr::FmNsz))
  1433. OS << "nsz ";
  1434. if (getFlag(MachineInstr::FmArcp))
  1435. OS << "arcp ";
  1436. if (getFlag(MachineInstr::FmContract))
  1437. OS << "contract ";
  1438. if (getFlag(MachineInstr::FmAfn))
  1439. OS << "afn ";
  1440. if (getFlag(MachineInstr::FmReassoc))
  1441. OS << "reassoc ";
  1442. if (getFlag(MachineInstr::NoUWrap))
  1443. OS << "nuw ";
  1444. if (getFlag(MachineInstr::NoSWrap))
  1445. OS << "nsw ";
  1446. if (getFlag(MachineInstr::IsExact))
  1447. OS << "exact ";
  1448. if (getFlag(MachineInstr::NoFPExcept))
  1449. OS << "nofpexcept ";
  1450. if (getFlag(MachineInstr::NoMerge))
  1451. OS << "nomerge ";
  1452. // Print the opcode name.
  1453. if (TII)
  1454. OS << TII->getName(getOpcode());
  1455. else
  1456. OS << "UNKNOWN";
  1457. if (SkipOpers)
  1458. return;
  1459. // Print the rest of the operands.
  1460. bool FirstOp = true;
  1461. unsigned AsmDescOp = ~0u;
  1462. unsigned AsmOpCount = 0;
  1463. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1464. // Print asm string.
  1465. OS << " ";
  1466. const unsigned OpIdx = InlineAsm::MIOp_AsmString;
  1467. LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
  1468. unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
  1469. getOperand(OpIdx).print(OS, MST, TypeToPrint, OpIdx, /*PrintDef=*/true, IsStandalone,
  1470. ShouldPrintRegisterTies, TiedOperandIdx, TRI,
  1471. IntrinsicInfo);
  1472. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1473. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1474. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1475. OS << " [sideeffect]";
  1476. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1477. OS << " [mayload]";
  1478. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1479. OS << " [maystore]";
  1480. if (ExtraInfo & InlineAsm::Extra_IsConvergent)
  1481. OS << " [isconvergent]";
  1482. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1483. OS << " [alignstack]";
  1484. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1485. OS << " [attdialect]";
  1486. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1487. OS << " [inteldialect]";
  1488. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1489. FirstOp = false;
  1490. }
  1491. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1492. const MachineOperand &MO = getOperand(i);
  1493. if (FirstOp) FirstOp = false; else OS << ",";
  1494. OS << " ";
  1495. if (isDebugValue() && MO.isMetadata()) {
  1496. // Pretty print DBG_VALUE* instructions.
  1497. auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
  1498. if (DIV && !DIV->getName().empty())
  1499. OS << "!\"" << DIV->getName() << '\"';
  1500. else {
  1501. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1502. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1503. MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
  1504. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1505. }
  1506. } else if (isDebugLabel() && MO.isMetadata()) {
  1507. // Pretty print DBG_LABEL instructions.
  1508. auto *DIL = dyn_cast<DILabel>(MO.getMetadata());
  1509. if (DIL && !DIL->getName().empty())
  1510. OS << "\"" << DIL->getName() << '\"';
  1511. else {
  1512. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1513. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1514. MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
  1515. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1516. }
  1517. } else if (i == AsmDescOp && MO.isImm()) {
  1518. // Pretty print the inline asm operand descriptor.
  1519. OS << '$' << AsmOpCount++;
  1520. unsigned Flag = MO.getImm();
  1521. OS << ":[";
  1522. OS << InlineAsm::getKindName(InlineAsm::getKind(Flag));
  1523. unsigned RCID = 0;
  1524. if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
  1525. InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1526. if (TRI) {
  1527. OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
  1528. } else
  1529. OS << ":RC" << RCID;
  1530. }
  1531. if (InlineAsm::isMemKind(Flag)) {
  1532. unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
  1533. OS << ":" << InlineAsm::getMemConstraintName(MCID);
  1534. }
  1535. unsigned TiedTo = 0;
  1536. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1537. OS << " tiedto:$" << TiedTo;
  1538. OS << ']';
  1539. // Compute the index of the next operand descriptor.
  1540. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1541. } else {
  1542. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1543. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1544. if (MO.isImm() && isOperandSubregIdx(i))
  1545. MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
  1546. else
  1547. MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
  1548. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1549. }
  1550. }
  1551. // Print any optional symbols attached to this instruction as-if they were
  1552. // operands.
  1553. if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) {
  1554. if (!FirstOp) {
  1555. FirstOp = false;
  1556. OS << ',';
  1557. }
  1558. OS << " pre-instr-symbol ";
  1559. MachineOperand::printSymbol(OS, *PreInstrSymbol);
  1560. }
  1561. if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) {
  1562. if (!FirstOp) {
  1563. FirstOp = false;
  1564. OS << ',';
  1565. }
  1566. OS << " post-instr-symbol ";
  1567. MachineOperand::printSymbol(OS, *PostInstrSymbol);
  1568. }
  1569. if (MDNode *HeapAllocMarker = getHeapAllocMarker()) {
  1570. if (!FirstOp) {
  1571. FirstOp = false;
  1572. OS << ',';
  1573. }
  1574. OS << " heap-alloc-marker ";
  1575. HeapAllocMarker->printAsOperand(OS, MST);
  1576. }
  1577. if (DebugInstrNum) {
  1578. if (!FirstOp)
  1579. OS << ",";
  1580. OS << " debug-instr-number " << DebugInstrNum;
  1581. }
  1582. if (!SkipDebugLoc) {
  1583. if (const DebugLoc &DL = getDebugLoc()) {
  1584. if (!FirstOp)
  1585. OS << ',';
  1586. OS << " debug-location ";
  1587. DL->printAsOperand(OS, MST);
  1588. }
  1589. }
  1590. if (!memoperands_empty()) {
  1591. SmallVector<StringRef, 0> SSNs;
  1592. const LLVMContext *Context = nullptr;
  1593. std::unique_ptr<LLVMContext> CtxPtr;
  1594. const MachineFrameInfo *MFI = nullptr;
  1595. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1596. MFI = &MF->getFrameInfo();
  1597. Context = &MF->getFunction().getContext();
  1598. } else {
  1599. CtxPtr = std::make_unique<LLVMContext>();
  1600. Context = CtxPtr.get();
  1601. }
  1602. OS << " :: ";
  1603. bool NeedComma = false;
  1604. for (const MachineMemOperand *Op : memoperands()) {
  1605. if (NeedComma)
  1606. OS << ", ";
  1607. Op->print(OS, MST, SSNs, *Context, MFI, TII);
  1608. NeedComma = true;
  1609. }
  1610. }
  1611. if (SkipDebugLoc)
  1612. return;
  1613. bool HaveSemi = false;
  1614. // Print debug location information.
  1615. if (const DebugLoc &DL = getDebugLoc()) {
  1616. if (!HaveSemi) {
  1617. OS << ';';
  1618. HaveSemi = true;
  1619. }
  1620. OS << ' ';
  1621. DL.print(OS);
  1622. }
  1623. // Print extra comments for DEBUG_VALUE.
  1624. if (isDebugValue() && getDebugVariableOp().isMetadata()) {
  1625. if (!HaveSemi) {
  1626. OS << ";";
  1627. HaveSemi = true;
  1628. }
  1629. auto *DV = getDebugVariable();
  1630. OS << " line no:" << DV->getLine();
  1631. if (isIndirectDebugValue())
  1632. OS << " indirect";
  1633. }
  1634. // TODO: DBG_LABEL
  1635. if (AddNewLine)
  1636. OS << '\n';
  1637. }
  1638. bool MachineInstr::addRegisterKilled(Register IncomingReg,
  1639. const TargetRegisterInfo *RegInfo,
  1640. bool AddIfNotFound) {
  1641. bool isPhysReg = Register::isPhysicalRegister(IncomingReg);
  1642. bool hasAliases = isPhysReg &&
  1643. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1644. bool Found = false;
  1645. SmallVector<unsigned,4> DeadOps;
  1646. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1647. MachineOperand &MO = getOperand(i);
  1648. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1649. continue;
  1650. // DEBUG_VALUE nodes do not contribute to code generation and should
  1651. // always be ignored. Failure to do so may result in trying to modify
  1652. // KILL flags on DEBUG_VALUE nodes.
  1653. if (MO.isDebug())
  1654. continue;
  1655. Register Reg = MO.getReg();
  1656. if (!Reg)
  1657. continue;
  1658. if (Reg == IncomingReg) {
  1659. if (!Found) {
  1660. if (MO.isKill())
  1661. // The register is already marked kill.
  1662. return true;
  1663. if (isPhysReg && isRegTiedToDefOperand(i))
  1664. // Two-address uses of physregs must not be marked kill.
  1665. return true;
  1666. MO.setIsKill();
  1667. Found = true;
  1668. }
  1669. } else if (hasAliases && MO.isKill() && Register::isPhysicalRegister(Reg)) {
  1670. // A super-register kill already exists.
  1671. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1672. return true;
  1673. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1674. DeadOps.push_back(i);
  1675. }
  1676. }
  1677. // Trim unneeded kill operands.
  1678. while (!DeadOps.empty()) {
  1679. unsigned OpIdx = DeadOps.back();
  1680. if (getOperand(OpIdx).isImplicit() &&
  1681. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1682. RemoveOperand(OpIdx);
  1683. else
  1684. getOperand(OpIdx).setIsKill(false);
  1685. DeadOps.pop_back();
  1686. }
  1687. // If not found, this means an alias of one of the operands is killed. Add a
  1688. // new implicit operand if required.
  1689. if (!Found && AddIfNotFound) {
  1690. addOperand(MachineOperand::CreateReg(IncomingReg,
  1691. false /*IsDef*/,
  1692. true /*IsImp*/,
  1693. true /*IsKill*/));
  1694. return true;
  1695. }
  1696. return Found;
  1697. }
  1698. void MachineInstr::clearRegisterKills(Register Reg,
  1699. const TargetRegisterInfo *RegInfo) {
  1700. if (!Register::isPhysicalRegister(Reg))
  1701. RegInfo = nullptr;
  1702. for (MachineOperand &MO : operands()) {
  1703. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1704. continue;
  1705. Register OpReg = MO.getReg();
  1706. if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
  1707. MO.setIsKill(false);
  1708. }
  1709. }
  1710. bool MachineInstr::addRegisterDead(Register Reg,
  1711. const TargetRegisterInfo *RegInfo,
  1712. bool AddIfNotFound) {
  1713. bool isPhysReg = Register::isPhysicalRegister(Reg);
  1714. bool hasAliases = isPhysReg &&
  1715. MCRegAliasIterator(Reg, RegInfo, false).isValid();
  1716. bool Found = false;
  1717. SmallVector<unsigned,4> DeadOps;
  1718. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1719. MachineOperand &MO = getOperand(i);
  1720. if (!MO.isReg() || !MO.isDef())
  1721. continue;
  1722. Register MOReg = MO.getReg();
  1723. if (!MOReg)
  1724. continue;
  1725. if (MOReg == Reg) {
  1726. MO.setIsDead();
  1727. Found = true;
  1728. } else if (hasAliases && MO.isDead() &&
  1729. Register::isPhysicalRegister(MOReg)) {
  1730. // There exists a super-register that's marked dead.
  1731. if (RegInfo->isSuperRegister(Reg, MOReg))
  1732. return true;
  1733. if (RegInfo->isSubRegister(Reg, MOReg))
  1734. DeadOps.push_back(i);
  1735. }
  1736. }
  1737. // Trim unneeded dead operands.
  1738. while (!DeadOps.empty()) {
  1739. unsigned OpIdx = DeadOps.back();
  1740. if (getOperand(OpIdx).isImplicit() &&
  1741. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1742. RemoveOperand(OpIdx);
  1743. else
  1744. getOperand(OpIdx).setIsDead(false);
  1745. DeadOps.pop_back();
  1746. }
  1747. // If not found, this means an alias of one of the operands is dead. Add a
  1748. // new implicit operand if required.
  1749. if (Found || !AddIfNotFound)
  1750. return Found;
  1751. addOperand(MachineOperand::CreateReg(Reg,
  1752. true /*IsDef*/,
  1753. true /*IsImp*/,
  1754. false /*IsKill*/,
  1755. true /*IsDead*/));
  1756. return true;
  1757. }
  1758. void MachineInstr::clearRegisterDeads(Register Reg) {
  1759. for (MachineOperand &MO : operands()) {
  1760. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
  1761. continue;
  1762. MO.setIsDead(false);
  1763. }
  1764. }
  1765. void MachineInstr::setRegisterDefReadUndef(Register Reg, bool IsUndef) {
  1766. for (MachineOperand &MO : operands()) {
  1767. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
  1768. continue;
  1769. MO.setIsUndef(IsUndef);
  1770. }
  1771. }
  1772. void MachineInstr::addRegisterDefined(Register Reg,
  1773. const TargetRegisterInfo *RegInfo) {
  1774. if (Register::isPhysicalRegister(Reg)) {
  1775. MachineOperand *MO = findRegisterDefOperand(Reg, false, false, RegInfo);
  1776. if (MO)
  1777. return;
  1778. } else {
  1779. for (const MachineOperand &MO : operands()) {
  1780. if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
  1781. MO.getSubReg() == 0)
  1782. return;
  1783. }
  1784. }
  1785. addOperand(MachineOperand::CreateReg(Reg,
  1786. true /*IsDef*/,
  1787. true /*IsImp*/));
  1788. }
  1789. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
  1790. const TargetRegisterInfo &TRI) {
  1791. bool HasRegMask = false;
  1792. for (MachineOperand &MO : operands()) {
  1793. if (MO.isRegMask()) {
  1794. HasRegMask = true;
  1795. continue;
  1796. }
  1797. if (!MO.isReg() || !MO.isDef()) continue;
  1798. Register Reg = MO.getReg();
  1799. if (!Reg.isPhysical())
  1800. continue;
  1801. // If there are no uses, including partial uses, the def is dead.
  1802. if (llvm::none_of(UsedRegs,
  1803. [&](MCRegister Use) { return TRI.regsOverlap(Use, Reg); }))
  1804. MO.setIsDead();
  1805. }
  1806. // This is a call with a register mask operand.
  1807. // Mask clobbers are always dead, so add defs for the non-dead defines.
  1808. if (HasRegMask)
  1809. for (const Register &UsedReg : UsedRegs)
  1810. addRegisterDefined(UsedReg, &TRI);
  1811. }
  1812. unsigned
  1813. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  1814. // Build up a buffer of hash code components.
  1815. SmallVector<size_t, 16> HashComponents;
  1816. HashComponents.reserve(MI->getNumOperands() + 1);
  1817. HashComponents.push_back(MI->getOpcode());
  1818. for (const MachineOperand &MO : MI->operands()) {
  1819. if (MO.isReg() && MO.isDef() && Register::isVirtualRegister(MO.getReg()))
  1820. continue; // Skip virtual register defs.
  1821. HashComponents.push_back(hash_value(MO));
  1822. }
  1823. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  1824. }
  1825. void MachineInstr::emitError(StringRef Msg) const {
  1826. // Find the source location cookie.
  1827. uint64_t LocCookie = 0;
  1828. const MDNode *LocMD = nullptr;
  1829. for (unsigned i = getNumOperands(); i != 0; --i) {
  1830. if (getOperand(i-1).isMetadata() &&
  1831. (LocMD = getOperand(i-1).getMetadata()) &&
  1832. LocMD->getNumOperands() != 0) {
  1833. if (const ConstantInt *CI =
  1834. mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
  1835. LocCookie = CI->getZExtValue();
  1836. break;
  1837. }
  1838. }
  1839. }
  1840. if (const MachineBasicBlock *MBB = getParent())
  1841. if (const MachineFunction *MF = MBB->getParent())
  1842. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  1843. report_fatal_error(Msg);
  1844. }
  1845. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1846. const MCInstrDesc &MCID, bool IsIndirect,
  1847. Register Reg, const MDNode *Variable,
  1848. const MDNode *Expr) {
  1849. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1850. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1851. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1852. "Expected inlined-at fields to agree");
  1853. auto MIB = BuildMI(MF, DL, MCID).addReg(Reg);
  1854. if (IsIndirect)
  1855. MIB.addImm(0U);
  1856. else
  1857. MIB.addReg(0U);
  1858. return MIB.addMetadata(Variable).addMetadata(Expr);
  1859. }
  1860. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1861. const MCInstrDesc &MCID, bool IsIndirect,
  1862. const MachineOperand &MO,
  1863. const MDNode *Variable, const MDNode *Expr) {
  1864. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1865. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1866. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1867. "Expected inlined-at fields to agree");
  1868. if (MO.isReg())
  1869. return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr);
  1870. auto MIB = BuildMI(MF, DL, MCID).add(MO);
  1871. if (IsIndirect)
  1872. MIB.addImm(0U);
  1873. else
  1874. MIB.addReg(0U);
  1875. return MIB.addMetadata(Variable).addMetadata(Expr);
  1876. }
  1877. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1878. const MCInstrDesc &MCID, bool IsIndirect,
  1879. ArrayRef<MachineOperand> MOs,
  1880. const MDNode *Variable, const MDNode *Expr) {
  1881. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1882. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1883. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1884. "Expected inlined-at fields to agree");
  1885. if (MCID.Opcode == TargetOpcode::DBG_VALUE)
  1886. return BuildMI(MF, DL, MCID, IsIndirect, MOs[0], Variable, Expr);
  1887. auto MIB = BuildMI(MF, DL, MCID);
  1888. MIB.addMetadata(Variable).addMetadata(Expr);
  1889. for (const MachineOperand &MO : MOs)
  1890. if (MO.isReg())
  1891. MIB.addReg(MO.getReg());
  1892. else
  1893. MIB.add(MO);
  1894. return MIB;
  1895. }
  1896. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1897. MachineBasicBlock::iterator I,
  1898. const DebugLoc &DL, const MCInstrDesc &MCID,
  1899. bool IsIndirect, Register Reg,
  1900. const MDNode *Variable, const MDNode *Expr) {
  1901. MachineFunction &MF = *BB.getParent();
  1902. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
  1903. BB.insert(I, MI);
  1904. return MachineInstrBuilder(MF, MI);
  1905. }
  1906. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1907. MachineBasicBlock::iterator I,
  1908. const DebugLoc &DL, const MCInstrDesc &MCID,
  1909. bool IsIndirect, MachineOperand &MO,
  1910. const MDNode *Variable, const MDNode *Expr) {
  1911. MachineFunction &MF = *BB.getParent();
  1912. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr);
  1913. BB.insert(I, MI);
  1914. return MachineInstrBuilder(MF, *MI);
  1915. }
  1916. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1917. MachineBasicBlock::iterator I,
  1918. const DebugLoc &DL, const MCInstrDesc &MCID,
  1919. bool IsIndirect, ArrayRef<MachineOperand> MOs,
  1920. const MDNode *Variable, const MDNode *Expr) {
  1921. MachineFunction &MF = *BB.getParent();
  1922. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MOs, Variable, Expr);
  1923. BB.insert(I, MI);
  1924. return MachineInstrBuilder(MF, *MI);
  1925. }
  1926. /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
  1927. /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
  1928. static const DIExpression *
  1929. computeExprForSpill(const MachineInstr &MI,
  1930. SmallVectorImpl<const MachineOperand *> &SpilledOperands) {
  1931. assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
  1932. "Expected inlined-at fields to agree");
  1933. const DIExpression *Expr = MI.getDebugExpression();
  1934. if (MI.isIndirectDebugValue()) {
  1935. assert(MI.getDebugOffset().getImm() == 0 &&
  1936. "DBG_VALUE with nonzero offset");
  1937. Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
  1938. } else if (MI.isDebugValueList()) {
  1939. // We will replace the spilled register with a frame index, so
  1940. // immediately deref all references to the spilled register.
  1941. std::array<uint64_t, 1> Ops{{dwarf::DW_OP_deref}};
  1942. for (const MachineOperand *Op : SpilledOperands) {
  1943. unsigned OpIdx = MI.getDebugOperandIndex(Op);
  1944. Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx);
  1945. }
  1946. }
  1947. return Expr;
  1948. }
  1949. static const DIExpression *computeExprForSpill(const MachineInstr &MI,
  1950. Register SpillReg) {
  1951. assert(MI.hasDebugOperandForReg(SpillReg) && "Spill Reg is not used in MI.");
  1952. SmallVector<const MachineOperand *> SpillOperands;
  1953. for (const MachineOperand &Op : MI.getDebugOperandsForReg(SpillReg))
  1954. SpillOperands.push_back(&Op);
  1955. return computeExprForSpill(MI, SpillOperands);
  1956. }
  1957. MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
  1958. MachineBasicBlock::iterator I,
  1959. const MachineInstr &Orig,
  1960. int FrameIndex, Register SpillReg) {
  1961. const DIExpression *Expr = computeExprForSpill(Orig, SpillReg);
  1962. MachineInstrBuilder NewMI =
  1963. BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc());
  1964. // Non-Variadic Operands: Location, Offset, Variable, Expression
  1965. // Variadic Operands: Variable, Expression, Locations...
  1966. if (Orig.isNonListDebugValue())
  1967. NewMI.addFrameIndex(FrameIndex).addImm(0U);
  1968. NewMI.addMetadata(Orig.getDebugVariable()).addMetadata(Expr);
  1969. if (Orig.isDebugValueList()) {
  1970. for (const MachineOperand &Op : Orig.debug_operands())
  1971. if (Op.isReg() && Op.getReg() == SpillReg)
  1972. NewMI.addFrameIndex(FrameIndex);
  1973. else
  1974. NewMI.add(MachineOperand(Op));
  1975. }
  1976. return NewMI;
  1977. }
  1978. MachineInstr *llvm::buildDbgValueForSpill(
  1979. MachineBasicBlock &BB, MachineBasicBlock::iterator I,
  1980. const MachineInstr &Orig, int FrameIndex,
  1981. SmallVectorImpl<const MachineOperand *> &SpilledOperands) {
  1982. const DIExpression *Expr = computeExprForSpill(Orig, SpilledOperands);
  1983. MachineInstrBuilder NewMI =
  1984. BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc());
  1985. // Non-Variadic Operands: Location, Offset, Variable, Expression
  1986. // Variadic Operands: Variable, Expression, Locations...
  1987. if (Orig.isNonListDebugValue())
  1988. NewMI.addFrameIndex(FrameIndex).addImm(0U);
  1989. NewMI.addMetadata(Orig.getDebugVariable()).addMetadata(Expr);
  1990. if (Orig.isDebugValueList()) {
  1991. for (const MachineOperand &Op : Orig.debug_operands())
  1992. if (is_contained(SpilledOperands, &Op))
  1993. NewMI.addFrameIndex(FrameIndex);
  1994. else
  1995. NewMI.add(MachineOperand(Op));
  1996. }
  1997. return NewMI;
  1998. }
  1999. void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex,
  2000. Register Reg) {
  2001. const DIExpression *Expr = computeExprForSpill(Orig, Reg);
  2002. if (Orig.isNonListDebugValue())
  2003. Orig.getDebugOffset().ChangeToImmediate(0U);
  2004. for (MachineOperand &Op : Orig.getDebugOperandsForReg(Reg))
  2005. Op.ChangeToFrameIndex(FrameIndex);
  2006. Orig.getDebugExpressionOp().setMetadata(Expr);
  2007. }
  2008. void MachineInstr::collectDebugValues(
  2009. SmallVectorImpl<MachineInstr *> &DbgValues) {
  2010. MachineInstr &MI = *this;
  2011. if (!MI.getOperand(0).isReg())
  2012. return;
  2013. MachineBasicBlock::iterator DI = MI; ++DI;
  2014. for (MachineBasicBlock::iterator DE = MI.getParent()->end();
  2015. DI != DE; ++DI) {
  2016. if (!DI->isDebugValue())
  2017. return;
  2018. if (DI->hasDebugOperandForReg(MI.getOperand(0).getReg()))
  2019. DbgValues.push_back(&*DI);
  2020. }
  2021. }
  2022. void MachineInstr::changeDebugValuesDefReg(Register Reg) {
  2023. // Collect matching debug values.
  2024. SmallVector<MachineInstr *, 2> DbgValues;
  2025. if (!getOperand(0).isReg())
  2026. return;
  2027. Register DefReg = getOperand(0).getReg();
  2028. auto *MRI = getRegInfo();
  2029. for (auto &MO : MRI->use_operands(DefReg)) {
  2030. auto *DI = MO.getParent();
  2031. if (!DI->isDebugValue())
  2032. continue;
  2033. if (DI->hasDebugOperandForReg(DefReg)) {
  2034. DbgValues.push_back(DI);
  2035. }
  2036. }
  2037. // Propagate Reg to debug value instructions.
  2038. for (auto *DBI : DbgValues)
  2039. for (MachineOperand &Op : DBI->getDebugOperandsForReg(DefReg))
  2040. Op.setReg(Reg);
  2041. }
  2042. using MMOList = SmallVector<const MachineMemOperand *, 2>;
  2043. static unsigned getSpillSlotSize(const MMOList &Accesses,
  2044. const MachineFrameInfo &MFI) {
  2045. unsigned Size = 0;
  2046. for (auto A : Accesses)
  2047. if (MFI.isSpillSlotObjectIndex(
  2048. cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
  2049. ->getFrameIndex()))
  2050. Size += A->getSize();
  2051. return Size;
  2052. }
  2053. Optional<unsigned>
  2054. MachineInstr::getSpillSize(const TargetInstrInfo *TII) const {
  2055. int FI;
  2056. if (TII->isStoreToStackSlotPostFE(*this, FI)) {
  2057. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  2058. if (MFI.isSpillSlotObjectIndex(FI))
  2059. return (*memoperands_begin())->getSize();
  2060. }
  2061. return None;
  2062. }
  2063. Optional<unsigned>
  2064. MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const {
  2065. MMOList Accesses;
  2066. if (TII->hasStoreToStackSlot(*this, Accesses))
  2067. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  2068. return None;
  2069. }
  2070. Optional<unsigned>
  2071. MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const {
  2072. int FI;
  2073. if (TII->isLoadFromStackSlotPostFE(*this, FI)) {
  2074. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  2075. if (MFI.isSpillSlotObjectIndex(FI))
  2076. return (*memoperands_begin())->getSize();
  2077. }
  2078. return None;
  2079. }
  2080. Optional<unsigned>
  2081. MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const {
  2082. MMOList Accesses;
  2083. if (TII->hasLoadFromStackSlot(*this, Accesses))
  2084. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  2085. return None;
  2086. }
  2087. unsigned MachineInstr::getDebugInstrNum() {
  2088. if (DebugInstrNum == 0)
  2089. DebugInstrNum = getParent()->getParent()->getNewDebugInstrNum();
  2090. return DebugInstrNum;
  2091. }
  2092. unsigned MachineInstr::getDebugInstrNum(MachineFunction &MF) {
  2093. if (DebugInstrNum == 0)
  2094. DebugInstrNum = MF.getNewDebugInstrNum();
  2095. return DebugInstrNum;
  2096. }