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/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.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
55 unsigned InstrEmitter::CountOperands(SDNode *Node) {
56 unsigned N = Node->getNumOperands();
57 while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
59 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
60 --N; // Ignore chain if it exists.
64 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
65 /// implicit physical register output.
67 EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
68 unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
70 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
71 // Just use the input register directly!
72 SDValue Op(Node, ResNo);
75 bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
76 (void)isNew; // Silence compiler warning.
77 assert(isNew && "Node emitted out of order - early");
81 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
82 // the CopyToReg'd destination register instead of creating a new vreg.
84 const TargetRegisterClass *UseRC = NULL;
85 EVT VT = Node->getValueType(ResNo);
87 // Stick to the preferred register classes for legal types.
88 if (TLI->isTypeLegal(VT))
89 UseRC = TLI->getRegClassFor(VT);
91 if (!IsClone && !IsCloned)
92 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
96 if (User->getOpcode() == ISD::CopyToReg &&
97 User->getOperand(2).getNode() == Node &&
98 User->getOperand(2).getResNo() == ResNo) {
99 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
100 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
103 } else if (DestReg != SrcReg)
106 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
107 SDValue Op = User->getOperand(i);
108 if (Op.getNode() != Node || Op.getResNo() != ResNo)
110 EVT VT = Node->getValueType(Op.getResNo());
111 if (VT == MVT::Other || VT == MVT::Glue)
114 if (User->isMachineOpcode()) {
115 const MCInstrDesc &II = TII->get(User->getMachineOpcode());
116 const TargetRegisterClass *RC = 0;
117 if (i+II.getNumDefs() < II.getNumOperands())
118 RC = TII->getRegClass(II, i+II.getNumDefs(), TRI);
122 const TargetRegisterClass *ComRC =
123 TRI->getCommonSubClass(UseRC, RC);
124 // If multiple uses expect disjoint register classes, we emit
125 // copies in AddRegisterOperand.
137 const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
138 SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
140 // Figure out the register class to create for the destreg.
142 DstRC = MRI->getRegClass(VRBase);
144 assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
147 DstRC = TLI->getRegClassFor(VT);
150 // If all uses are reading from the src physical register and copying the
151 // register is either impossible or very expensive, then don't create a copy.
152 if (MatchReg && SrcRC->getCopyCost() < 0) {
155 // Create the reg, emit the copy.
156 VRBase = MRI->createVirtualRegister(DstRC);
157 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
158 VRBase).addReg(SrcReg);
161 SDValue Op(Node, ResNo);
164 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
165 (void)isNew; // Silence compiler warning.
166 assert(isNew && "Node emitted out of order - early");
169 /// getDstOfCopyToRegUse - If the only use of the specified result number of
170 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
171 unsigned InstrEmitter::getDstOfOnlyCopyToRegUse(SDNode *Node,
172 unsigned ResNo) const {
173 if (!Node->hasOneUse())
176 SDNode *User = *Node->use_begin();
177 if (User->getOpcode() == ISD::CopyToReg &&
178 User->getOperand(2).getNode() == Node &&
179 User->getOperand(2).getResNo() == ResNo) {
180 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
181 if (TargetRegisterInfo::isVirtualRegister(Reg))
187 void InstrEmitter::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
188 const MCInstrDesc &II,
189 bool IsClone, bool IsCloned,
190 DenseMap<SDValue, unsigned> &VRBaseMap) {
191 assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
192 "IMPLICIT_DEF should have been handled as a special case elsewhere!");
194 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
195 // If the specific node value is only used by a CopyToReg and the dest reg
196 // is a vreg in the same register class, use the CopyToReg'd destination
197 // register instead of creating a new vreg.
199 const TargetRegisterClass *RC = TII->getRegClass(II, i, TRI);
200 if (II.OpInfo[i].isOptionalDef()) {
201 // Optional def must be a physical register.
202 unsigned NumResults = CountResults(Node);
203 VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
204 assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
205 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
208 if (!VRBase && !IsClone && !IsCloned)
209 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
212 if (User->getOpcode() == ISD::CopyToReg &&
213 User->getOperand(2).getNode() == Node &&
214 User->getOperand(2).getResNo() == i) {
215 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
216 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
217 const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
220 MI->addOperand(MachineOperand::CreateReg(Reg, true));
227 // Create the result registers for this node and add the result regs to
228 // the machine instruction.
230 assert(RC && "Isn't a register operand!");
231 VRBase = MRI->createVirtualRegister(RC);
232 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
238 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
239 (void)isNew; // Silence compiler warning.
240 assert(isNew && "Node emitted out of order - early");
244 /// getVR - Return the virtual register corresponding to the specified result
245 /// of the specified node.
246 unsigned InstrEmitter::getVR(SDValue Op,
247 DenseMap<SDValue, unsigned> &VRBaseMap) {
248 if (Op.isMachineOpcode() &&
249 Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
250 // Add an IMPLICIT_DEF instruction before every use.
251 unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
252 // IMPLICIT_DEF can produce any type of result so its MCInstrDesc
253 // does not include operand register class info.
255 const TargetRegisterClass *RC = TLI->getRegClassFor(Op.getValueType());
256 VReg = MRI->createVirtualRegister(RC);
258 BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
259 TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
263 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
264 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
269 /// AddRegisterOperand - Add the specified register as an operand to the
270 /// specified machine instr. Insert register copies if the register is
271 /// not in the required register class.
273 InstrEmitter::AddRegisterOperand(MachineInstr *MI, SDValue Op,
275 const MCInstrDesc *II,
276 DenseMap<SDValue, unsigned> &VRBaseMap,
277 bool IsDebug, bool IsClone, bool IsCloned) {
278 assert(Op.getValueType() != MVT::Other &&
279 Op.getValueType() != MVT::Glue &&
280 "Chain and glue operands should occur at end of operand list!");
281 // Get/emit the operand.
282 unsigned VReg = getVR(Op, VRBaseMap);
283 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
285 const MCInstrDesc &MCID = MI->getDesc();
286 bool isOptDef = IIOpNum < MCID.getNumOperands() &&
287 MCID.OpInfo[IIOpNum].isOptionalDef();
289 // If the instruction requires a register in a different class, create
290 // a new virtual register and copy the value into it, but first attempt to
291 // shrink VReg's register class within reason. For example, if VReg == GR32
292 // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
294 const TargetRegisterClass *DstRC = 0;
295 if (IIOpNum < II->getNumOperands())
296 DstRC = TII->getRegClass(*II, IIOpNum, TRI);
297 assert((DstRC || (MI->isVariadic() && IIOpNum >= MCID.getNumOperands())) &&
298 "Don't have operand info for this instruction!");
299 if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
300 unsigned NewVReg = MRI->createVirtualRegister(DstRC);
301 BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
302 TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
307 // If this value has only one use, that use is a kill. This is a
308 // conservative approximation. InstrEmitter does trivial coalescing
309 // with CopyFromReg nodes, so don't emit kill flags for them.
310 // Avoid kill flags on Schedule cloned nodes, since there will be
312 // Tied operands are never killed, so we need to check that. And that
313 // means we need to determine the index of the operand.
314 bool isKill = Op.hasOneUse() &&
315 Op.getNode()->getOpcode() != ISD::CopyFromReg &&
317 !(IsClone || IsCloned);
319 unsigned Idx = MI->getNumOperands();
321 MI->getOperand(Idx-1).isReg() && MI->getOperand(Idx-1).isImplicit())
323 bool isTied = MI->getDesc().getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
328 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef,
329 false/*isImp*/, isKill,
330 false/*isDead*/, false/*isUndef*/,
331 false/*isEarlyClobber*/,
332 0/*SubReg*/, IsDebug));
335 /// AddOperand - Add the specified operand to the specified machine instr. II
336 /// specifies the instruction information for the node, and IIOpNum is the
337 /// operand number (in the II) that we are adding. IIOpNum and II are used for
339 void InstrEmitter::AddOperand(MachineInstr *MI, SDValue Op,
341 const MCInstrDesc *II,
342 DenseMap<SDValue, unsigned> &VRBaseMap,
343 bool IsDebug, bool IsClone, bool IsCloned) {
344 if (Op.isMachineOpcode()) {
345 AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap,
346 IsDebug, IsClone, IsCloned);
347 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
348 MI->addOperand(MachineOperand::CreateImm(C->getSExtValue()));
349 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
350 const ConstantFP *CFP = F->getConstantFPValue();
351 MI->addOperand(MachineOperand::CreateFPImm(CFP));
352 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
353 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
354 } else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
355 MI->addOperand(MachineOperand::CreateRegMask(RM->getRegMask()));
356 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
357 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(), TGA->getOffset(),
358 TGA->getTargetFlags()));
359 } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
360 MI->addOperand(MachineOperand::CreateMBB(BBNode->getBasicBlock()));
361 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
362 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
363 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
364 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex(),
365 JT->getTargetFlags()));
366 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
367 int Offset = CP->getOffset();
368 unsigned Align = CP->getAlignment();
369 Type *Type = CP->getType();
370 // MachineConstantPool wants an explicit alignment.
372 Align = TM->getTargetData()->getPrefTypeAlignment(Type);
374 // Alignment of vector types. FIXME!
375 Align = TM->getTargetData()->getTypeAllocSize(Type);
380 MachineConstantPool *MCP = MF->getConstantPool();
381 if (CP->isMachineConstantPoolEntry())
382 Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
384 Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
385 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset,
386 CP->getTargetFlags()));
387 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
388 MI->addOperand(MachineOperand::CreateES(ES->getSymbol(),
389 ES->getTargetFlags()));
390 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
391 MI->addOperand(MachineOperand::CreateBA(BA->getBlockAddress(),
392 BA->getTargetFlags()));
394 assert(Op.getValueType() != MVT::Other &&
395 Op.getValueType() != MVT::Glue &&
396 "Chain and glue operands should occur at end of operand list!");
397 AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap,
398 IsDebug, IsClone, IsCloned);
402 unsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
403 EVT VT, DebugLoc DL) {
404 const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
405 const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
407 // RC is a sub-class of VRC that supports SubIdx. Try to constrain VReg
410 RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
412 // VReg has been adjusted. It can be used with SubIdx operands now.
416 // VReg couldn't be reasonably constrained. Emit a COPY to a new virtual
418 RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
419 assert(RC && "No legal register class for VT supports that SubIdx");
420 unsigned NewReg = MRI->createVirtualRegister(RC);
421 BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
426 /// EmitSubregNode - Generate machine code for subreg nodes.
428 void InstrEmitter::EmitSubregNode(SDNode *Node,
429 DenseMap<SDValue, unsigned> &VRBaseMap,
430 bool IsClone, bool IsCloned) {
432 unsigned Opc = Node->getMachineOpcode();
434 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
435 // the CopyToReg'd destination register instead of creating a new vreg.
436 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
439 if (User->getOpcode() == ISD::CopyToReg &&
440 User->getOperand(2).getNode() == Node) {
441 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
442 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
449 if (Opc == TargetOpcode::EXTRACT_SUBREG) {
450 // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub. There are no
451 // constraints on the %dst register, COPY can target all legal register
453 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
454 const TargetRegisterClass *TRC = TLI->getRegClassFor(Node->getValueType(0));
456 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
457 MachineInstr *DefMI = MRI->getVRegDef(VReg);
458 unsigned SrcReg, DstReg, DefSubIdx;
460 TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
461 SubIdx == DefSubIdx) {
463 // r1025 = s/zext r1024, 4
464 // r1026 = extract_subreg r1025, 4
466 // r1026 = copy r1024
467 VRBase = MRI->createVirtualRegister(TRC);
468 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
469 TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
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
474 VReg = ConstrainForSubReg(VReg, SubIdx,
475 Node->getOperand(0).getValueType(),
476 Node->getDebugLoc());
478 // Create the destreg if it is missing.
480 VRBase = MRI->createVirtualRegister(TRC);
482 // Create the extract_subreg machine instruction.
483 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
484 TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
486 } else if (Opc == TargetOpcode::INSERT_SUBREG ||
487 Opc == TargetOpcode::SUBREG_TO_REG) {
488 SDValue N0 = Node->getOperand(0);
489 SDValue N1 = Node->getOperand(1);
490 SDValue N2 = Node->getOperand(2);
491 unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
493 // Figure out the register class to create for the destreg. It should be
494 // the largest legal register class supporting SubIdx sub-registers.
495 // RegisterCoalescer will constrain it further if it decides to eliminate
496 // the INSERT_SUBREG instruction.
498 // %dst = INSERT_SUBREG %src, %sub, SubIdx
500 // is lowered by TwoAddressInstructionPass to:
503 // %dst:SubIdx = COPY %sub
505 // There is no constraint on the %src register class.
507 const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getValueType(0));
508 SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
509 assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
511 if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
512 VRBase = MRI->createVirtualRegister(SRC);
514 // Create the insert_subreg or subreg_to_reg machine instruction.
515 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc));
516 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
518 // If creating a subreg_to_reg, then the first input operand
519 // is an implicit value immediate, otherwise it's a register
520 if (Opc == TargetOpcode::SUBREG_TO_REG) {
521 const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
522 MI->addOperand(MachineOperand::CreateImm(SD->getZExtValue()));
524 AddOperand(MI, N0, 0, 0, VRBaseMap, /*IsDebug=*/false,
526 // Add the subregster being inserted
527 AddOperand(MI, N1, 0, 0, VRBaseMap, /*IsDebug=*/false,
529 MI->addOperand(MachineOperand::CreateImm(SubIdx));
530 MBB->insert(InsertPos, MI);
532 llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
535 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
536 (void)isNew; // Silence compiler warning.
537 assert(isNew && "Node emitted out of order - early");
540 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
541 /// COPY_TO_REGCLASS is just a normal copy, except that the destination
542 /// register is constrained to be in a particular register class.
545 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
546 DenseMap<SDValue, unsigned> &VRBaseMap) {
547 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
549 // Create the new VReg in the destination class and emit a copy.
550 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
551 const TargetRegisterClass *DstRC = TRI->getRegClass(DstRCIdx);
552 unsigned NewVReg = MRI->createVirtualRegister(DstRC);
553 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
554 NewVReg).addReg(VReg);
557 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
558 (void)isNew; // Silence compiler warning.
559 assert(isNew && "Node emitted out of order - early");
562 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
564 void InstrEmitter::EmitRegSequence(SDNode *Node,
565 DenseMap<SDValue, unsigned> &VRBaseMap,
566 bool IsClone, bool IsCloned) {
567 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
568 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
569 unsigned NewVReg = MRI->createVirtualRegister(RC);
570 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
571 TII->get(TargetOpcode::REG_SEQUENCE), NewVReg);
572 unsigned NumOps = Node->getNumOperands();
573 assert((NumOps & 1) == 1 &&
574 "REG_SEQUENCE must have an odd number of operands!");
575 const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
576 for (unsigned i = 1; i != NumOps; ++i) {
577 SDValue Op = Node->getOperand(i);
579 RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
580 // Skip physical registers as they don't have a vreg to get and we'll
581 // insert copies for them in TwoAddressInstructionPass anyway.
582 if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
583 unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
584 unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
585 const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
586 const TargetRegisterClass *SRC =
587 TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
588 if (SRC && SRC != RC) {
589 MRI->setRegClass(NewVReg, SRC);
594 AddOperand(MI, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
598 MBB->insert(InsertPos, MI);
600 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
601 (void)isNew; // Silence compiler warning.
602 assert(isNew && "Node emitted out of order - early");
605 /// EmitDbgValue - Generate machine instruction for a dbg_value node.
608 InstrEmitter::EmitDbgValue(SDDbgValue *SD,
609 DenseMap<SDValue, unsigned> &VRBaseMap) {
610 uint64_t Offset = SD->getOffset();
611 MDNode* MDPtr = SD->getMDPtr();
612 DebugLoc DL = SD->getDebugLoc();
614 if (SD->getKind() == SDDbgValue::FRAMEIX) {
615 // Stack address; this needs to be lowered in target-dependent fashion.
616 // EmitTargetCodeForFrameDebugValue is responsible for allocation.
617 unsigned FrameIx = SD->getFrameIx();
618 return TII->emitFrameIndexDebugValue(*MF, FrameIx, Offset, MDPtr, DL);
620 // Otherwise, we're going to create an instruction here.
621 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
622 MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
623 if (SD->getKind() == SDDbgValue::SDNODE) {
624 SDNode *Node = SD->getSDNode();
625 SDValue Op = SDValue(Node, SD->getResNo());
626 // It's possible we replaced this SDNode with other(s) and therefore
627 // didn't generate code for it. It's better to catch these cases where
628 // they happen and transfer the debug info, but trying to guarantee that
629 // in all cases would be very fragile; this is a safeguard for any
631 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
632 if (I==VRBaseMap.end())
633 MIB.addReg(0U); // undef
635 AddOperand(&*MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
636 /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
637 } else if (SD->getKind() == SDDbgValue::CONST) {
638 const Value *V = SD->getConst();
639 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
640 if (CI->getBitWidth() > 64)
643 MIB.addImm(CI->getSExtValue());
644 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
647 // Could be an Undef. In any case insert an Undef so we can see what we
652 // Insert an Undef so we can see what we dropped.
656 MIB.addImm(Offset).addMetadata(MDPtr);
660 /// EmitMachineNode - Generate machine code for a target-specific node and
661 /// needed dependencies.
664 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
665 DenseMap<SDValue, unsigned> &VRBaseMap) {
666 unsigned Opc = Node->getMachineOpcode();
668 // Handle subreg insert/extract specially
669 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
670 Opc == TargetOpcode::INSERT_SUBREG ||
671 Opc == TargetOpcode::SUBREG_TO_REG) {
672 EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
676 // Handle COPY_TO_REGCLASS specially.
677 if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
678 EmitCopyToRegClassNode(Node, VRBaseMap);
682 // Handle REG_SEQUENCE specially.
683 if (Opc == TargetOpcode::REG_SEQUENCE) {
684 EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
688 if (Opc == TargetOpcode::IMPLICIT_DEF)
689 // We want a unique VR for each IMPLICIT_DEF use.
692 const MCInstrDesc &II = TII->get(Opc);
693 unsigned NumResults = CountResults(Node);
694 unsigned NodeOperands = CountOperands(Node);
695 bool HasPhysRegOuts = NumResults > II.getNumDefs() && II.getImplicitDefs()!=0;
697 unsigned NumMIOperands = NodeOperands + NumResults;
699 assert(NumMIOperands >= II.getNumOperands() &&
700 "Too few operands for a variadic node!");
702 assert(NumMIOperands >= II.getNumOperands() &&
703 NumMIOperands <= II.getNumOperands()+II.getNumImplicitDefs() &&
704 "#operands for dag node doesn't match .td file!");
707 // Create the new machine instruction.
708 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), II);
710 // Add result register values for things that are defined by this
713 CreateVirtualRegisters(Node, MI, II, IsClone, IsCloned, VRBaseMap);
715 // Emit all of the actual operands of this instruction, adding them to the
716 // instruction as appropriate.
717 bool HasOptPRefs = II.getNumDefs() > NumResults;
718 assert((!HasOptPRefs || !HasPhysRegOuts) &&
719 "Unable to cope with optional defs and phys regs defs!");
720 unsigned NumSkip = HasOptPRefs ? II.getNumDefs() - NumResults : 0;
721 for (unsigned i = NumSkip; i != NodeOperands; ++i)
722 AddOperand(MI, Node->getOperand(i), i-NumSkip+II.getNumDefs(), &II,
723 VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
725 // Transfer all of the memory reference descriptions of this instruction.
726 MI->setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
727 cast<MachineSDNode>(Node)->memoperands_end());
729 // Insert the instruction into position in the block. This needs to
730 // happen before any custom inserter hook is called so that the
731 // hook knows where in the block to insert the replacement code.
732 MBB->insert(InsertPos, MI);
734 // The MachineInstr may also define physregs instead of virtregs. These
735 // physreg values can reach other instructions in different ways:
737 // 1. When there is a use of a Node value beyond the explicitly defined
738 // virtual registers, we emit a CopyFromReg for one of the implicitly
739 // defined physregs. This only happens when HasPhysRegOuts is true.
741 // 2. A CopyFromReg reading a physreg may be glued to this instruction.
743 // 3. A glued instruction may implicitly use a physreg.
745 // 4. A glued instruction may use a RegisterSDNode operand.
747 // Collect all the used physreg defs, and make sure that any unused physreg
748 // defs are marked as dead.
749 SmallVector<unsigned, 8> UsedRegs;
751 // Additional results must be physical register defs.
752 if (HasPhysRegOuts) {
753 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
754 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
755 if (!Node->hasAnyUseOfValue(i))
757 // This implicitly defined physreg has a use.
758 UsedRegs.push_back(Reg);
759 EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
763 // Scan the glue chain for any used physregs.
764 if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
765 for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
766 if (F->getOpcode() == ISD::CopyFromReg) {
767 UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
770 // Collect declared implicit uses.
771 const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
772 UsedRegs.append(MCID.getImplicitUses(),
773 MCID.getImplicitUses() + MCID.getNumImplicitUses());
774 // In addition to declared implicit uses, we must also check for
775 // direct RegisterSDNode operands.
776 for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
777 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
778 unsigned Reg = R->getReg();
779 if (TargetRegisterInfo::isPhysicalRegister(Reg))
780 UsedRegs.push_back(Reg);
785 // Finally mark unused registers as dead.
786 if (!UsedRegs.empty() || II.getImplicitDefs())
787 MI->setPhysRegsDeadExcept(UsedRegs, *TRI);
789 // Run post-isel target hook to adjust this instruction if needed.
791 if (II.hasPostISelHook())
793 TLI->AdjustInstrPostInstrSelection(MI, Node);
796 /// EmitSpecialNode - Generate machine code for a target-independent node and
797 /// needed dependencies.
799 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
800 DenseMap<SDValue, unsigned> &VRBaseMap) {
801 switch (Node->getOpcode()) {
806 llvm_unreachable("This target-independent node should have been selected!");
807 case ISD::EntryToken:
808 llvm_unreachable("EntryToken should have been excluded from the schedule!");
809 case ISD::MERGE_VALUES:
810 case ISD::TokenFactor: // fall thru
812 case ISD::CopyToReg: {
814 SDValue SrcVal = Node->getOperand(2);
815 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
816 SrcReg = R->getReg();
818 SrcReg = getVR(SrcVal, VRBaseMap);
820 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
821 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
824 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
825 DestReg).addReg(SrcReg);
828 case ISD::CopyFromReg: {
829 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
830 EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
833 case ISD::EH_LABEL: {
834 MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
835 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
836 TII->get(TargetOpcode::EH_LABEL)).addSym(S);
840 case ISD::INLINEASM: {
841 unsigned NumOps = Node->getNumOperands();
842 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
843 --NumOps; // Ignore the glue operand.
845 // Create the inline asm machine instruction.
846 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
847 TII->get(TargetOpcode::INLINEASM));
849 // Add the asm string as an external symbol operand.
850 SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
851 const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
852 MI->addOperand(MachineOperand::CreateES(AsmStr));
854 // Add the HasSideEffect and isAlignStack bits.
856 cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
858 MI->addOperand(MachineOperand::CreateImm(ExtraInfo));
860 // Add all of the operand registers to the instruction.
861 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
863 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
864 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
866 MI->addOperand(MachineOperand::CreateImm(Flags));
867 ++i; // Skip the ID value.
869 switch (InlineAsm::getKind(Flags)) {
870 default: llvm_unreachable("Bad flags!");
871 case InlineAsm::Kind_RegDef:
872 for (; NumVals; --NumVals, ++i) {
873 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
874 // FIXME: Add dead flags for physical and virtual registers defined.
875 // For now, mark physical register defs as implicit to help fast
876 // regalloc. This makes inline asm look a lot like calls.
877 MI->addOperand(MachineOperand::CreateReg(Reg, true,
878 /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg)));
881 case InlineAsm::Kind_RegDefEarlyClobber:
882 case InlineAsm::Kind_Clobber:
883 for (; NumVals; --NumVals, ++i) {
884 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
885 MI->addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/ true,
886 /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg),
890 /*isEarlyClobber=*/ true));
893 case InlineAsm::Kind_RegUse: // Use of register.
894 case InlineAsm::Kind_Imm: // Immediate.
895 case InlineAsm::Kind_Mem: // Addressing mode.
896 // The addressing mode has been selected, just add all of the
897 // operands to the machine instruction.
898 for (; NumVals; --NumVals, ++i)
899 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap,
900 /*IsDebug=*/false, IsClone, IsCloned);
905 // Get the mdnode from the asm if it exists and add it to the instruction.
906 SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
907 const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
909 MI->addOperand(MachineOperand::CreateMetadata(MD));
911 MBB->insert(InsertPos, MI);
917 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
918 /// at the given position in the given block.
919 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
920 MachineBasicBlock::iterator insertpos)
921 : MF(mbb->getParent()),
922 MRI(&MF->getRegInfo()),
923 TM(&MF->getTarget()),
924 TII(TM->getInstrInfo()),
925 TRI(TM->getRegisterInfo()),
926 TLI(TM->getTargetLowering()),
927 MBB(mbb), InsertPos(insertpos) {