[Stackmap] Add AnyReg calling convention support for patchpoint intrinsic.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / InstrEmitter.cpp
1 //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the Emit routines for the SelectionDAG class, which creates
11 // MachineInstrs based on the decisions of the SelectionDAG instruction
12 // selection.
13 //
14 //===----------------------------------------------------------------------===//
15
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"
31 using namespace llvm;
32
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
36 /// instead.
37 const unsigned MinRCSize = 4;
38
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)
45     --N;
46   if (N && Node->getValueType(N - 1) == MVT::Other)
47     --N;    // Skip over chain result.
48   return N;
49 }
50
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
54 /// MachineInstr.
55 ///
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)
62     --N;
63   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
64     --N; // Ignore chain if it exists.
65
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)))
70       continue;
71     if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1)))
72       if (TargetRegisterInfo::isPhysicalRegister(RN->getReg()))
73         continue;
74     NumImpUses = N - I;
75     break;
76   }
77
78   return N;
79 }
80
81 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
82 /// implicit physical register output.
83 void InstrEmitter::
84 EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
85                 unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
86   unsigned VRBase = 0;
87   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
88     // Just use the input register directly!
89     SDValue Op(Node, ResNo);
90     if (IsClone)
91       VRBaseMap.erase(Op);
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");
95     return;
96   }
97
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);
103
104   // Stick to the preferred register classes for legal types.
105   if (TLI->isTypeLegal(VT))
106     UseRC = TLI->getRegClassFor(VT);
107
108   if (!IsClone && !IsCloned)
109     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
110          UI != E; ++UI) {
111       SDNode *User = *UI;
112       bool Match = true;
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)) {
118           VRBase = DestReg;
119           Match = false;
120         } else if (DestReg != SrcReg)
121           Match = false;
122       } else {
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)
126             continue;
127           MVT VT = Node->getSimpleValueType(Op.getResNo());
128           if (VT == MVT::Other || VT == MVT::Glue)
129             continue;
130           Match = false;
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));
137             }
138             if (!UseRC)
139               UseRC = RC;
140             else if (RC) {
141               const TargetRegisterClass *ComRC =
142                 TRI->getCommonSubClass(UseRC, RC);
143               // If multiple uses expect disjoint register classes, we emit
144               // copies in AddRegisterOperand.
145               if (ComRC)
146                 UseRC = ComRC;
147             }
148           }
149         }
150       }
151       MatchReg &= Match;
152       if (VRBase)
153         break;
154     }
155
156   const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
157   SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
158
159   // Figure out the register class to create for the destreg.
160   if (VRBase) {
161     DstRC = MRI->getRegClass(VRBase);
162   } else if (UseRC) {
163     assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
164     DstRC = UseRC;
165   } else {
166     DstRC = TLI->getRegClassFor(VT);
167   }
168
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) {
172     VRBase = SrcReg;
173   } else {
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);
178   }
179
180   SDValue Op(Node, ResNo);
181   if (IsClone)
182     VRBaseMap.erase(Op);
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");
186 }
187
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())
193     return 0;
194
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))
201       return Reg;
202   }
203   return 0;
204 }
205
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!");
213
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.
219     unsigned VRBase = 0;
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);
232     }
233
234     if (!VRBase && !IsClone && !IsCloned)
235       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
236            UI != E; ++UI) {
237         SDNode *User = *UI;
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);
244             if (RegRC == RC) {
245               VRBase = Reg;
246               MIB.addReg(VRBase, RegState::Define);
247               break;
248             }
249           }
250         }
251       }
252
253     // Create the result registers for this node and add the result regs to
254     // the machine instruction.
255     if (VRBase == 0) {
256       assert(RC && "Isn't a register operand!");
257       VRBase = MRI->createVirtualRegister(RC);
258       MIB.addReg(VRBase, RegState::Define);
259     }
260
261     SDValue Op(Node, i);
262     if (IsClone)
263       VRBaseMap.erase(Op);
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");
267   }
268 }
269
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.
280     if (!VReg) {
281       const TargetRegisterClass *RC =
282         TLI->getRegClassFor(Op.getSimpleValueType());
283       VReg = MRI->createVirtualRegister(RC);
284     }
285     BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
286             TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
287     return VReg;
288   }
289
290   DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
291   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
292   return I->second;
293 }
294
295
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.
299 void
300 InstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB,
301                                  SDValue Op,
302                                  unsigned IIOpNum,
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?");
312
313   const MCInstrDesc &MCID = MIB->getDesc();
314   bool isOptDef = IIOpNum < MCID.getNumOperands() &&
315     MCID.OpInfo[IIOpNum].isOptionalDef();
316
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.
321   if (II) {
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);
329       VReg = NewVReg;
330     }
331   }
332
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
337   // multiple uses.
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 &&
342                 !IsDebug &&
343                 !(IsClone || IsCloned);
344   if (isKill) {
345     unsigned Idx = MIB->getNumOperands();
346     while (Idx > 0 &&
347            MIB->getOperand(Idx-1).isReg() &&
348            MIB->getOperand(Idx-1).isImplicit())
349       --Idx;
350     bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
351     if (isTied)
352       isKill = false;
353   }
354
355   MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) |
356              getDebugRegState(IsDebug));
357 }
358
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,
363                               SDValue Op,
364                               unsigned IIOpNum,
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.
397     if (Align == 0) {
398       Align = TM->getDataLayout()->getPrefTypeAlignment(Type);
399       if (Align == 0) {
400         // Alignment of vector types.  FIXME!
401         Align = TM->getDataLayout()->getTypeAllocSize(Type);
402       }
403     }
404
405     unsigned Idx;
406     MachineConstantPool *MCP = MF->getConstantPool();
407     if (CP->isMachineConstantPoolEntry())
408       Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
409     else
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(),
416                         BA->getOffset(),
417                         BA->getTargetFlags());
418   } else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
419     MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags());
420   } else {
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);
426   }
427 }
428
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);
433
434   // RC is a sub-class of VRC that supports SubIdx.  Try to constrain VReg
435   // within reason.
436   if (RC && RC != VRC)
437     RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
438
439   // VReg has been adjusted.  It can be used with SubIdx operands now.
440   if (RC)
441     return VReg;
442
443   // VReg couldn't be reasonably constrained.  Emit a COPY to a new virtual
444   // register instead.
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)
449     .addReg(VReg);
450   return NewReg;
451 }
452
453 /// EmitSubregNode - Generate machine code for subreg nodes.
454 ///
455 void InstrEmitter::EmitSubregNode(SDNode *Node,
456                                   DenseMap<SDValue, unsigned> &VRBaseMap,
457                                   bool IsClone, bool IsCloned) {
458   unsigned VRBase = 0;
459   unsigned Opc = Node->getMachineOpcode();
460
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();
464        UI != E; ++UI) {
465     SDNode *User = *UI;
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)) {
470         VRBase = DestReg;
471         break;
472       }
473     }
474   }
475
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
479     // classes.
480     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
481     const TargetRegisterClass *TRC =
482       TLI->getRegClassFor(Node->getSimpleValueType(0));
483
484     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
485     MachineInstr *DefMI = MRI->getVRegDef(VReg);
486     unsigned SrcReg, DstReg, DefSubIdx;
487     if (DefMI &&
488         TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
489         SubIdx == DefSubIdx &&
490         TRC == MRI->getRegClass(SrcReg)) {
491       // Optimize these:
492       // r1025 = s/zext r1024, 4
493       // r1026 = extract_subreg r1025, 4
494       // to a copy
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);
500     } else {
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
503       // class.
504       VReg = ConstrainForSubReg(VReg, SubIdx,
505                                 Node->getOperand(0).getSimpleValueType(),
506                                 Node->getDebugLoc());
507
508       // Create the destreg if it is missing.
509       if (VRBase == 0)
510         VRBase = MRI->createVirtualRegister(TRC);
511
512       // Create the extract_subreg machine instruction.
513       BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
514               TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
515     }
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();
522
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.
527     //
528     //   %dst = INSERT_SUBREG %src, %sub, SubIdx
529     //
530     // is lowered by TwoAddressInstructionPass to:
531     //
532     //   %dst = COPY %src
533     //   %dst:SubIdx = COPY %sub
534     //
535     // There is no constraint on the %src register class.
536     //
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");
540
541     if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
542       VRBase = MRI->createVirtualRegister(SRC);
543
544     // Create the insert_subreg or subreg_to_reg machine instruction.
545     MachineInstrBuilder MIB =
546       BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
547
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());
553     } else
554       AddOperand(MIB, N0, 0, 0, VRBaseMap, /*IsDebug=*/false,
555                  IsClone, IsCloned);
556     // Add the subregster being inserted
557     AddOperand(MIB, N1, 0, 0, VRBaseMap, /*IsDebug=*/false,
558                IsClone, IsCloned);
559     MIB.addImm(SubIdx);
560     MBB->insert(InsertPos, MIB);
561   } else
562     llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
563
564   SDValue Op(Node, 0);
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");
568 }
569
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.
573 ///
574 void
575 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
576                                      DenseMap<SDValue, unsigned> &VRBaseMap) {
577   unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
578
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);
586
587   SDValue Op(Node, 0);
588   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
589   (void)isNew; // Silence compiler warning.
590   assert(isNew && "Node emitted out of order - early");
591 }
592
593 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
594 ///
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);
608     if ((i & 1) == 0) {
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);
620           RC = SRC;
621         }
622       }
623     }
624     AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
625                IsClone, IsCloned);
626   }
627
628   MBB->insert(InsertPos, MIB);
629   SDValue Op(Node, 0);
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");
633 }
634
635 /// EmitDbgValue - Generate machine instruction for a dbg_value node.
636 ///
637 MachineInstr *
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();
643
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);
649   }
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
660     // that were missed.
661     DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
662     if (I==VRBaseMap.end())
663       MIB.addReg(0U);       // undef
664     else
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)
671         MIB.addCImm(CI);
672       else
673         MIB.addImm(CI->getSExtValue());
674     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
675       MIB.addFPImm(CF);
676     } else {
677       // Could be an Undef.  In any case insert an Undef so we can see what we
678       // dropped.
679       MIB.addReg(0U);
680     }
681   } else {
682     // Insert an Undef so we can see what we dropped.
683     MIB.addReg(0U);
684   }
685
686   if (Offset != 0) // Indirect addressing.
687     MIB.addImm(Offset);
688   else
689     MIB.addReg(0U, RegState::Debug);
690
691   MIB.addMetadata(MDPtr);
692
693   return &*MIB;
694 }
695
696 /// EmitMachineNode - Generate machine code for a target-specific node and
697 /// needed dependencies.
698 ///
699 void InstrEmitter::
700 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
701                 DenseMap<SDValue, unsigned> &VRBaseMap) {
702   unsigned Opc = Node->getMachineOpcode();
703
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);
709     return;
710   }
711
712   // Handle COPY_TO_REGCLASS specially.
713   if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
714     EmitCopyToRegClassNode(Node, VRBaseMap);
715     return;
716   }
717
718   // Handle REG_SEQUENCE specially.
719   if (Opc == TargetOpcode::REG_SEQUENCE) {
720     EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
721     return;
722   }
723
724   if (Opc == TargetOpcode::IMPLICIT_DEF)
725     // We want a unique VR for each IMPLICIT_DEF use.
726     return;
727
728   const MCInstrDesc &II = TII->get(Opc);
729   unsigned NumResults = CountResults(Node);
730   unsigned NumDefs = II.getNumDefs();
731
732   // Handle PATCHPOINT specially and then use the generic code.
733   if (Opc == TargetOpcode::PATCHPOINT)
734     NumDefs = NumResults;
735
736   unsigned NumImpUses = 0;
737   unsigned NodeOperands =
738     countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
739   bool HasPhysRegOuts = NumResults > NumDefs && II.getImplicitDefs()!=0;
740 #ifndef NDEBUG
741   unsigned NumMIOperands = NodeOperands + NumResults;
742   if (II.isVariadic())
743     assert(NumMIOperands >= II.getNumOperands() &&
744            "Too few operands for a variadic node!");
745   else
746     assert(NumMIOperands >= II.getNumOperands() &&
747            NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
748                             NumImpUses &&
749            "#operands for dag node doesn't match .td file!");
750 #endif
751
752   // Create the new machine instruction.
753   MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
754
755   // Add result register values for things that are defined by this
756   // instruction.
757   if (NumResults)
758     CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
759
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);
769
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());
773
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);
778
779   // The MachineInstr may also define physregs instead of virtregs.  These
780   // physreg values can reach other instructions in different ways:
781   //
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.
785   //
786   // 2. A CopyFromReg reading a physreg may be glued to this instruction.
787   //
788   // 3. A glued instruction may implicitly use a physreg.
789   //
790   // 4. A glued instruction may use a RegisterSDNode operand.
791   //
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;
795
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))
801         continue;
802       // This implicitly defined physreg has a use.
803       UsedRegs.push_back(Reg);
804       EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
805     }
806   }
807
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());
813         continue;
814       } else if (F->getOpcode() == ISD::CopyToReg) {
815         // Skip CopyToReg nodes that are internal to the glue chain.
816         continue;
817       }
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);
829         }
830     }
831   }
832
833   // Finally mark unused registers as dead.
834   if (!UsedRegs.empty() || II.getImplicitDefs())
835     MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
836
837   // Run post-isel target hook to adjust this instruction if needed.
838 #ifdef NDEBUG
839   if (II.hasPostISelHook())
840 #endif
841     TLI->AdjustInstrPostInstrSelection(MIB, Node);
842 }
843
844 /// EmitSpecialNode - Generate machine code for a target-independent node and
845 /// needed dependencies.
846 void InstrEmitter::
847 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
848                 DenseMap<SDValue, unsigned> &VRBaseMap) {
849   switch (Node->getOpcode()) {
850   default:
851 #ifndef NDEBUG
852     Node->dump();
853 #endif
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
859     break;
860   case ISD::CopyToReg: {
861     unsigned SrcReg;
862     SDValue SrcVal = Node->getOperand(2);
863     if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
864       SrcReg = R->getReg();
865     else
866       SrcReg = getVR(SrcVal, VRBaseMap);
867
868     unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
869     if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
870       break;
871
872     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
873             DestReg).addReg(SrcReg);
874     break;
875   }
876   case ISD::CopyFromReg: {
877     unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
878     EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
879     break;
880   }
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);
885     break;
886   }
887
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;
892
893     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1));
894     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
895     .addFrameIndex(FI->getIndex());
896     break;
897   }
898
899   case ISD::INLINEASM: {
900     unsigned NumOps = Node->getNumOperands();
901     if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
902       --NumOps;  // Ignore the glue operand.
903
904     // Create the inline asm machine instruction.
905     MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(),
906                                       TII->get(TargetOpcode::INLINEASM));
907
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);
912
913     // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
914     // bits.
915     int64_t ExtraInfo =
916       cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
917                           getZExtValue();
918     MIB.addImm(ExtraInfo);
919
920     // Remember to operand index of the group flags.
921     SmallVector<unsigned, 8> GroupIdx;
922
923     // Add all of the operand registers to the instruction.
924     for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
925       unsigned Flags =
926         cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
927       const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
928
929       GroupIdx.push_back(MIB->getNumOperands());
930       MIB.addImm(Flags);
931       ++i;  // Skip the ID value.
932
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)));
943         }
944         break;
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)));
951         }
952         break;
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);
961
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);
970           }
971         }
972         break;
973       }
974     }
975
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();
979     if (MD)
980       MIB.addMetadata(MD);
981
982     MBB->insert(InsertPos, MIB);
983     break;
984   }
985   }
986 }
987
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) {
999 }