MachineInstr.cpp 63 KB

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