MachineInstr.cpp 65 KB

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