MachineInstr.cpp 82 KB

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