InstrEmitter.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This implements the Emit routines for the SelectionDAG class, which creates
  11. // MachineInstrs based on the decisions of the SelectionDAG instruction
  12. // selection.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "InstrEmitter.h"
  16. #include "SDNodeDbgValue.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/CodeGen/MachineConstantPool.h"
  19. #include "llvm/CodeGen/MachineFunction.h"
  20. #include "llvm/CodeGen/MachineInstrBuilder.h"
  21. #include "llvm/CodeGen/MachineRegisterInfo.h"
  22. #include "llvm/CodeGen/StackMaps.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Target/TargetInstrInfo.h"
  28. #include "llvm/Target/TargetLowering.h"
  29. #include "llvm/Target/TargetSubtargetInfo.h"
  30. using namespace llvm;
  31. #define DEBUG_TYPE "instr-emitter"
  32. /// MinRCSize - Smallest register class we allow when constraining virtual
  33. /// registers. If satisfying all register class constraints would require
  34. /// using a smaller register class, emit a COPY to a new virtual register
  35. /// instead.
  36. const unsigned MinRCSize = 4;
  37. /// CountResults - The results of target nodes have register or immediate
  38. /// operands first, then an optional chain, and optional glue operands (which do
  39. /// not go into the resulting MachineInstr).
  40. unsigned InstrEmitter::CountResults(SDNode *Node) {
  41. unsigned N = Node->getNumValues();
  42. while (N && Node->getValueType(N - 1) == MVT::Glue)
  43. --N;
  44. if (N && Node->getValueType(N - 1) == MVT::Other)
  45. --N; // Skip over chain result.
  46. return N;
  47. }
  48. /// countOperands - The inputs to target nodes have any actual inputs first,
  49. /// followed by an optional chain operand, then an optional glue operand.
  50. /// Compute the number of actual operands that will go into the resulting
  51. /// MachineInstr.
  52. ///
  53. /// Also count physreg RegisterSDNode and RegisterMaskSDNode operands preceding
  54. /// the chain and glue. These operands may be implicit on the machine instr.
  55. static unsigned countOperands(SDNode *Node, unsigned NumExpUses,
  56. unsigned &NumImpUses) {
  57. unsigned N = Node->getNumOperands();
  58. while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
  59. --N;
  60. if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
  61. --N; // Ignore chain if it exists.
  62. // Count RegisterSDNode and RegisterMaskSDNode operands for NumImpUses.
  63. NumImpUses = N - NumExpUses;
  64. for (unsigned I = N; I > NumExpUses; --I) {
  65. if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1)))
  66. continue;
  67. if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1)))
  68. if (TargetRegisterInfo::isPhysicalRegister(RN->getReg()))
  69. continue;
  70. NumImpUses = N - I;
  71. break;
  72. }
  73. return N;
  74. }
  75. /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
  76. /// implicit physical register output.
  77. void InstrEmitter::
  78. EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
  79. unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
  80. unsigned VRBase = 0;
  81. if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
  82. // Just use the input register directly!
  83. SDValue Op(Node, ResNo);
  84. if (IsClone)
  85. VRBaseMap.erase(Op);
  86. bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
  87. (void)isNew; // Silence compiler warning.
  88. assert(isNew && "Node emitted out of order - early");
  89. return;
  90. }
  91. // If the node is only used by a CopyToReg and the dest reg is a vreg, use
  92. // the CopyToReg'd destination register instead of creating a new vreg.
  93. bool MatchReg = true;
  94. const TargetRegisterClass *UseRC = nullptr;
  95. MVT VT = Node->getSimpleValueType(ResNo);
  96. // Stick to the preferred register classes for legal types.
  97. if (TLI->isTypeLegal(VT))
  98. UseRC = TLI->getRegClassFor(VT);
  99. if (!IsClone && !IsCloned)
  100. for (SDNode *User : Node->uses()) {
  101. bool Match = true;
  102. if (User->getOpcode() == ISD::CopyToReg &&
  103. User->getOperand(2).getNode() == Node &&
  104. User->getOperand(2).getResNo() == ResNo) {
  105. unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
  106. if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
  107. VRBase = DestReg;
  108. Match = false;
  109. } else if (DestReg != SrcReg)
  110. Match = false;
  111. } else {
  112. for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
  113. SDValue Op = User->getOperand(i);
  114. if (Op.getNode() != Node || Op.getResNo() != ResNo)
  115. continue;
  116. MVT VT = Node->getSimpleValueType(Op.getResNo());
  117. if (VT == MVT::Other || VT == MVT::Glue)
  118. continue;
  119. Match = false;
  120. if (User->isMachineOpcode()) {
  121. const MCInstrDesc &II = TII->get(User->getMachineOpcode());
  122. const TargetRegisterClass *RC = nullptr;
  123. if (i+II.getNumDefs() < II.getNumOperands()) {
  124. RC = TRI->getAllocatableClass(
  125. TII->getRegClass(II, i+II.getNumDefs(), TRI, *MF));
  126. }
  127. if (!UseRC)
  128. UseRC = RC;
  129. else if (RC) {
  130. const TargetRegisterClass *ComRC =
  131. TRI->getCommonSubClass(UseRC, RC);
  132. // If multiple uses expect disjoint register classes, we emit
  133. // copies in AddRegisterOperand.
  134. if (ComRC)
  135. UseRC = ComRC;
  136. }
  137. }
  138. }
  139. }
  140. MatchReg &= Match;
  141. if (VRBase)
  142. break;
  143. }
  144. const TargetRegisterClass *SrcRC = nullptr, *DstRC = nullptr;
  145. SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
  146. // Figure out the register class to create for the destreg.
  147. if (VRBase) {
  148. DstRC = MRI->getRegClass(VRBase);
  149. } else if (UseRC) {
  150. assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
  151. DstRC = UseRC;
  152. } else {
  153. DstRC = TLI->getRegClassFor(VT);
  154. }
  155. // If all uses are reading from the src physical register and copying the
  156. // register is either impossible or very expensive, then don't create a copy.
  157. if (MatchReg && SrcRC->getCopyCost() < 0) {
  158. VRBase = SrcReg;
  159. } else {
  160. // Create the reg, emit the copy.
  161. VRBase = MRI->createVirtualRegister(DstRC);
  162. BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
  163. VRBase).addReg(SrcReg);
  164. }
  165. SDValue Op(Node, ResNo);
  166. if (IsClone)
  167. VRBaseMap.erase(Op);
  168. bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
  169. (void)isNew; // Silence compiler warning.
  170. assert(isNew && "Node emitted out of order - early");
  171. }
  172. /// getDstOfCopyToRegUse - If the only use of the specified result number of
  173. /// node is a CopyToReg, return its destination register. Return 0 otherwise.
  174. unsigned InstrEmitter::getDstOfOnlyCopyToRegUse(SDNode *Node,
  175. unsigned ResNo) const {
  176. if (!Node->hasOneUse())
  177. return 0;
  178. SDNode *User = *Node->use_begin();
  179. if (User->getOpcode() == ISD::CopyToReg &&
  180. User->getOperand(2).getNode() == Node &&
  181. User->getOperand(2).getResNo() == ResNo) {
  182. unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
  183. if (TargetRegisterInfo::isVirtualRegister(Reg))
  184. return Reg;
  185. }
  186. return 0;
  187. }
  188. void InstrEmitter::CreateVirtualRegisters(SDNode *Node,
  189. MachineInstrBuilder &MIB,
  190. const MCInstrDesc &II,
  191. bool IsClone, bool IsCloned,
  192. DenseMap<SDValue, unsigned> &VRBaseMap) {
  193. assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
  194. "IMPLICIT_DEF should have been handled as a special case elsewhere!");
  195. unsigned NumResults = CountResults(Node);
  196. for (unsigned i = 0; i < II.getNumDefs(); ++i) {
  197. // If the specific node value is only used by a CopyToReg and the dest reg
  198. // is a vreg in the same register class, use the CopyToReg'd destination
  199. // register instead of creating a new vreg.
  200. unsigned VRBase = 0;
  201. const TargetRegisterClass *RC =
  202. TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF));
  203. // Always let the value type influence the used register class. The
  204. // constraints on the instruction may be too lax to represent the value
  205. // type correctly. For example, a 64-bit float (X86::FR64) can't live in
  206. // the 32-bit float super-class (X86::FR32).
  207. if (i < NumResults && TLI->isTypeLegal(Node->getSimpleValueType(i))) {
  208. const TargetRegisterClass *VTRC =
  209. TLI->getRegClassFor(Node->getSimpleValueType(i));
  210. if (RC)
  211. VTRC = TRI->getCommonSubClass(RC, VTRC);
  212. if (VTRC)
  213. RC = VTRC;
  214. }
  215. if (II.OpInfo[i].isOptionalDef()) {
  216. // Optional def must be a physical register.
  217. unsigned NumResults = CountResults(Node);
  218. VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
  219. assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
  220. MIB.addReg(VRBase, RegState::Define);
  221. }
  222. if (!VRBase && !IsClone && !IsCloned)
  223. for (SDNode *User : Node->uses()) {
  224. if (User->getOpcode() == ISD::CopyToReg &&
  225. User->getOperand(2).getNode() == Node &&
  226. User->getOperand(2).getResNo() == i) {
  227. unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
  228. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  229. const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
  230. if (RegRC == RC) {
  231. VRBase = Reg;
  232. MIB.addReg(VRBase, RegState::Define);
  233. break;
  234. }
  235. }
  236. }
  237. }
  238. // Create the result registers for this node and add the result regs to
  239. // the machine instruction.
  240. if (VRBase == 0) {
  241. assert(RC && "Isn't a register operand!");
  242. VRBase = MRI->createVirtualRegister(RC);
  243. MIB.addReg(VRBase, RegState::Define);
  244. }
  245. // If this def corresponds to a result of the SDNode insert the VRBase into
  246. // the lookup map.
  247. if (i < NumResults) {
  248. SDValue Op(Node, i);
  249. if (IsClone)
  250. VRBaseMap.erase(Op);
  251. bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
  252. (void)isNew; // Silence compiler warning.
  253. assert(isNew && "Node emitted out of order - early");
  254. }
  255. }
  256. }
  257. /// getVR - Return the virtual register corresponding to the specified result
  258. /// of the specified node.
  259. unsigned InstrEmitter::getVR(SDValue Op,
  260. DenseMap<SDValue, unsigned> &VRBaseMap) {
  261. if (Op.isMachineOpcode() &&
  262. Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
  263. // Add an IMPLICIT_DEF instruction before every use.
  264. unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
  265. // IMPLICIT_DEF can produce any type of result so its MCInstrDesc
  266. // does not include operand register class info.
  267. if (!VReg) {
  268. const TargetRegisterClass *RC =
  269. TLI->getRegClassFor(Op.getSimpleValueType());
  270. VReg = MRI->createVirtualRegister(RC);
  271. }
  272. BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
  273. TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
  274. return VReg;
  275. }
  276. DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
  277. assert(I != VRBaseMap.end() && "Node emitted out of order - late");
  278. return I->second;
  279. }
  280. /// AddRegisterOperand - Add the specified register as an operand to the
  281. /// specified machine instr. Insert register copies if the register is
  282. /// not in the required register class.
  283. void
  284. InstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB,
  285. SDValue Op,
  286. unsigned IIOpNum,
  287. const MCInstrDesc *II,
  288. DenseMap<SDValue, unsigned> &VRBaseMap,
  289. bool IsDebug, bool IsClone, bool IsCloned) {
  290. assert(Op.getValueType() != MVT::Other &&
  291. Op.getValueType() != MVT::Glue &&
  292. "Chain and glue operands should occur at end of operand list!");
  293. // Get/emit the operand.
  294. unsigned VReg = getVR(Op, VRBaseMap);
  295. assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
  296. const MCInstrDesc &MCID = MIB->getDesc();
  297. bool isOptDef = IIOpNum < MCID.getNumOperands() &&
  298. MCID.OpInfo[IIOpNum].isOptionalDef();
  299. // If the instruction requires a register in a different class, create
  300. // a new virtual register and copy the value into it, but first attempt to
  301. // shrink VReg's register class within reason. For example, if VReg == GR32
  302. // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
  303. if (II) {
  304. const TargetRegisterClass *DstRC = nullptr;
  305. if (IIOpNum < II->getNumOperands())
  306. DstRC = TRI->getAllocatableClass(TII->getRegClass(*II,IIOpNum,TRI,*MF));
  307. if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
  308. unsigned NewVReg = MRI->createVirtualRegister(DstRC);
  309. BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
  310. TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
  311. VReg = NewVReg;
  312. }
  313. }
  314. // If this value has only one use, that use is a kill. This is a
  315. // conservative approximation. InstrEmitter does trivial coalescing
  316. // with CopyFromReg nodes, so don't emit kill flags for them.
  317. // Avoid kill flags on Schedule cloned nodes, since there will be
  318. // multiple uses.
  319. // Tied operands are never killed, so we need to check that. And that
  320. // means we need to determine the index of the operand.
  321. bool isKill = Op.hasOneUse() &&
  322. Op.getNode()->getOpcode() != ISD::CopyFromReg &&
  323. !IsDebug &&
  324. !(IsClone || IsCloned);
  325. if (isKill) {
  326. unsigned Idx = MIB->getNumOperands();
  327. while (Idx > 0 &&
  328. MIB->getOperand(Idx-1).isReg() &&
  329. MIB->getOperand(Idx-1).isImplicit())
  330. --Idx;
  331. bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
  332. if (isTied)
  333. isKill = false;
  334. }
  335. MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) |
  336. getDebugRegState(IsDebug));
  337. }
  338. /// AddOperand - Add the specified operand to the specified machine instr. II
  339. /// specifies the instruction information for the node, and IIOpNum is the
  340. /// operand number (in the II) that we are adding.
  341. void InstrEmitter::AddOperand(MachineInstrBuilder &MIB,
  342. SDValue Op,
  343. unsigned IIOpNum,
  344. const MCInstrDesc *II,
  345. DenseMap<SDValue, unsigned> &VRBaseMap,
  346. bool IsDebug, bool IsClone, bool IsCloned) {
  347. if (Op.isMachineOpcode()) {
  348. AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
  349. IsDebug, IsClone, IsCloned);
  350. } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
  351. MIB.addImm(C->getSExtValue());
  352. } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
  353. MIB.addFPImm(F->getConstantFPValue());
  354. } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
  355. // Turn additional physreg operands into implicit uses on non-variadic
  356. // instructions. This is used by call and return instructions passing
  357. // arguments in registers.
  358. bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic());
  359. MIB.addReg(R->getReg(), getImplRegState(Imp));
  360. } else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
  361. MIB.addRegMask(RM->getRegMask());
  362. } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
  363. MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(),
  364. TGA->getTargetFlags());
  365. } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
  366. MIB.addMBB(BBNode->getBasicBlock());
  367. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
  368. MIB.addFrameIndex(FI->getIndex());
  369. } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
  370. MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags());
  371. } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
  372. int Offset = CP->getOffset();
  373. unsigned Align = CP->getAlignment();
  374. Type *Type = CP->getType();
  375. // MachineConstantPool wants an explicit alignment.
  376. if (Align == 0) {
  377. Align = MF->getDataLayout().getPrefTypeAlignment(Type);
  378. if (Align == 0) {
  379. // Alignment of vector types. FIXME!
  380. Align = MF->getDataLayout().getTypeAllocSize(Type);
  381. }
  382. }
  383. unsigned Idx;
  384. MachineConstantPool *MCP = MF->getConstantPool();
  385. if (CP->isMachineConstantPoolEntry())
  386. Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
  387. else
  388. Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
  389. MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags());
  390. } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
  391. MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags());
  392. } else if (auto *SymNode = dyn_cast<MCSymbolSDNode>(Op)) {
  393. MIB.addSym(SymNode->getMCSymbol());
  394. } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
  395. MIB.addBlockAddress(BA->getBlockAddress(),
  396. BA->getOffset(),
  397. BA->getTargetFlags());
  398. } else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
  399. MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags());
  400. } else {
  401. assert(Op.getValueType() != MVT::Other &&
  402. Op.getValueType() != MVT::Glue &&
  403. "Chain and glue operands should occur at end of operand list!");
  404. AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
  405. IsDebug, IsClone, IsCloned);
  406. }
  407. }
  408. unsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
  409. MVT VT, DebugLoc DL) {
  410. const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
  411. const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
  412. // RC is a sub-class of VRC that supports SubIdx. Try to constrain VReg
  413. // within reason.
  414. if (RC && RC != VRC)
  415. RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
  416. // VReg has been adjusted. It can be used with SubIdx operands now.
  417. if (RC)
  418. return VReg;
  419. // VReg couldn't be reasonably constrained. Emit a COPY to a new virtual
  420. // register instead.
  421. RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
  422. assert(RC && "No legal register class for VT supports that SubIdx");
  423. unsigned NewReg = MRI->createVirtualRegister(RC);
  424. BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
  425. .addReg(VReg);
  426. return NewReg;
  427. }
  428. /// EmitSubregNode - Generate machine code for subreg nodes.
  429. ///
  430. void InstrEmitter::EmitSubregNode(SDNode *Node,
  431. DenseMap<SDValue, unsigned> &VRBaseMap,
  432. bool IsClone, bool IsCloned) {
  433. unsigned VRBase = 0;
  434. unsigned Opc = Node->getMachineOpcode();
  435. // If the node is only used by a CopyToReg and the dest reg is a vreg, use
  436. // the CopyToReg'd destination register instead of creating a new vreg.
  437. for (SDNode *User : Node->uses()) {
  438. if (User->getOpcode() == ISD::CopyToReg &&
  439. User->getOperand(2).getNode() == Node) {
  440. unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
  441. if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
  442. VRBase = DestReg;
  443. break;
  444. }
  445. }
  446. }
  447. if (Opc == TargetOpcode::EXTRACT_SUBREG) {
  448. // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub. There are no
  449. // constraints on the %dst register, COPY can target all legal register
  450. // classes.
  451. unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
  452. const TargetRegisterClass *TRC =
  453. TLI->getRegClassFor(Node->getSimpleValueType(0));
  454. unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
  455. MachineInstr *DefMI = MRI->getVRegDef(VReg);
  456. unsigned SrcReg, DstReg, DefSubIdx;
  457. if (DefMI &&
  458. TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
  459. SubIdx == DefSubIdx &&
  460. TRC == MRI->getRegClass(SrcReg)) {
  461. // Optimize these:
  462. // r1025 = s/zext r1024, 4
  463. // r1026 = extract_subreg r1025, 4
  464. // to a copy
  465. // r1026 = copy r1024
  466. VRBase = MRI->createVirtualRegister(TRC);
  467. BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
  468. TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
  469. MRI->clearKillFlags(SrcReg);
  470. } else {
  471. // VReg may not support a SubIdx sub-register, and we may need to
  472. // constrain its register class or issue a COPY to a compatible register
  473. // class.
  474. VReg = ConstrainForSubReg(VReg, SubIdx,
  475. Node->getOperand(0).getSimpleValueType(),
  476. Node->getDebugLoc());
  477. // Create the destreg if it is missing.
  478. if (VRBase == 0)
  479. VRBase = MRI->createVirtualRegister(TRC);
  480. // Create the extract_subreg machine instruction.
  481. BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
  482. TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
  483. }
  484. } else if (Opc == TargetOpcode::INSERT_SUBREG ||
  485. Opc == TargetOpcode::SUBREG_TO_REG) {
  486. SDValue N0 = Node->getOperand(0);
  487. SDValue N1 = Node->getOperand(1);
  488. SDValue N2 = Node->getOperand(2);
  489. unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
  490. // Figure out the register class to create for the destreg. It should be
  491. // the largest legal register class supporting SubIdx sub-registers.
  492. // RegisterCoalescer will constrain it further if it decides to eliminate
  493. // the INSERT_SUBREG instruction.
  494. //
  495. // %dst = INSERT_SUBREG %src, %sub, SubIdx
  496. //
  497. // is lowered by TwoAddressInstructionPass to:
  498. //
  499. // %dst = COPY %src
  500. // %dst:SubIdx = COPY %sub
  501. //
  502. // There is no constraint on the %src register class.
  503. //
  504. const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getSimpleValueType(0));
  505. SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
  506. assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
  507. if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
  508. VRBase = MRI->createVirtualRegister(SRC);
  509. // Create the insert_subreg or subreg_to_reg machine instruction.
  510. MachineInstrBuilder MIB =
  511. BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
  512. // If creating a subreg_to_reg, then the first input operand
  513. // is an implicit value immediate, otherwise it's a register
  514. if (Opc == TargetOpcode::SUBREG_TO_REG) {
  515. const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
  516. MIB.addImm(SD->getZExtValue());
  517. } else
  518. AddOperand(MIB, N0, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
  519. IsClone, IsCloned);
  520. // Add the subregster being inserted
  521. AddOperand(MIB, N1, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
  522. IsClone, IsCloned);
  523. MIB.addImm(SubIdx);
  524. MBB->insert(InsertPos, MIB);
  525. } else
  526. llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
  527. SDValue Op(Node, 0);
  528. bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
  529. (void)isNew; // Silence compiler warning.
  530. assert(isNew && "Node emitted out of order - early");
  531. }
  532. /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
  533. /// COPY_TO_REGCLASS is just a normal copy, except that the destination
  534. /// register is constrained to be in a particular register class.
  535. ///
  536. void
  537. InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
  538. DenseMap<SDValue, unsigned> &VRBaseMap) {
  539. unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
  540. // Create the new VReg in the destination class and emit a copy.
  541. unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
  542. const TargetRegisterClass *DstRC =
  543. TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx));
  544. unsigned NewVReg = MRI->createVirtualRegister(DstRC);
  545. BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
  546. NewVReg).addReg(VReg);
  547. SDValue Op(Node, 0);
  548. bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
  549. (void)isNew; // Silence compiler warning.
  550. assert(isNew && "Node emitted out of order - early");
  551. }
  552. /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
  553. ///
  554. void InstrEmitter::EmitRegSequence(SDNode *Node,
  555. DenseMap<SDValue, unsigned> &VRBaseMap,
  556. bool IsClone, bool IsCloned) {
  557. unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
  558. const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
  559. unsigned NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC));
  560. const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
  561. MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg);
  562. unsigned NumOps = Node->getNumOperands();
  563. assert((NumOps & 1) == 1 &&
  564. "REG_SEQUENCE must have an odd number of operands!");
  565. for (unsigned i = 1; i != NumOps; ++i) {
  566. SDValue Op = Node->getOperand(i);
  567. if ((i & 1) == 0) {
  568. RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
  569. // Skip physical registers as they don't have a vreg to get and we'll
  570. // insert copies for them in TwoAddressInstructionPass anyway.
  571. if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
  572. unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
  573. unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
  574. const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
  575. const TargetRegisterClass *SRC =
  576. TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
  577. if (SRC && SRC != RC) {
  578. MRI->setRegClass(NewVReg, SRC);
  579. RC = SRC;
  580. }
  581. }
  582. }
  583. AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
  584. IsClone, IsCloned);
  585. }
  586. MBB->insert(InsertPos, MIB);
  587. SDValue Op(Node, 0);
  588. bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
  589. (void)isNew; // Silence compiler warning.
  590. assert(isNew && "Node emitted out of order - early");
  591. }
  592. /// EmitDbgValue - Generate machine instruction for a dbg_value node.
  593. ///
  594. MachineInstr *
  595. InstrEmitter::EmitDbgValue(SDDbgValue *SD,
  596. DenseMap<SDValue, unsigned> &VRBaseMap) {
  597. uint64_t Offset = SD->getOffset();
  598. MDNode *Var = SD->getVariable();
  599. MDNode *Expr = SD->getExpression();
  600. DebugLoc DL = SD->getDebugLoc();
  601. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  602. "Expected inlined-at fields to agree");
  603. if (SD->getKind() == SDDbgValue::FRAMEIX) {
  604. // Stack address; this needs to be lowered in target-dependent fashion.
  605. // EmitTargetCodeForFrameDebugValue is responsible for allocation.
  606. return BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE))
  607. .addFrameIndex(SD->getFrameIx())
  608. .addImm(Offset)
  609. .addMetadata(Var)
  610. .addMetadata(Expr);
  611. }
  612. // Otherwise, we're going to create an instruction here.
  613. const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
  614. MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
  615. if (SD->getKind() == SDDbgValue::SDNODE) {
  616. SDNode *Node = SD->getSDNode();
  617. SDValue Op = SDValue(Node, SD->getResNo());
  618. // It's possible we replaced this SDNode with other(s) and therefore
  619. // didn't generate code for it. It's better to catch these cases where
  620. // they happen and transfer the debug info, but trying to guarantee that
  621. // in all cases would be very fragile; this is a safeguard for any
  622. // that were missed.
  623. DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
  624. if (I==VRBaseMap.end())
  625. MIB.addReg(0U); // undef
  626. else
  627. AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
  628. /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
  629. } else if (SD->getKind() == SDDbgValue::CONST) {
  630. const Value *V = SD->getConst();
  631. if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  632. if (CI->getBitWidth() > 64)
  633. MIB.addCImm(CI);
  634. else
  635. MIB.addImm(CI->getSExtValue());
  636. } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
  637. MIB.addFPImm(CF);
  638. } else {
  639. // Could be an Undef. In any case insert an Undef so we can see what we
  640. // dropped.
  641. MIB.addReg(0U);
  642. }
  643. } else {
  644. // Insert an Undef so we can see what we dropped.
  645. MIB.addReg(0U);
  646. }
  647. // Indirect addressing is indicated by an Imm as the second parameter.
  648. if (SD->isIndirect())
  649. MIB.addImm(Offset);
  650. else {
  651. assert(Offset == 0 && "direct value cannot have an offset");
  652. MIB.addReg(0U, RegState::Debug);
  653. }
  654. MIB.addMetadata(Var);
  655. MIB.addMetadata(Expr);
  656. return &*MIB;
  657. }
  658. /// EmitMachineNode - Generate machine code for a target-specific node and
  659. /// needed dependencies.
  660. ///
  661. void InstrEmitter::
  662. EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
  663. DenseMap<SDValue, unsigned> &VRBaseMap) {
  664. unsigned Opc = Node->getMachineOpcode();
  665. // Handle subreg insert/extract specially
  666. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  667. Opc == TargetOpcode::INSERT_SUBREG ||
  668. Opc == TargetOpcode::SUBREG_TO_REG) {
  669. EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
  670. return;
  671. }
  672. // Handle COPY_TO_REGCLASS specially.
  673. if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
  674. EmitCopyToRegClassNode(Node, VRBaseMap);
  675. return;
  676. }
  677. // Handle REG_SEQUENCE specially.
  678. if (Opc == TargetOpcode::REG_SEQUENCE) {
  679. EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
  680. return;
  681. }
  682. if (Opc == TargetOpcode::IMPLICIT_DEF)
  683. // We want a unique VR for each IMPLICIT_DEF use.
  684. return;
  685. const MCInstrDesc &II = TII->get(Opc);
  686. unsigned NumResults = CountResults(Node);
  687. unsigned NumDefs = II.getNumDefs();
  688. const MCPhysReg *ScratchRegs = nullptr;
  689. // Handle STACKMAP and PATCHPOINT specially and then use the generic code.
  690. if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) {
  691. // Stackmaps do not have arguments and do not preserve their calling
  692. // convention. However, to simplify runtime support, they clobber the same
  693. // scratch registers as AnyRegCC.
  694. unsigned CC = CallingConv::AnyReg;
  695. if (Opc == TargetOpcode::PATCHPOINT) {
  696. CC = Node->getConstantOperandVal(PatchPointOpers::CCPos);
  697. NumDefs = NumResults;
  698. }
  699. ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC);
  700. }
  701. unsigned NumImpUses = 0;
  702. unsigned NodeOperands =
  703. countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
  704. bool HasPhysRegOuts = NumResults > NumDefs && II.getImplicitDefs()!=nullptr;
  705. #ifndef NDEBUG
  706. unsigned NumMIOperands = NodeOperands + NumResults;
  707. if (II.isVariadic())
  708. assert(NumMIOperands >= II.getNumOperands() &&
  709. "Too few operands for a variadic node!");
  710. else
  711. assert(NumMIOperands >= II.getNumOperands() &&
  712. NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
  713. NumImpUses &&
  714. "#operands for dag node doesn't match .td file!");
  715. #endif
  716. // Create the new machine instruction.
  717. MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
  718. // Add result register values for things that are defined by this
  719. // instruction.
  720. if (NumResults)
  721. CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
  722. // Emit all of the actual operands of this instruction, adding them to the
  723. // instruction as appropriate.
  724. bool HasOptPRefs = NumDefs > NumResults;
  725. assert((!HasOptPRefs || !HasPhysRegOuts) &&
  726. "Unable to cope with optional defs and phys regs defs!");
  727. unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0;
  728. for (unsigned i = NumSkip; i != NodeOperands; ++i)
  729. AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II,
  730. VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
  731. // Add scratch registers as implicit def and early clobber
  732. if (ScratchRegs)
  733. for (unsigned i = 0; ScratchRegs[i]; ++i)
  734. MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine |
  735. RegState::EarlyClobber);
  736. // Transfer all of the memory reference descriptions of this instruction.
  737. MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
  738. cast<MachineSDNode>(Node)->memoperands_end());
  739. // Insert the instruction into position in the block. This needs to
  740. // happen before any custom inserter hook is called so that the
  741. // hook knows where in the block to insert the replacement code.
  742. MBB->insert(InsertPos, MIB);
  743. // The MachineInstr may also define physregs instead of virtregs. These
  744. // physreg values can reach other instructions in different ways:
  745. //
  746. // 1. When there is a use of a Node value beyond the explicitly defined
  747. // virtual registers, we emit a CopyFromReg for one of the implicitly
  748. // defined physregs. This only happens when HasPhysRegOuts is true.
  749. //
  750. // 2. A CopyFromReg reading a physreg may be glued to this instruction.
  751. //
  752. // 3. A glued instruction may implicitly use a physreg.
  753. //
  754. // 4. A glued instruction may use a RegisterSDNode operand.
  755. //
  756. // Collect all the used physreg defs, and make sure that any unused physreg
  757. // defs are marked as dead.
  758. SmallVector<unsigned, 8> UsedRegs;
  759. // Additional results must be physical register defs.
  760. if (HasPhysRegOuts) {
  761. for (unsigned i = NumDefs; i < NumResults; ++i) {
  762. unsigned Reg = II.getImplicitDefs()[i - NumDefs];
  763. if (!Node->hasAnyUseOfValue(i))
  764. continue;
  765. // This implicitly defined physreg has a use.
  766. UsedRegs.push_back(Reg);
  767. EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
  768. }
  769. }
  770. // Scan the glue chain for any used physregs.
  771. if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
  772. for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
  773. if (F->getOpcode() == ISD::CopyFromReg) {
  774. UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
  775. continue;
  776. } else if (F->getOpcode() == ISD::CopyToReg) {
  777. // Skip CopyToReg nodes that are internal to the glue chain.
  778. continue;
  779. }
  780. // Collect declared implicit uses.
  781. const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
  782. UsedRegs.append(MCID.getImplicitUses(),
  783. MCID.getImplicitUses() + MCID.getNumImplicitUses());
  784. // In addition to declared implicit uses, we must also check for
  785. // direct RegisterSDNode operands.
  786. for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
  787. if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
  788. unsigned Reg = R->getReg();
  789. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  790. UsedRegs.push_back(Reg);
  791. }
  792. }
  793. }
  794. // Finally mark unused registers as dead.
  795. if (!UsedRegs.empty() || II.getImplicitDefs())
  796. MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
  797. // Run post-isel target hook to adjust this instruction if needed.
  798. if (II.hasPostISelHook())
  799. TLI->AdjustInstrPostInstrSelection(MIB, Node);
  800. }
  801. /// EmitSpecialNode - Generate machine code for a target-independent node and
  802. /// needed dependencies.
  803. void InstrEmitter::
  804. EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
  805. DenseMap<SDValue, unsigned> &VRBaseMap) {
  806. switch (Node->getOpcode()) {
  807. default:
  808. #ifndef NDEBUG
  809. Node->dump();
  810. #endif
  811. llvm_unreachable("This target-independent node should have been selected!");
  812. case ISD::EntryToken:
  813. llvm_unreachable("EntryToken should have been excluded from the schedule!");
  814. case ISD::MERGE_VALUES:
  815. case ISD::TokenFactor: // fall thru
  816. break;
  817. case ISD::CopyToReg: {
  818. unsigned SrcReg;
  819. SDValue SrcVal = Node->getOperand(2);
  820. if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
  821. SrcReg = R->getReg();
  822. else
  823. SrcReg = getVR(SrcVal, VRBaseMap);
  824. unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
  825. if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
  826. break;
  827. BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
  828. DestReg).addReg(SrcReg);
  829. break;
  830. }
  831. case ISD::CopyFromReg: {
  832. unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
  833. EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
  834. break;
  835. }
  836. case ISD::EH_LABEL: {
  837. MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
  838. BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
  839. TII->get(TargetOpcode::EH_LABEL)).addSym(S);
  840. break;
  841. }
  842. case ISD::LIFETIME_START:
  843. case ISD::LIFETIME_END: {
  844. unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ?
  845. TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END;
  846. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1));
  847. BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
  848. .addFrameIndex(FI->getIndex());
  849. break;
  850. }
  851. case ISD::INLINEASM: {
  852. unsigned NumOps = Node->getNumOperands();
  853. if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
  854. --NumOps; // Ignore the glue operand.
  855. // Create the inline asm machine instruction.
  856. MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(),
  857. TII->get(TargetOpcode::INLINEASM));
  858. // Add the asm string as an external symbol operand.
  859. SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
  860. const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
  861. MIB.addExternalSymbol(AsmStr);
  862. // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
  863. // bits.
  864. int64_t ExtraInfo =
  865. cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
  866. getZExtValue();
  867. MIB.addImm(ExtraInfo);
  868. // Remember to operand index of the group flags.
  869. SmallVector<unsigned, 8> GroupIdx;
  870. // Remember registers that are part of early-clobber defs.
  871. SmallVector<unsigned, 8> ECRegs;
  872. // Add all of the operand registers to the instruction.
  873. for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
  874. unsigned Flags =
  875. cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
  876. const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
  877. GroupIdx.push_back(MIB->getNumOperands());
  878. MIB.addImm(Flags);
  879. ++i; // Skip the ID value.
  880. switch (InlineAsm::getKind(Flags)) {
  881. default: llvm_unreachable("Bad flags!");
  882. case InlineAsm::Kind_RegDef:
  883. for (unsigned j = 0; j != NumVals; ++j, ++i) {
  884. unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
  885. // FIXME: Add dead flags for physical and virtual registers defined.
  886. // For now, mark physical register defs as implicit to help fast
  887. // regalloc. This makes inline asm look a lot like calls.
  888. MIB.addReg(Reg, RegState::Define |
  889. getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
  890. }
  891. break;
  892. case InlineAsm::Kind_RegDefEarlyClobber:
  893. case InlineAsm::Kind_Clobber:
  894. for (unsigned j = 0; j != NumVals; ++j, ++i) {
  895. unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
  896. MIB.addReg(Reg, RegState::Define | RegState::EarlyClobber |
  897. getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
  898. ECRegs.push_back(Reg);
  899. }
  900. break;
  901. case InlineAsm::Kind_RegUse: // Use of register.
  902. case InlineAsm::Kind_Imm: // Immediate.
  903. case InlineAsm::Kind_Mem: // Addressing mode.
  904. // The addressing mode has been selected, just add all of the
  905. // operands to the machine instruction.
  906. for (unsigned j = 0; j != NumVals; ++j, ++i)
  907. AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap,
  908. /*IsDebug=*/false, IsClone, IsCloned);
  909. // Manually set isTied bits.
  910. if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
  911. unsigned DefGroup = 0;
  912. if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
  913. unsigned DefIdx = GroupIdx[DefGroup] + 1;
  914. unsigned UseIdx = GroupIdx.back() + 1;
  915. for (unsigned j = 0; j != NumVals; ++j)
  916. MIB->tieOperands(DefIdx + j, UseIdx + j);
  917. }
  918. }
  919. break;
  920. }
  921. }
  922. // GCC inline assembly allows input operands to also be early-clobber
  923. // output operands (so long as the operand is written only after it's
  924. // used), but this does not match the semantics of our early-clobber flag.
  925. // If an early-clobber operand register is also an input operand register,
  926. // then remove the early-clobber flag.
  927. for (unsigned Reg : ECRegs) {
  928. if (MIB->readsRegister(Reg, TRI)) {
  929. MachineOperand *MO = MIB->findRegisterDefOperand(Reg, false, TRI);
  930. assert(MO && "No def operand for clobbered register?");
  931. MO->setIsEarlyClobber(false);
  932. }
  933. }
  934. // Get the mdnode from the asm if it exists and add it to the instruction.
  935. SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
  936. const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
  937. if (MD)
  938. MIB.addMetadata(MD);
  939. MBB->insert(InsertPos, MIB);
  940. break;
  941. }
  942. }
  943. }
  944. /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
  945. /// at the given position in the given block.
  946. InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
  947. MachineBasicBlock::iterator insertpos)
  948. : MF(mbb->getParent()), MRI(&MF->getRegInfo()),
  949. TII(MF->getSubtarget().getInstrInfo()),
  950. TRI(MF->getSubtarget().getRegisterInfo()),
  951. TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb),
  952. InsertPos(insertpos) {}