MachineInstr.cpp 72 KB

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