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