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