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/IR/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 MVT VT = Node->getSimpleValueType(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,
207 MachineInstrBuilder &MIB,
208 const MCInstrDesc &II,
209 bool IsClone, bool IsCloned,
210 DenseMap<SDValue, unsigned> &VRBaseMap) {
211 assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
212 "IMPLICIT_DEF should have been handled as a special case elsewhere!");
214 unsigned NumResults = CountResults(Node);
215 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
216 // If the specific node value is only used by a CopyToReg and the dest reg
217 // is a vreg in the same register class, use the CopyToReg'd destination
218 // register instead of creating a new vreg.
220 const TargetRegisterClass *RC =
221 TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF));
222 // If the register class is unknown for the given definition, then try to
223 // infer one from the value type.
224 if (!RC && i < NumResults)
225 RC = TLI->getRegClassFor(Node->getSimpleValueType(i));
226 if (II.OpInfo[i].isOptionalDef()) {
227 // Optional def must be a physical register.
228 unsigned NumResults = CountResults(Node);
229 VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
230 assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
231 MIB.addReg(VRBase, RegState::Define);
234 if (!VRBase && !IsClone && !IsCloned)
235 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
238 if (User->getOpcode() == ISD::CopyToReg &&
239 User->getOperand(2).getNode() == Node &&
240 User->getOperand(2).getResNo() == i) {
241 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
242 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
243 const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
246 MIB.addReg(VRBase, RegState::Define);
253 // Create the result registers for this node and add the result regs to
254 // the machine instruction.
256 assert(RC && "Isn't a register operand!");
257 VRBase = MRI->createVirtualRegister(RC);
258 MIB.addReg(VRBase, RegState::Define);
264 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
265 (void)isNew; // Silence compiler warning.
266 assert(isNew && "Node emitted out of order - early");
270 /// getVR - Return the virtual register corresponding to the specified result
271 /// of the specified node.
272 unsigned InstrEmitter::getVR(SDValue Op,
273 DenseMap<SDValue, unsigned> &VRBaseMap) {
274 if (Op.isMachineOpcode() &&
275 Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
276 // Add an IMPLICIT_DEF instruction before every use.
277 unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
278 // IMPLICIT_DEF can produce any type of result so its MCInstrDesc
279 // does not include operand register class info.
281 const TargetRegisterClass *RC =
282 TLI->getRegClassFor(Op.getSimpleValueType());
283 VReg = MRI->createVirtualRegister(RC);
285 BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
286 TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
290 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
291 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
296 /// AddRegisterOperand - Add the specified register as an operand to the
297 /// specified machine instr. Insert register copies if the register is
298 /// not in the required register class.
300 InstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB,
303 const MCInstrDesc *II,
304 DenseMap<SDValue, unsigned> &VRBaseMap,
305 bool IsDebug, bool IsClone, bool IsCloned) {
306 assert(Op.getValueType() != MVT::Other &&
307 Op.getValueType() != MVT::Glue &&
308 "Chain and glue operands should occur at end of operand list!");
309 // Get/emit the operand.
310 unsigned VReg = getVR(Op, VRBaseMap);
311 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
313 const MCInstrDesc &MCID = MIB->getDesc();
314 bool isOptDef = IIOpNum < MCID.getNumOperands() &&
315 MCID.OpInfo[IIOpNum].isOptionalDef();
317 // If the instruction requires a register in a different class, create
318 // a new virtual register and copy the value into it, but first attempt to
319 // shrink VReg's register class within reason. For example, if VReg == GR32
320 // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
322 const TargetRegisterClass *DstRC = 0;
323 if (IIOpNum < II->getNumOperands())
324 DstRC = TRI->getAllocatableClass(TII->getRegClass(*II,IIOpNum,TRI,*MF));
325 if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
326 unsigned NewVReg = MRI->createVirtualRegister(DstRC);
327 BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
328 TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
333 // If this value has only one use, that use is a kill. This is a
334 // conservative approximation. InstrEmitter does trivial coalescing
335 // with CopyFromReg nodes, so don't emit kill flags for them.
336 // Avoid kill flags on Schedule cloned nodes, since there will be
338 // Tied operands are never killed, so we need to check that. And that
339 // means we need to determine the index of the operand.
340 bool isKill = Op.hasOneUse() &&
341 Op.getNode()->getOpcode() != ISD::CopyFromReg &&
343 !(IsClone || IsCloned);
345 unsigned Idx = MIB->getNumOperands();
347 MIB->getOperand(Idx-1).isReg() &&
348 MIB->getOperand(Idx-1).isImplicit())
350 bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
355 MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) |
356 getDebugRegState(IsDebug));
359 /// AddOperand - Add the specified operand to the specified machine instr. II
360 /// specifies the instruction information for the node, and IIOpNum is the
361 /// operand number (in the II) that we are adding.
362 void InstrEmitter::AddOperand(MachineInstrBuilder &MIB,
365 const MCInstrDesc *II,
366 DenseMap<SDValue, unsigned> &VRBaseMap,
367 bool IsDebug, bool IsClone, bool IsCloned) {
368 if (Op.isMachineOpcode()) {
369 AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
370 IsDebug, IsClone, IsCloned);
371 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
372 MIB.addImm(C->getSExtValue());
373 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
374 MIB.addFPImm(F->getConstantFPValue());
375 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
376 // Turn additional physreg operands into implicit uses on non-variadic
377 // instructions. This is used by call and return instructions passing
378 // arguments in registers.
379 bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic());
380 MIB.addReg(R->getReg(), getImplRegState(Imp));
381 } else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
382 MIB.addRegMask(RM->getRegMask());
383 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
384 MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(),
385 TGA->getTargetFlags());
386 } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
387 MIB.addMBB(BBNode->getBasicBlock());
388 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
389 MIB.addFrameIndex(FI->getIndex());
390 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
391 MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags());
392 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
393 int Offset = CP->getOffset();
394 unsigned Align = CP->getAlignment();
395 Type *Type = CP->getType();
396 // MachineConstantPool wants an explicit alignment.
398 Align = TM->getDataLayout()->getPrefTypeAlignment(Type);
400 // Alignment of vector types. FIXME!
401 Align = TM->getDataLayout()->getTypeAllocSize(Type);
406 MachineConstantPool *MCP = MF->getConstantPool();
407 if (CP->isMachineConstantPoolEntry())
408 Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
410 Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
411 MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags());
412 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
413 MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags());
414 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
415 MIB.addBlockAddress(BA->getBlockAddress(),
417 BA->getTargetFlags());
418 } else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
419 MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), 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(MIB, 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 MachineInstrBuilder MIB =
546 BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
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 MIB.addImm(SD->getZExtValue());
554 AddOperand(MIB, N0, 0, 0, VRBaseMap, /*IsDebug=*/false,
556 // Add the subregster being inserted
557 AddOperand(MIB, N1, 0, 0, VRBaseMap, /*IsDebug=*/false,
560 MBB->insert(InsertPos, MIB);
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 const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
602 MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg);
603 unsigned NumOps = Node->getNumOperands();
604 assert((NumOps & 1) == 1 &&
605 "REG_SEQUENCE must have an odd number of operands!");
606 for (unsigned i = 1; i != NumOps; ++i) {
607 SDValue Op = Node->getOperand(i);
609 RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
610 // Skip physical registers as they don't have a vreg to get and we'll
611 // insert copies for them in TwoAddressInstructionPass anyway.
612 if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
613 unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
614 unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
615 const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
616 const TargetRegisterClass *SRC =
617 TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
618 if (SRC && SRC != RC) {
619 MRI->setRegClass(NewVReg, SRC);
624 AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
628 MBB->insert(InsertPos, MIB);
630 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
631 (void)isNew; // Silence compiler warning.
632 assert(isNew && "Node emitted out of order - early");
635 /// EmitDbgValue - Generate machine instruction for a dbg_value node.
638 InstrEmitter::EmitDbgValue(SDDbgValue *SD,
639 DenseMap<SDValue, unsigned> &VRBaseMap) {
640 uint64_t Offset = SD->getOffset();
641 MDNode* MDPtr = SD->getMDPtr();
642 DebugLoc DL = SD->getDebugLoc();
644 if (SD->getKind() == SDDbgValue::FRAMEIX) {
645 // Stack address; this needs to be lowered in target-dependent fashion.
646 // EmitTargetCodeForFrameDebugValue is responsible for allocation.
647 return BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE))
648 .addFrameIndex(SD->getFrameIx()).addImm(Offset).addMetadata(MDPtr);
650 // Otherwise, we're going to create an instruction here.
651 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
652 MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
653 if (SD->getKind() == SDDbgValue::SDNODE) {
654 SDNode *Node = SD->getSDNode();
655 SDValue Op = SDValue(Node, SD->getResNo());
656 // It's possible we replaced this SDNode with other(s) and therefore
657 // didn't generate code for it. It's better to catch these cases where
658 // they happen and transfer the debug info, but trying to guarantee that
659 // in all cases would be very fragile; this is a safeguard for any
661 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
662 if (I==VRBaseMap.end())
663 MIB.addReg(0U); // undef
665 AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
666 /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
667 } else if (SD->getKind() == SDDbgValue::CONST) {
668 const Value *V = SD->getConst();
669 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
670 if (CI->getBitWidth() > 64)
673 MIB.addImm(CI->getSExtValue());
674 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
677 // Could be an Undef. In any case insert an Undef so we can see what we
682 // Insert an Undef so we can see what we dropped.
686 if (Offset != 0) // Indirect addressing.
689 MIB.addReg(0U, RegState::Debug);
691 MIB.addMetadata(MDPtr);
696 /// EmitMachineNode - Generate machine code for a target-specific node and
697 /// needed dependencies.
700 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
701 DenseMap<SDValue, unsigned> &VRBaseMap) {
702 unsigned Opc = Node->getMachineOpcode();
704 // Handle subreg insert/extract specially
705 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
706 Opc == TargetOpcode::INSERT_SUBREG ||
707 Opc == TargetOpcode::SUBREG_TO_REG) {
708 EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
712 // Handle COPY_TO_REGCLASS specially.
713 if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
714 EmitCopyToRegClassNode(Node, VRBaseMap);
718 // Handle REG_SEQUENCE specially.
719 if (Opc == TargetOpcode::REG_SEQUENCE) {
720 EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
724 if (Opc == TargetOpcode::IMPLICIT_DEF)
725 // We want a unique VR for each IMPLICIT_DEF use.
728 const MCInstrDesc &II = TII->get(Opc);
729 unsigned NumResults = CountResults(Node);
730 unsigned NumDefs = II.getNumDefs();
732 // Handle PATCHPOINT specially and then use the generic code.
733 if (Opc == TargetOpcode::PATCHPOINT)
734 NumDefs = NumResults;
736 unsigned NumImpUses = 0;
737 unsigned NodeOperands =
738 countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
739 bool HasPhysRegOuts = NumResults > NumDefs && II.getImplicitDefs()!=0;
741 unsigned NumMIOperands = NodeOperands + NumResults;
743 assert(NumMIOperands >= II.getNumOperands() &&
744 "Too few operands for a variadic node!");
746 assert(NumMIOperands >= II.getNumOperands() &&
747 NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
749 "#operands for dag node doesn't match .td file!");
752 // Create the new machine instruction.
753 MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
755 // Add result register values for things that are defined by this
758 CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
760 // Emit all of the actual operands of this instruction, adding them to the
761 // instruction as appropriate.
762 bool HasOptPRefs = NumDefs > NumResults;
763 assert((!HasOptPRefs || !HasPhysRegOuts) &&
764 "Unable to cope with optional defs and phys regs defs!");
765 unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0;
766 for (unsigned i = NumSkip; i != NodeOperands; ++i)
767 AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II,
768 VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
770 // Transfer all of the memory reference descriptions of this instruction.
771 MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
772 cast<MachineSDNode>(Node)->memoperands_end());
774 // Insert the instruction into position in the block. This needs to
775 // happen before any custom inserter hook is called so that the
776 // hook knows where in the block to insert the replacement code.
777 MBB->insert(InsertPos, MIB);
779 // The MachineInstr may also define physregs instead of virtregs. These
780 // physreg values can reach other instructions in different ways:
782 // 1. When there is a use of a Node value beyond the explicitly defined
783 // virtual registers, we emit a CopyFromReg for one of the implicitly
784 // defined physregs. This only happens when HasPhysRegOuts is true.
786 // 2. A CopyFromReg reading a physreg may be glued to this instruction.
788 // 3. A glued instruction may implicitly use a physreg.
790 // 4. A glued instruction may use a RegisterSDNode operand.
792 // Collect all the used physreg defs, and make sure that any unused physreg
793 // defs are marked as dead.
794 SmallVector<unsigned, 8> UsedRegs;
796 // Additional results must be physical register defs.
797 if (HasPhysRegOuts) {
798 for (unsigned i = NumDefs; i < NumResults; ++i) {
799 unsigned Reg = II.getImplicitDefs()[i - NumDefs];
800 if (!Node->hasAnyUseOfValue(i))
802 // This implicitly defined physreg has a use.
803 UsedRegs.push_back(Reg);
804 EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
808 // Scan the glue chain for any used physregs.
809 if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
810 for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
811 if (F->getOpcode() == ISD::CopyFromReg) {
812 UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
814 } else if (F->getOpcode() == ISD::CopyToReg) {
815 // Skip CopyToReg nodes that are internal to the glue chain.
818 // Collect declared implicit uses.
819 const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
820 UsedRegs.append(MCID.getImplicitUses(),
821 MCID.getImplicitUses() + MCID.getNumImplicitUses());
822 // In addition to declared implicit uses, we must also check for
823 // direct RegisterSDNode operands.
824 for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
825 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
826 unsigned Reg = R->getReg();
827 if (TargetRegisterInfo::isPhysicalRegister(Reg))
828 UsedRegs.push_back(Reg);
833 // Finally mark unused registers as dead.
834 if (!UsedRegs.empty() || II.getImplicitDefs())
835 MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
837 // Run post-isel target hook to adjust this instruction if needed.
839 if (II.hasPostISelHook())
841 TLI->AdjustInstrPostInstrSelection(MIB, Node);
844 /// EmitSpecialNode - Generate machine code for a target-independent node and
845 /// needed dependencies.
847 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
848 DenseMap<SDValue, unsigned> &VRBaseMap) {
849 switch (Node->getOpcode()) {
854 llvm_unreachable("This target-independent node should have been selected!");
855 case ISD::EntryToken:
856 llvm_unreachable("EntryToken should have been excluded from the schedule!");
857 case ISD::MERGE_VALUES:
858 case ISD::TokenFactor: // fall thru
860 case ISD::CopyToReg: {
862 SDValue SrcVal = Node->getOperand(2);
863 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
864 SrcReg = R->getReg();
866 SrcReg = getVR(SrcVal, VRBaseMap);
868 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
869 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
872 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
873 DestReg).addReg(SrcReg);
876 case ISD::CopyFromReg: {
877 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
878 EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
881 case ISD::EH_LABEL: {
882 MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
883 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
884 TII->get(TargetOpcode::EH_LABEL)).addSym(S);
888 case ISD::LIFETIME_START:
889 case ISD::LIFETIME_END: {
890 unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ?
891 TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END;
893 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1));
894 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
895 .addFrameIndex(FI->getIndex());
899 case ISD::INLINEASM: {
900 unsigned NumOps = Node->getNumOperands();
901 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
902 --NumOps; // Ignore the glue operand.
904 // Create the inline asm machine instruction.
905 MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(),
906 TII->get(TargetOpcode::INLINEASM));
908 // Add the asm string as an external symbol operand.
909 SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
910 const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
911 MIB.addExternalSymbol(AsmStr);
913 // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
916 cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
918 MIB.addImm(ExtraInfo);
920 // Remember to operand index of the group flags.
921 SmallVector<unsigned, 8> GroupIdx;
923 // Add all of the operand registers to the instruction.
924 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
926 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
927 const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
929 GroupIdx.push_back(MIB->getNumOperands());
931 ++i; // Skip the ID value.
933 switch (InlineAsm::getKind(Flags)) {
934 default: llvm_unreachable("Bad flags!");
935 case InlineAsm::Kind_RegDef:
936 for (unsigned j = 0; j != NumVals; ++j, ++i) {
937 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
938 // FIXME: Add dead flags for physical and virtual registers defined.
939 // For now, mark physical register defs as implicit to help fast
940 // regalloc. This makes inline asm look a lot like calls.
941 MIB.addReg(Reg, RegState::Define |
942 getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
945 case InlineAsm::Kind_RegDefEarlyClobber:
946 case InlineAsm::Kind_Clobber:
947 for (unsigned j = 0; j != NumVals; ++j, ++i) {
948 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
949 MIB.addReg(Reg, RegState::Define | RegState::EarlyClobber |
950 getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
953 case InlineAsm::Kind_RegUse: // Use of register.
954 case InlineAsm::Kind_Imm: // Immediate.
955 case InlineAsm::Kind_Mem: // Addressing mode.
956 // The addressing mode has been selected, just add all of the
957 // operands to the machine instruction.
958 for (unsigned j = 0; j != NumVals; ++j, ++i)
959 AddOperand(MIB, Node->getOperand(i), 0, 0, VRBaseMap,
960 /*IsDebug=*/false, IsClone, IsCloned);
962 // Manually set isTied bits.
963 if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
964 unsigned DefGroup = 0;
965 if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
966 unsigned DefIdx = GroupIdx[DefGroup] + 1;
967 unsigned UseIdx = GroupIdx.back() + 1;
968 for (unsigned j = 0; j != NumVals; ++j)
969 MIB->tieOperands(DefIdx + j, UseIdx + j);
976 // Get the mdnode from the asm if it exists and add it to the instruction.
977 SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
978 const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
982 MBB->insert(InsertPos, MIB);
988 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
989 /// at the given position in the given block.
990 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
991 MachineBasicBlock::iterator insertpos)
992 : MF(mbb->getParent()),
993 MRI(&MF->getRegInfo()),
994 TM(&MF->getTarget()),
995 TII(TM->getInstrInfo()),
996 TRI(TM->getRegisterInfo()),
997 TLI(TM->getTargetLowering()),
998 MBB(mbb), InsertPos(insertpos) {