1 //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the Emit routines for the SelectionDAG class, which creates
11 // MachineInstrs based on the decisions of the SelectionDAG instruction
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "instr-emitter"
17 #include "InstrEmitter.h"
18 #include "SDNodeDbgValue.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/DataLayout.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
33 /// MinRCSize - Smallest register class we allow when constraining virtual
34 /// registers. If satisfying all register class constraints would require
35 /// using a smaller register class, emit a COPY to a new virtual register
37 const unsigned MinRCSize = 4;
39 /// CountResults - The results of target nodes have register or immediate
40 /// operands first, then an optional chain, and optional glue operands (which do
41 /// not go into the resulting MachineInstr).
42 unsigned InstrEmitter::CountResults(SDNode *Node) {
43 unsigned N = Node->getNumValues();
44 while (N && Node->getValueType(N - 1) == MVT::Glue)
46 if (N && Node->getValueType(N - 1) == MVT::Other)
47 --N; // Skip over chain result.
51 /// countOperands - The inputs to target nodes have any actual inputs first,
52 /// followed by an optional chain operand, then an optional glue operand.
53 /// Compute the number of actual operands that will go into the resulting
56 /// Also count physreg RegisterSDNode and RegisterMaskSDNode operands preceding
57 /// the chain and glue. These operands may be implicit on the machine instr.
58 static unsigned countOperands(SDNode *Node, unsigned NumExpUses,
59 unsigned &NumImpUses) {
60 unsigned N = Node->getNumOperands();
61 while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
63 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
64 --N; // Ignore chain if it exists.
66 // Count RegisterSDNode and RegisterMaskSDNode operands for NumImpUses.
67 NumImpUses = N - NumExpUses;
68 for (unsigned I = N; I > NumExpUses; --I) {
69 if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1)))
71 if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1)))
72 if (TargetRegisterInfo::isPhysicalRegister(RN->getReg()))
81 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
82 /// implicit physical register output.
84 EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
85 unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
87 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
88 // Just use the input register directly!
89 SDValue Op(Node, ResNo);
92 bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
93 (void)isNew; // Silence compiler warning.
94 assert(isNew && "Node emitted out of order - early");
98 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
99 // the CopyToReg'd destination register instead of creating a new vreg.
100 bool MatchReg = true;
101 const TargetRegisterClass *UseRC = NULL;
102 MVT VT = Node->getSimpleValueType(ResNo);
104 // Stick to the preferred register classes for legal types.
105 if (TLI->isTypeLegal(VT))
106 UseRC = TLI->getRegClassFor(VT);
108 if (!IsClone && !IsCloned)
109 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
113 if (User->getOpcode() == ISD::CopyToReg &&
114 User->getOperand(2).getNode() == Node &&
115 User->getOperand(2).getResNo() == ResNo) {
116 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
117 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
120 } else if (DestReg != SrcReg)
123 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
124 SDValue Op = User->getOperand(i);
125 if (Op.getNode() != Node || Op.getResNo() != ResNo)
127 EVT VT = Node->getValueType(Op.getResNo());
128 if (VT == MVT::Other || VT == MVT::Glue)
131 if (User->isMachineOpcode()) {
132 const MCInstrDesc &II = TII->get(User->getMachineOpcode());
133 const TargetRegisterClass *RC = 0;
134 if (i+II.getNumDefs() < II.getNumOperands()) {
135 RC = TRI->getAllocatableClass(
136 TII->getRegClass(II, i+II.getNumDefs(), TRI, *MF));
141 const TargetRegisterClass *ComRC =
142 TRI->getCommonSubClass(UseRC, RC);
143 // If multiple uses expect disjoint register classes, we emit
144 // copies in AddRegisterOperand.
156 const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
157 SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
159 // Figure out the register class to create for the destreg.
161 DstRC = MRI->getRegClass(VRBase);
163 assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
166 DstRC = TLI->getRegClassFor(VT);
169 // If all uses are reading from the src physical register and copying the
170 // register is either impossible or very expensive, then don't create a copy.
171 if (MatchReg && SrcRC->getCopyCost() < 0) {
174 // Create the reg, emit the copy.
175 VRBase = MRI->createVirtualRegister(DstRC);
176 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
177 VRBase).addReg(SrcReg);
180 SDValue Op(Node, ResNo);
183 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
184 (void)isNew; // Silence compiler warning.
185 assert(isNew && "Node emitted out of order - early");
188 /// getDstOfCopyToRegUse - If the only use of the specified result number of
189 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
190 unsigned InstrEmitter::getDstOfOnlyCopyToRegUse(SDNode *Node,
191 unsigned ResNo) const {
192 if (!Node->hasOneUse())
195 SDNode *User = *Node->use_begin();
196 if (User->getOpcode() == ISD::CopyToReg &&
197 User->getOperand(2).getNode() == Node &&
198 User->getOperand(2).getResNo() == ResNo) {
199 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
200 if (TargetRegisterInfo::isVirtualRegister(Reg))
206 void InstrEmitter::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
207 const MCInstrDesc &II,
208 bool IsClone, bool IsCloned,
209 DenseMap<SDValue, unsigned> &VRBaseMap) {
210 assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
211 "IMPLICIT_DEF should have been handled as a special case elsewhere!");
213 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
214 // If the specific node value is only used by a CopyToReg and the dest reg
215 // is a vreg in the same register class, use the CopyToReg'd destination
216 // register instead of creating a new vreg.
218 const TargetRegisterClass *RC =
219 TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF));
220 if (II.OpInfo[i].isOptionalDef()) {
221 // Optional def must be a physical register.
222 unsigned NumResults = CountResults(Node);
223 VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
224 assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
225 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
228 if (!VRBase && !IsClone && !IsCloned)
229 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
232 if (User->getOpcode() == ISD::CopyToReg &&
233 User->getOperand(2).getNode() == Node &&
234 User->getOperand(2).getResNo() == i) {
235 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
236 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
237 const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
240 MI->addOperand(MachineOperand::CreateReg(Reg, true));
247 // Create the result registers for this node and add the result regs to
248 // the machine instruction.
250 assert(RC && "Isn't a register operand!");
251 VRBase = MRI->createVirtualRegister(RC);
252 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
258 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
259 (void)isNew; // Silence compiler warning.
260 assert(isNew && "Node emitted out of order - early");
264 /// getVR - Return the virtual register corresponding to the specified result
265 /// of the specified node.
266 unsigned InstrEmitter::getVR(SDValue Op,
267 DenseMap<SDValue, unsigned> &VRBaseMap) {
268 if (Op.isMachineOpcode() &&
269 Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
270 // Add an IMPLICIT_DEF instruction before every use.
271 unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
272 // IMPLICIT_DEF can produce any type of result so its MCInstrDesc
273 // does not include operand register class info.
275 const TargetRegisterClass *RC =
276 TLI->getRegClassFor(Op.getSimpleValueType());
277 VReg = MRI->createVirtualRegister(RC);
279 BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
280 TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
284 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
285 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
290 /// AddRegisterOperand - Add the specified register as an operand to the
291 /// specified machine instr. Insert register copies if the register is
292 /// not in the required register class.
294 InstrEmitter::AddRegisterOperand(MachineInstr *MI, SDValue Op,
296 const MCInstrDesc *II,
297 DenseMap<SDValue, unsigned> &VRBaseMap,
298 bool IsDebug, bool IsClone, bool IsCloned) {
299 assert(Op.getValueType() != MVT::Other &&
300 Op.getValueType() != MVT::Glue &&
301 "Chain and glue operands should occur at end of operand list!");
302 // Get/emit the operand.
303 unsigned VReg = getVR(Op, VRBaseMap);
304 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
306 const MCInstrDesc &MCID = MI->getDesc();
307 bool isOptDef = IIOpNum < MCID.getNumOperands() &&
308 MCID.OpInfo[IIOpNum].isOptionalDef();
310 // If the instruction requires a register in a different class, create
311 // a new virtual register and copy the value into it, but first attempt to
312 // shrink VReg's register class within reason. For example, if VReg == GR32
313 // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
315 const TargetRegisterClass *DstRC = 0;
316 if (IIOpNum < II->getNumOperands())
317 DstRC = TRI->getAllocatableClass(TII->getRegClass(*II,IIOpNum,TRI,*MF));
318 if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
319 unsigned NewVReg = MRI->createVirtualRegister(DstRC);
320 BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
321 TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
326 // If this value has only one use, that use is a kill. This is a
327 // conservative approximation. InstrEmitter does trivial coalescing
328 // with CopyFromReg nodes, so don't emit kill flags for them.
329 // Avoid kill flags on Schedule cloned nodes, since there will be
331 // Tied operands are never killed, so we need to check that. And that
332 // means we need to determine the index of the operand.
333 bool isKill = Op.hasOneUse() &&
334 Op.getNode()->getOpcode() != ISD::CopyFromReg &&
336 !(IsClone || IsCloned);
338 unsigned Idx = MI->getNumOperands();
340 MI->getOperand(Idx-1).isReg() && MI->getOperand(Idx-1).isImplicit())
342 bool isTied = MI->getDesc().getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
347 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef,
348 false/*isImp*/, isKill,
349 false/*isDead*/, false/*isUndef*/,
350 false/*isEarlyClobber*/,
351 0/*SubReg*/, IsDebug));
354 /// AddOperand - Add the specified operand to the specified machine instr. II
355 /// specifies the instruction information for the node, and IIOpNum is the
356 /// operand number (in the II) that we are adding.
357 void InstrEmitter::AddOperand(MachineInstr *MI, SDValue Op,
359 const MCInstrDesc *II,
360 DenseMap<SDValue, unsigned> &VRBaseMap,
361 bool IsDebug, bool IsClone, bool IsCloned) {
362 if (Op.isMachineOpcode()) {
363 AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap,
364 IsDebug, IsClone, IsCloned);
365 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
366 MI->addOperand(MachineOperand::CreateImm(C->getSExtValue()));
367 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
368 const ConstantFP *CFP = F->getConstantFPValue();
369 MI->addOperand(MachineOperand::CreateFPImm(CFP));
370 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
371 // Turn additional physreg operands into implicit uses on non-variadic
372 // instructions. This is used by call and return instructions passing
373 // arguments in registers.
374 bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic());
375 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false, Imp));
376 } else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
377 MI->addOperand(MachineOperand::CreateRegMask(RM->getRegMask()));
378 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
379 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(), TGA->getOffset(),
380 TGA->getTargetFlags()));
381 } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
382 MI->addOperand(MachineOperand::CreateMBB(BBNode->getBasicBlock()));
383 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
384 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
385 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
386 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex(),
387 JT->getTargetFlags()));
388 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
389 int Offset = CP->getOffset();
390 unsigned Align = CP->getAlignment();
391 Type *Type = CP->getType();
392 // MachineConstantPool wants an explicit alignment.
394 Align = TM->getDataLayout()->getPrefTypeAlignment(Type);
396 // Alignment of vector types. FIXME!
397 Align = TM->getDataLayout()->getTypeAllocSize(Type);
402 MachineConstantPool *MCP = MF->getConstantPool();
403 if (CP->isMachineConstantPoolEntry())
404 Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
406 Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
407 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset,
408 CP->getTargetFlags()));
409 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
410 MI->addOperand(MachineOperand::CreateES(ES->getSymbol(),
411 ES->getTargetFlags()));
412 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
413 MI->addOperand(MachineOperand::CreateBA(BA->getBlockAddress(),
415 BA->getTargetFlags()));
416 } else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
417 MI->addOperand(MachineOperand::CreateTargetIndex(TI->getIndex(),
419 TI->getTargetFlags()));
421 assert(Op.getValueType() != MVT::Other &&
422 Op.getValueType() != MVT::Glue &&
423 "Chain and glue operands should occur at end of operand list!");
424 AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap,
425 IsDebug, IsClone, IsCloned);
429 unsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
430 MVT VT, DebugLoc DL) {
431 const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
432 const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
434 // RC is a sub-class of VRC that supports SubIdx. Try to constrain VReg
437 RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
439 // VReg has been adjusted. It can be used with SubIdx operands now.
443 // VReg couldn't be reasonably constrained. Emit a COPY to a new virtual
445 RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
446 assert(RC && "No legal register class for VT supports that SubIdx");
447 unsigned NewReg = MRI->createVirtualRegister(RC);
448 BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
453 /// EmitSubregNode - Generate machine code for subreg nodes.
455 void InstrEmitter::EmitSubregNode(SDNode *Node,
456 DenseMap<SDValue, unsigned> &VRBaseMap,
457 bool IsClone, bool IsCloned) {
459 unsigned Opc = Node->getMachineOpcode();
461 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
462 // the CopyToReg'd destination register instead of creating a new vreg.
463 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
466 if (User->getOpcode() == ISD::CopyToReg &&
467 User->getOperand(2).getNode() == Node) {
468 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
469 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
476 if (Opc == TargetOpcode::EXTRACT_SUBREG) {
477 // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub. There are no
478 // constraints on the %dst register, COPY can target all legal register
480 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
481 const TargetRegisterClass *TRC =
482 TLI->getRegClassFor(Node->getSimpleValueType(0));
484 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
485 MachineInstr *DefMI = MRI->getVRegDef(VReg);
486 unsigned SrcReg, DstReg, DefSubIdx;
488 TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
489 SubIdx == DefSubIdx &&
490 TRC == MRI->getRegClass(SrcReg)) {
492 // r1025 = s/zext r1024, 4
493 // r1026 = extract_subreg r1025, 4
495 // r1026 = copy r1024
496 VRBase = MRI->createVirtualRegister(TRC);
497 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
498 TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
499 MRI->clearKillFlags(SrcReg);
501 // VReg may not support a SubIdx sub-register, and we may need to
502 // constrain its register class or issue a COPY to a compatible register
504 VReg = ConstrainForSubReg(VReg, SubIdx,
505 Node->getOperand(0).getSimpleValueType(),
506 Node->getDebugLoc());
508 // Create the destreg if it is missing.
510 VRBase = MRI->createVirtualRegister(TRC);
512 // Create the extract_subreg machine instruction.
513 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
514 TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
516 } else if (Opc == TargetOpcode::INSERT_SUBREG ||
517 Opc == TargetOpcode::SUBREG_TO_REG) {
518 SDValue N0 = Node->getOperand(0);
519 SDValue N1 = Node->getOperand(1);
520 SDValue N2 = Node->getOperand(2);
521 unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
523 // Figure out the register class to create for the destreg. It should be
524 // the largest legal register class supporting SubIdx sub-registers.
525 // RegisterCoalescer will constrain it further if it decides to eliminate
526 // the INSERT_SUBREG instruction.
528 // %dst = INSERT_SUBREG %src, %sub, SubIdx
530 // is lowered by TwoAddressInstructionPass to:
533 // %dst:SubIdx = COPY %sub
535 // There is no constraint on the %src register class.
537 const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getSimpleValueType(0));
538 SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
539 assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
541 if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
542 VRBase = MRI->createVirtualRegister(SRC);
544 // Create the insert_subreg or subreg_to_reg machine instruction.
545 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc));
546 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
548 // If creating a subreg_to_reg, then the first input operand
549 // is an implicit value immediate, otherwise it's a register
550 if (Opc == TargetOpcode::SUBREG_TO_REG) {
551 const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
552 MI->addOperand(MachineOperand::CreateImm(SD->getZExtValue()));
554 AddOperand(MI, N0, 0, 0, VRBaseMap, /*IsDebug=*/false,
556 // Add the subregster being inserted
557 AddOperand(MI, N1, 0, 0, VRBaseMap, /*IsDebug=*/false,
559 MI->addOperand(MachineOperand::CreateImm(SubIdx));
560 MBB->insert(InsertPos, MI);
562 llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
565 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
566 (void)isNew; // Silence compiler warning.
567 assert(isNew && "Node emitted out of order - early");
570 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
571 /// COPY_TO_REGCLASS is just a normal copy, except that the destination
572 /// register is constrained to be in a particular register class.
575 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
576 DenseMap<SDValue, unsigned> &VRBaseMap) {
577 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
579 // Create the new VReg in the destination class and emit a copy.
580 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
581 const TargetRegisterClass *DstRC =
582 TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx));
583 unsigned NewVReg = MRI->createVirtualRegister(DstRC);
584 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
585 NewVReg).addReg(VReg);
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");
593 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
595 void InstrEmitter::EmitRegSequence(SDNode *Node,
596 DenseMap<SDValue, unsigned> &VRBaseMap,
597 bool IsClone, bool IsCloned) {
598 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
599 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
600 unsigned NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC));
601 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
602 TII->get(TargetOpcode::REG_SEQUENCE), NewVReg);
603 unsigned NumOps = Node->getNumOperands();
604 assert((NumOps & 1) == 1 &&
605 "REG_SEQUENCE must have an odd number of operands!");
606 const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
607 for (unsigned i = 1; i != NumOps; ++i) {
608 SDValue Op = Node->getOperand(i);
610 RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
611 // Skip physical registers as they don't have a vreg to get and we'll
612 // insert copies for them in TwoAddressInstructionPass anyway.
613 if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
614 unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
615 unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
616 const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
617 const TargetRegisterClass *SRC =
618 TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
619 if (SRC && SRC != RC) {
620 MRI->setRegClass(NewVReg, SRC);
625 AddOperand(MI, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
629 MBB->insert(InsertPos, MI);
631 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
632 (void)isNew; // Silence compiler warning.
633 assert(isNew && "Node emitted out of order - early");
636 /// EmitDbgValue - Generate machine instruction for a dbg_value node.
639 InstrEmitter::EmitDbgValue(SDDbgValue *SD,
640 DenseMap<SDValue, unsigned> &VRBaseMap) {
641 uint64_t Offset = SD->getOffset();
642 MDNode* MDPtr = SD->getMDPtr();
643 DebugLoc DL = SD->getDebugLoc();
645 if (SD->getKind() == SDDbgValue::FRAMEIX) {
646 // Stack address; this needs to be lowered in target-dependent fashion.
647 // EmitTargetCodeForFrameDebugValue is responsible for allocation.
648 unsigned FrameIx = SD->getFrameIx();
649 return TII->emitFrameIndexDebugValue(*MF, FrameIx, Offset, MDPtr, DL);
651 // Otherwise, we're going to create an instruction here.
652 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
653 MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
654 if (SD->getKind() == SDDbgValue::SDNODE) {
655 SDNode *Node = SD->getSDNode();
656 SDValue Op = SDValue(Node, SD->getResNo());
657 // It's possible we replaced this SDNode with other(s) and therefore
658 // didn't generate code for it. It's better to catch these cases where
659 // they happen and transfer the debug info, but trying to guarantee that
660 // in all cases would be very fragile; this is a safeguard for any
662 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
663 if (I==VRBaseMap.end())
664 MIB.addReg(0U); // undef
666 AddOperand(&*MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
667 /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
668 } else if (SD->getKind() == SDDbgValue::CONST) {
669 const Value *V = SD->getConst();
670 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
671 if (CI->getBitWidth() > 64)
674 MIB.addImm(CI->getSExtValue());
675 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
678 // Could be an Undef. In any case insert an Undef so we can see what we
683 // Insert an Undef so we can see what we dropped.
687 MIB.addImm(Offset).addMetadata(MDPtr);
691 /// EmitMachineNode - Generate machine code for a target-specific node and
692 /// needed dependencies.
695 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
696 DenseMap<SDValue, unsigned> &VRBaseMap) {
697 unsigned Opc = Node->getMachineOpcode();
699 // Handle subreg insert/extract specially
700 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
701 Opc == TargetOpcode::INSERT_SUBREG ||
702 Opc == TargetOpcode::SUBREG_TO_REG) {
703 EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
707 // Handle COPY_TO_REGCLASS specially.
708 if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
709 EmitCopyToRegClassNode(Node, VRBaseMap);
713 // Handle REG_SEQUENCE specially.
714 if (Opc == TargetOpcode::REG_SEQUENCE) {
715 EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
719 if (Opc == TargetOpcode::IMPLICIT_DEF)
720 // We want a unique VR for each IMPLICIT_DEF use.
723 const MCInstrDesc &II = TII->get(Opc);
724 unsigned NumResults = CountResults(Node);
725 unsigned NumImpUses = 0;
726 unsigned NodeOperands =
727 countOperands(Node, II.getNumOperands() - II.getNumDefs(), NumImpUses);
728 bool HasPhysRegOuts = NumResults > II.getNumDefs() && II.getImplicitDefs()!=0;
730 unsigned NumMIOperands = NodeOperands + NumResults;
732 assert(NumMIOperands >= II.getNumOperands() &&
733 "Too few operands for a variadic node!");
735 assert(NumMIOperands >= II.getNumOperands() &&
736 NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
738 "#operands for dag node doesn't match .td file!");
741 // Create the new machine instruction.
742 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), II);
744 // Add result register values for things that are defined by this
747 CreateVirtualRegisters(Node, MI, II, IsClone, IsCloned, VRBaseMap);
749 // Emit all of the actual operands of this instruction, adding them to the
750 // instruction as appropriate.
751 bool HasOptPRefs = II.getNumDefs() > NumResults;
752 assert((!HasOptPRefs || !HasPhysRegOuts) &&
753 "Unable to cope with optional defs and phys regs defs!");
754 unsigned NumSkip = HasOptPRefs ? II.getNumDefs() - NumResults : 0;
755 for (unsigned i = NumSkip; i != NodeOperands; ++i)
756 AddOperand(MI, Node->getOperand(i), i-NumSkip+II.getNumDefs(), &II,
757 VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
759 // Transfer all of the memory reference descriptions of this instruction.
760 MI->setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
761 cast<MachineSDNode>(Node)->memoperands_end());
763 // Insert the instruction into position in the block. This needs to
764 // happen before any custom inserter hook is called so that the
765 // hook knows where in the block to insert the replacement code.
766 MBB->insert(InsertPos, MI);
768 // The MachineInstr may also define physregs instead of virtregs. These
769 // physreg values can reach other instructions in different ways:
771 // 1. When there is a use of a Node value beyond the explicitly defined
772 // virtual registers, we emit a CopyFromReg for one of the implicitly
773 // defined physregs. This only happens when HasPhysRegOuts is true.
775 // 2. A CopyFromReg reading a physreg may be glued to this instruction.
777 // 3. A glued instruction may implicitly use a physreg.
779 // 4. A glued instruction may use a RegisterSDNode operand.
781 // Collect all the used physreg defs, and make sure that any unused physreg
782 // defs are marked as dead.
783 SmallVector<unsigned, 8> UsedRegs;
785 // Additional results must be physical register defs.
786 if (HasPhysRegOuts) {
787 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
788 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
789 if (!Node->hasAnyUseOfValue(i))
791 // This implicitly defined physreg has a use.
792 UsedRegs.push_back(Reg);
793 EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
797 // Scan the glue chain for any used physregs.
798 if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
799 for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
800 if (F->getOpcode() == ISD::CopyFromReg) {
801 UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
803 } else if (F->getOpcode() == ISD::CopyToReg) {
804 // Skip CopyToReg nodes that are internal to the glue chain.
807 // Collect declared implicit uses.
808 const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
809 UsedRegs.append(MCID.getImplicitUses(),
810 MCID.getImplicitUses() + MCID.getNumImplicitUses());
811 // In addition to declared implicit uses, we must also check for
812 // direct RegisterSDNode operands.
813 for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
814 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
815 unsigned Reg = R->getReg();
816 if (TargetRegisterInfo::isPhysicalRegister(Reg))
817 UsedRegs.push_back(Reg);
822 // Finally mark unused registers as dead.
823 if (!UsedRegs.empty() || II.getImplicitDefs())
824 MI->setPhysRegsDeadExcept(UsedRegs, *TRI);
826 // Run post-isel target hook to adjust this instruction if needed.
828 if (II.hasPostISelHook())
830 TLI->AdjustInstrPostInstrSelection(MI, Node);
833 /// EmitSpecialNode - Generate machine code for a target-independent node and
834 /// needed dependencies.
836 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
837 DenseMap<SDValue, unsigned> &VRBaseMap) {
838 switch (Node->getOpcode()) {
843 llvm_unreachable("This target-independent node should have been selected!");
844 case ISD::EntryToken:
845 llvm_unreachable("EntryToken should have been excluded from the schedule!");
846 case ISD::MERGE_VALUES:
847 case ISD::TokenFactor: // fall thru
849 case ISD::CopyToReg: {
851 SDValue SrcVal = Node->getOperand(2);
852 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
853 SrcReg = R->getReg();
855 SrcReg = getVR(SrcVal, VRBaseMap);
857 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
858 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
861 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
862 DestReg).addReg(SrcReg);
865 case ISD::CopyFromReg: {
866 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
867 EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
870 case ISD::EH_LABEL: {
871 MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
872 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
873 TII->get(TargetOpcode::EH_LABEL)).addSym(S);
877 case ISD::LIFETIME_START:
878 case ISD::LIFETIME_END: {
879 unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ?
880 TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END;
882 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1));
883 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
884 .addFrameIndex(FI->getIndex());
888 case ISD::INLINEASM: {
889 unsigned NumOps = Node->getNumOperands();
890 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
891 --NumOps; // Ignore the glue operand.
893 // Create the inline asm machine instruction.
894 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
895 TII->get(TargetOpcode::INLINEASM));
897 // Add the asm string as an external symbol operand.
898 SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
899 const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
900 MI->addOperand(MachineOperand::CreateES(AsmStr));
902 // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
905 cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
907 MI->addOperand(MachineOperand::CreateImm(ExtraInfo));
909 // Remember to operand index of the group flags.
910 SmallVector<unsigned, 8> GroupIdx;
912 // Add all of the operand registers to the instruction.
913 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
915 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
916 const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
918 GroupIdx.push_back(MI->getNumOperands());
919 MI->addOperand(MachineOperand::CreateImm(Flags));
920 ++i; // Skip the ID value.
922 switch (InlineAsm::getKind(Flags)) {
923 default: llvm_unreachable("Bad flags!");
924 case InlineAsm::Kind_RegDef:
925 for (unsigned j = 0; j != NumVals; ++j, ++i) {
926 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
927 // FIXME: Add dead flags for physical and virtual registers defined.
928 // For now, mark physical register defs as implicit to help fast
929 // regalloc. This makes inline asm look a lot like calls.
930 MI->addOperand(MachineOperand::CreateReg(Reg, true,
931 /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg)));
934 case InlineAsm::Kind_RegDefEarlyClobber:
935 case InlineAsm::Kind_Clobber:
936 for (unsigned j = 0; j != NumVals; ++j, ++i) {
937 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
938 MI->addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/ true,
939 /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg),
943 /*isEarlyClobber=*/ true));
946 case InlineAsm::Kind_RegUse: // Use of register.
947 case InlineAsm::Kind_Imm: // Immediate.
948 case InlineAsm::Kind_Mem: // Addressing mode.
949 // The addressing mode has been selected, just add all of the
950 // operands to the machine instruction.
951 for (unsigned j = 0; j != NumVals; ++j, ++i)
952 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap,
953 /*IsDebug=*/false, IsClone, IsCloned);
955 // Manually set isTied bits.
956 if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
957 unsigned DefGroup = 0;
958 if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
959 unsigned DefIdx = GroupIdx[DefGroup] + 1;
960 unsigned UseIdx = GroupIdx.back() + 1;
961 for (unsigned j = 0; j != NumVals; ++j)
962 MI->tieOperands(DefIdx + j, UseIdx + j);
969 // Get the mdnode from the asm if it exists and add it to the instruction.
970 SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
971 const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
973 MI->addOperand(MachineOperand::CreateMetadata(MD));
975 MBB->insert(InsertPos, MI);
981 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
982 /// at the given position in the given block.
983 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
984 MachineBasicBlock::iterator insertpos)
985 : MF(mbb->getParent()),
986 MRI(&MF->getRegInfo()),
987 TM(&MF->getTarget()),
988 TII(TM->getInstrInfo()),
989 TRI(TM->getRegisterInfo()),
990 TLI(TM->getTargetLowering()),
991 MBB(mbb), InsertPos(insertpos) {