propagate target operand flags from dag nodes into MachineOperands.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGSDNodesEmit.cpp
1 //===---- ScheduleDAGEmit.cpp - Emit routines for the ScheduleDAG 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 ScheduleDAG class, which creates
11 // MachineInstrs according to the computed schedule.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "ScheduleDAGSDNodes.h"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/MathExtras.h"
29 using namespace llvm;
30
31 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
32 /// implicit physical register output.
33 void ScheduleDAGSDNodes::
34 EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
35                 unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
36   unsigned VRBase = 0;
37   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
38     // Just use the input register directly!
39     SDValue Op(Node, ResNo);
40     if (IsClone)
41       VRBaseMap.erase(Op);
42     bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
43     isNew = isNew; // Silence compiler warning.
44     assert(isNew && "Node emitted out of order - early");
45     return;
46   }
47
48   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
49   // the CopyToReg'd destination register instead of creating a new vreg.
50   bool MatchReg = true;
51   const TargetRegisterClass *UseRC = NULL;
52   if (!IsClone && !IsCloned)
53     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
54          UI != E; ++UI) {
55       SDNode *User = *UI;
56       bool Match = true;
57       if (User->getOpcode() == ISD::CopyToReg && 
58           User->getOperand(2).getNode() == Node &&
59           User->getOperand(2).getResNo() == ResNo) {
60         unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
61         if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
62           VRBase = DestReg;
63           Match = false;
64         } else if (DestReg != SrcReg)
65           Match = false;
66       } else {
67         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
68           SDValue Op = User->getOperand(i);
69           if (Op.getNode() != Node || Op.getResNo() != ResNo)
70             continue;
71           MVT VT = Node->getValueType(Op.getResNo());
72           if (VT == MVT::Other || VT == MVT::Flag)
73             continue;
74           Match = false;
75           if (User->isMachineOpcode()) {
76             const TargetInstrDesc &II = TII->get(User->getMachineOpcode());
77             const TargetRegisterClass *RC =
78               getInstrOperandRegClass(TRI, II, i+II.getNumDefs());
79             if (!UseRC)
80               UseRC = RC;
81             else if (RC) {
82               if (UseRC->hasSuperClass(RC))
83                 UseRC = RC;
84               else
85                 assert((UseRC == RC || RC->hasSuperClass(UseRC)) &&
86                        "Multiple uses expecting different register classes!");
87             }
88           }
89         }
90       }
91       MatchReg &= Match;
92       if (VRBase)
93         break;
94     }
95
96   MVT VT = Node->getValueType(ResNo);
97   const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
98   SrcRC = TRI->getPhysicalRegisterRegClass(SrcReg, VT);
99   
100   // Figure out the register class to create for the destreg.
101   if (VRBase) {
102     DstRC = MRI.getRegClass(VRBase);
103   } else if (UseRC) {
104     assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
105     DstRC = UseRC;
106   } else {
107     DstRC = TLI->getRegClassFor(VT);
108   }
109     
110   // If all uses are reading from the src physical register and copying the
111   // register is either impossible or very expensive, then don't create a copy.
112   if (MatchReg && SrcRC->getCopyCost() < 0) {
113     VRBase = SrcReg;
114   } else {
115     // Create the reg, emit the copy.
116     VRBase = MRI.createVirtualRegister(DstRC);
117     bool Emitted = TII->copyRegToReg(*BB, InsertPos, VRBase, SrcReg,
118                                      DstRC, SrcRC);
119
120     assert(Emitted && "Unable to issue a copy instruction!\n");
121     (void) Emitted;
122   }
123
124   SDValue Op(Node, ResNo);
125   if (IsClone)
126     VRBaseMap.erase(Op);
127   bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
128   isNew = isNew; // Silence compiler warning.
129   assert(isNew && "Node emitted out of order - early");
130 }
131
132 /// getDstOfCopyToRegUse - If the only use of the specified result number of
133 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
134 unsigned ScheduleDAGSDNodes::getDstOfOnlyCopyToRegUse(SDNode *Node,
135                                                       unsigned ResNo) const {
136   if (!Node->hasOneUse())
137     return 0;
138
139   SDNode *User = *Node->use_begin();
140   if (User->getOpcode() == ISD::CopyToReg && 
141       User->getOperand(2).getNode() == Node &&
142       User->getOperand(2).getResNo() == ResNo) {
143     unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
144     if (TargetRegisterInfo::isVirtualRegister(Reg))
145       return Reg;
146   }
147   return 0;
148 }
149
150 void ScheduleDAGSDNodes::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
151                                        const TargetInstrDesc &II,
152                                        bool IsClone, bool IsCloned,
153                                        DenseMap<SDValue, unsigned> &VRBaseMap) {
154   assert(Node->getMachineOpcode() != TargetInstrInfo::IMPLICIT_DEF &&
155          "IMPLICIT_DEF should have been handled as a special case elsewhere!");
156
157   for (unsigned i = 0; i < II.getNumDefs(); ++i) {
158     // If the specific node value is only used by a CopyToReg and the dest reg
159     // is a vreg in the same register class, use the CopyToReg'd destination
160     // register instead of creating a new vreg.
161     unsigned VRBase = 0;
162     const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, II, i);
163
164     if (!IsClone && !IsCloned)
165       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
166            UI != E; ++UI) {
167         SDNode *User = *UI;
168         if (User->getOpcode() == ISD::CopyToReg && 
169             User->getOperand(2).getNode() == Node &&
170             User->getOperand(2).getResNo() == i) {
171           unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
172           if (TargetRegisterInfo::isVirtualRegister(Reg)) {
173             const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
174             if (RegRC == RC) {
175               VRBase = Reg;
176               MI->addOperand(MachineOperand::CreateReg(Reg, true));
177               break;
178             }
179           }
180         }
181       }
182
183     // Create the result registers for this node and add the result regs to
184     // the machine instruction.
185     if (VRBase == 0) {
186       assert(RC && "Isn't a register operand!");
187       VRBase = MRI.createVirtualRegister(RC);
188       MI->addOperand(MachineOperand::CreateReg(VRBase, true));
189     }
190
191     SDValue Op(Node, i);
192     if (IsClone)
193       VRBaseMap.erase(Op);
194     bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
195     isNew = isNew; // Silence compiler warning.
196     assert(isNew && "Node emitted out of order - early");
197   }
198 }
199
200 /// getVR - Return the virtual register corresponding to the specified result
201 /// of the specified node.
202 unsigned ScheduleDAGSDNodes::getVR(SDValue Op,
203                                    DenseMap<SDValue, unsigned> &VRBaseMap) {
204   if (Op.isMachineOpcode() &&
205       Op.getMachineOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
206     // Add an IMPLICIT_DEF instruction before every use.
207     unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
208     // IMPLICIT_DEF can produce any type of result so its TargetInstrDesc
209     // does not include operand register class info.
210     if (!VReg) {
211       const TargetRegisterClass *RC = TLI->getRegClassFor(Op.getValueType());
212       VReg = MRI.createVirtualRegister(RC);
213     }
214     BuildMI(BB, Op.getDebugLoc(), TII->get(TargetInstrInfo::IMPLICIT_DEF),VReg);
215     return VReg;
216   }
217
218   DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
219   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
220   return I->second;
221 }
222
223
224 /// AddRegisterOperand - Add the specified register as an operand to the
225 /// specified machine instr. Insert register copies if the register is
226 /// not in the required register class.
227 void
228 ScheduleDAGSDNodes::AddRegisterOperand(MachineInstr *MI, SDValue Op,
229                                        unsigned IIOpNum,
230                                        const TargetInstrDesc *II,
231                                        DenseMap<SDValue, unsigned> &VRBaseMap) {
232   assert(Op.getValueType() != MVT::Other &&
233          Op.getValueType() != MVT::Flag &&
234          "Chain and flag operands should occur at end of operand list!");
235   // Get/emit the operand.
236   unsigned VReg = getVR(Op, VRBaseMap);
237   assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
238
239   const TargetInstrDesc &TID = MI->getDesc();
240   bool isOptDef = IIOpNum < TID.getNumOperands() &&
241     TID.OpInfo[IIOpNum].isOptionalDef();
242
243   // If the instruction requires a register in a different class, create
244   // a new virtual register and copy the value into it.
245   if (II) {
246     const TargetRegisterClass *SrcRC =
247       MRI.getRegClass(VReg);
248     const TargetRegisterClass *DstRC =
249       getInstrOperandRegClass(TRI, *II, IIOpNum);
250     assert((DstRC || (TID.isVariadic() && IIOpNum >= TID.getNumOperands())) &&
251            "Don't have operand info for this instruction!");
252     if (DstRC && SrcRC != DstRC && !SrcRC->hasSuperClass(DstRC)) {
253       unsigned NewVReg = MRI.createVirtualRegister(DstRC);
254       bool Emitted = TII->copyRegToReg(*BB, InsertPos, NewVReg, VReg,
255                                        DstRC, SrcRC);
256       assert(Emitted && "Unable to issue a copy instruction!\n");
257       (void) Emitted;
258       VReg = NewVReg;
259     }
260   }
261
262   MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
263 }
264
265 /// AddOperand - Add the specified operand to the specified machine instr.  II
266 /// specifies the instruction information for the node, and IIOpNum is the
267 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
268 /// assertions only.
269 void ScheduleDAGSDNodes::AddOperand(MachineInstr *MI, SDValue Op,
270                                     unsigned IIOpNum,
271                                     const TargetInstrDesc *II,
272                                     DenseMap<SDValue, unsigned> &VRBaseMap) {
273   if (Op.isMachineOpcode()) {
274     AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap);
275   } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
276     MI->addOperand(MachineOperand::CreateImm(C->getZExtValue()));
277   } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
278     const ConstantFP *CFP = F->getConstantFPValue();
279     MI->addOperand(MachineOperand::CreateFPImm(CFP));
280   } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
281     MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
282   } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
283     MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(), TGA->getOffset(),
284                                             TGA->getTargetFlags()));
285   } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
286     MI->addOperand(MachineOperand::CreateMBB(BBNode->getBasicBlock()));
287   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
288     MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
289   } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
290     MI->addOperand(MachineOperand::CreateJTI(JT->getIndex(),
291                                              JT->getTargetFlags()));
292   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
293     int Offset = CP->getOffset();
294     unsigned Align = CP->getAlignment();
295     const Type *Type = CP->getType();
296     // MachineConstantPool wants an explicit alignment.
297     if (Align == 0) {
298       Align = TM.getTargetData()->getPrefTypeAlignment(Type);
299       if (Align == 0) {
300         // Alignment of vector types.  FIXME!
301         Align = TM.getTargetData()->getTypeAllocSize(Type);
302       }
303     }
304     
305     unsigned Idx;
306     if (CP->isMachineConstantPoolEntry())
307       Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
308     else
309       Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
310     MI->addOperand(MachineOperand::CreateCPI(Idx, Offset,
311                                              CP->getTargetFlags()));
312   } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
313     MI->addOperand(MachineOperand::CreateES(ES->getSymbol(), 0,
314                                             ES->getTargetFlags()));
315   } else {
316     assert(Op.getValueType() != MVT::Other &&
317            Op.getValueType() != MVT::Flag &&
318            "Chain and flag operands should occur at end of operand list!");
319     AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap);
320   }
321 }
322
323 /// getSuperRegisterRegClass - Returns the register class of a superreg A whose
324 /// "SubIdx"'th sub-register class is the specified register class and whose
325 /// type matches the specified type.
326 static const TargetRegisterClass*
327 getSuperRegisterRegClass(const TargetRegisterClass *TRC,
328                          unsigned SubIdx, MVT VT) {
329   // Pick the register class of the superegister for this type
330   for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
331          E = TRC->superregclasses_end(); I != E; ++I)
332     if ((*I)->hasType(VT) && (*I)->getSubRegisterRegClass(SubIdx) == TRC)
333       return *I;
334   assert(false && "Couldn't find the register class");
335   return 0;
336 }
337
338 /// EmitSubregNode - Generate machine code for subreg nodes.
339 ///
340 void ScheduleDAGSDNodes::EmitSubregNode(SDNode *Node, 
341                                         DenseMap<SDValue, unsigned> &VRBaseMap){
342   unsigned VRBase = 0;
343   unsigned Opc = Node->getMachineOpcode();
344   
345   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
346   // the CopyToReg'd destination register instead of creating a new vreg.
347   for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
348        UI != E; ++UI) {
349     SDNode *User = *UI;
350     if (User->getOpcode() == ISD::CopyToReg && 
351         User->getOperand(2).getNode() == Node) {
352       unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
353       if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
354         VRBase = DestReg;
355         break;
356       }
357     }
358   }
359   
360   if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
361     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
362
363     // Create the extract_subreg machine instruction.
364     MachineInstr *MI = BuildMI(MF, Node->getDebugLoc(),
365                                TII->get(TargetInstrInfo::EXTRACT_SUBREG));
366
367     // Figure out the register class to create for the destreg.
368     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
369     const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
370     const TargetRegisterClass *SRC = TRC->getSubRegisterRegClass(SubIdx);
371     assert(SRC && "Invalid subregister index in EXTRACT_SUBREG");
372
373     // Figure out the register class to create for the destreg.
374     // Note that if we're going to directly use an existing register,
375     // it must be precisely the required class, and not a subclass
376     // thereof.
377     if (VRBase == 0 || SRC != MRI.getRegClass(VRBase)) {
378       // Create the reg
379       assert(SRC && "Couldn't find source register class");
380       VRBase = MRI.createVirtualRegister(SRC);
381     }
382
383     // Add def, source, and subreg index
384     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
385     AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
386     MI->addOperand(MachineOperand::CreateImm(SubIdx));
387     BB->insert(InsertPos, MI);
388   } else if (Opc == TargetInstrInfo::INSERT_SUBREG ||
389              Opc == TargetInstrInfo::SUBREG_TO_REG) {
390     SDValue N0 = Node->getOperand(0);
391     SDValue N1 = Node->getOperand(1);
392     SDValue N2 = Node->getOperand(2);
393     unsigned SubReg = getVR(N1, VRBaseMap);
394     unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
395     const TargetRegisterClass *TRC = MRI.getRegClass(SubReg);
396     const TargetRegisterClass *SRC =
397       getSuperRegisterRegClass(TRC, SubIdx,
398                                Node->getValueType(0));
399
400     // Figure out the register class to create for the destreg.
401     // Note that if we're going to directly use an existing register,
402     // it must be precisely the required class, and not a subclass
403     // thereof.
404     if (VRBase == 0 || SRC != MRI.getRegClass(VRBase)) {
405       // Create the reg
406       assert(SRC && "Couldn't find source register class");
407       VRBase = MRI.createVirtualRegister(SRC);
408     }
409
410     // Create the insert_subreg or subreg_to_reg machine instruction.
411     MachineInstr *MI = BuildMI(MF, Node->getDebugLoc(), TII->get(Opc));
412     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
413     
414     // If creating a subreg_to_reg, then the first input operand
415     // is an implicit value immediate, otherwise it's a register
416     if (Opc == TargetInstrInfo::SUBREG_TO_REG) {
417       const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
418       MI->addOperand(MachineOperand::CreateImm(SD->getZExtValue()));
419     } else
420       AddOperand(MI, N0, 0, 0, VRBaseMap);
421     // Add the subregster being inserted
422     AddOperand(MI, N1, 0, 0, VRBaseMap);
423     MI->addOperand(MachineOperand::CreateImm(SubIdx));
424     BB->insert(InsertPos, MI);
425   } else
426     assert(0 && "Node is not insert_subreg, extract_subreg, or subreg_to_reg");
427      
428   SDValue Op(Node, 0);
429   bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
430   isNew = isNew; // Silence compiler warning.
431   assert(isNew && "Node emitted out of order - early");
432 }
433
434 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
435 /// COPY_TO_REGCLASS is just a normal copy, except that the destination
436 /// register is constrained to be in a particular register class.
437 ///
438 void
439 ScheduleDAGSDNodes::EmitCopyToRegClassNode(SDNode *Node,
440                                        DenseMap<SDValue, unsigned> &VRBaseMap) {
441   unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
442   const TargetRegisterClass *SrcRC = MRI.getRegClass(VReg);
443
444   unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
445   const TargetRegisterClass *DstRC = TRI->getRegClass(DstRCIdx);
446
447   // Create the new VReg in the destination class and emit a copy.
448   unsigned NewVReg = MRI.createVirtualRegister(DstRC);
449   bool Emitted = TII->copyRegToReg(*BB, InsertPos, NewVReg, VReg,
450                                    DstRC, SrcRC);
451   assert(Emitted &&
452          "Unable to issue a copy instruction for a COPY_TO_REGCLASS node!\n");
453   (void) Emitted;
454
455   SDValue Op(Node, 0);
456   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
457   isNew = isNew; // Silence compiler warning.
458   assert(isNew && "Node emitted out of order - early");
459 }
460
461 /// EmitNode - Generate machine code for an node and needed dependencies.
462 ///
463 void ScheduleDAGSDNodes::EmitNode(SDNode *Node, bool IsClone, bool IsCloned,
464                                   DenseMap<SDValue, unsigned> &VRBaseMap) {
465   // If machine instruction
466   if (Node->isMachineOpcode()) {
467     unsigned Opc = Node->getMachineOpcode();
468     
469     // Handle subreg insert/extract specially
470     if (Opc == TargetInstrInfo::EXTRACT_SUBREG || 
471         Opc == TargetInstrInfo::INSERT_SUBREG ||
472         Opc == TargetInstrInfo::SUBREG_TO_REG) {
473       EmitSubregNode(Node, VRBaseMap);
474       return;
475     }
476
477     // Handle COPY_TO_REGCLASS specially.
478     if (Opc == TargetInstrInfo::COPY_TO_REGCLASS) {
479       EmitCopyToRegClassNode(Node, VRBaseMap);
480       return;
481     }
482
483     if (Opc == TargetInstrInfo::IMPLICIT_DEF)
484       // We want a unique VR for each IMPLICIT_DEF use.
485       return;
486     
487     const TargetInstrDesc &II = TII->get(Opc);
488     unsigned NumResults = CountResults(Node);
489     unsigned NodeOperands = CountOperands(Node);
490     unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
491     bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
492                           II.getImplicitDefs() != 0;
493 #ifndef NDEBUG
494     unsigned NumMIOperands = NodeOperands + NumResults;
495     assert((II.getNumOperands() == NumMIOperands ||
496             HasPhysRegOuts || II.isVariadic()) &&
497            "#operands for dag node doesn't match .td file!"); 
498 #endif
499
500     // Create the new machine instruction.
501     MachineInstr *MI = BuildMI(MF, Node->getDebugLoc(), II);
502     
503     // Add result register values for things that are defined by this
504     // instruction.
505     if (NumResults)
506       CreateVirtualRegisters(Node, MI, II, IsClone, IsCloned, VRBaseMap);
507     
508     // Emit all of the actual operands of this instruction, adding them to the
509     // instruction as appropriate.
510     for (unsigned i = 0; i != NodeOperands; ++i)
511       AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
512
513     // Emit all of the memory operands of this instruction
514     for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
515       AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
516
517     if (II.usesCustomDAGSchedInsertionHook()) {
518       // Insert this instruction into the basic block using a target
519       // specific inserter which may returns a new basic block.
520       BB = TLI->EmitInstrWithCustomInserter(MI, BB);
521       InsertPos = BB->end();
522     } else {
523       BB->insert(InsertPos, MI);
524     }
525
526     // Additional results must be an physical register def.
527     if (HasPhysRegOuts) {
528       for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
529         unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
530         if (Node->hasAnyUseOfValue(i))
531           EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
532       }
533     }
534     return;
535   }
536
537   switch (Node->getOpcode()) {
538   default:
539 #ifndef NDEBUG
540     Node->dump(DAG);
541 #endif
542     assert(0 && "This target-independent node should have been selected!");
543     break;
544   case ISD::EntryToken:
545     assert(0 && "EntryToken should have been excluded from the schedule!");
546     break;
547   case ISD::TokenFactor: // fall thru
548     break;
549   case ISD::CopyToReg: {
550     unsigned SrcReg;
551     SDValue SrcVal = Node->getOperand(2);
552     if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
553       SrcReg = R->getReg();
554     else
555       SrcReg = getVR(SrcVal, VRBaseMap);
556       
557     unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
558     if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
559       break;
560       
561     const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
562     // Get the register classes of the src/dst.
563     if (TargetRegisterInfo::isVirtualRegister(SrcReg))
564       SrcTRC = MRI.getRegClass(SrcReg);
565     else
566       SrcTRC = TRI->getPhysicalRegisterRegClass(SrcReg,SrcVal.getValueType());
567
568     if (TargetRegisterInfo::isVirtualRegister(DestReg))
569       DstTRC = MRI.getRegClass(DestReg);
570     else
571       DstTRC = TRI->getPhysicalRegisterRegClass(DestReg,
572                                             Node->getOperand(1).getValueType());
573
574     bool Emitted = TII->copyRegToReg(*BB, InsertPos, DestReg, SrcReg,
575                                      DstTRC, SrcTRC);
576     assert(Emitted && "Unable to issue a copy instruction!\n");
577     (void) Emitted;
578     break;
579   }
580   case ISD::CopyFromReg: {
581     unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
582     EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
583     break;
584   }
585   case ISD::INLINEASM: {
586     unsigned NumOps = Node->getNumOperands();
587     if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
588       --NumOps;  // Ignore the flag operand.
589       
590     // Create the inline asm machine instruction.
591     MachineInstr *MI = BuildMI(MF, Node->getDebugLoc(),
592                                TII->get(TargetInstrInfo::INLINEASM));
593
594     // Add the asm string as an external symbol operand.
595     const char *AsmStr =
596       cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
597     MI->addOperand(MachineOperand::CreateES(AsmStr));
598       
599     // Add all of the operand registers to the instruction.
600     for (unsigned i = 2; i != NumOps;) {
601       unsigned Flags =
602         cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
603       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
604         
605       MI->addOperand(MachineOperand::CreateImm(Flags));
606       ++i;  // Skip the ID value.
607         
608       switch (Flags & 7) {
609       default: assert(0 && "Bad flags!");
610       case 2:   // Def of register.
611         for (; NumVals; --NumVals, ++i) {
612           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
613           MI->addOperand(MachineOperand::CreateReg(Reg, true));
614         }
615         break;
616       case 6:   // Def of earlyclobber register.
617         for (; NumVals; --NumVals, ++i) {
618           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
619           MI->addOperand(MachineOperand::CreateReg(Reg, true, false, false, 
620                                                    false, 0, true));
621         }
622         break;
623       case 1:  // Use of register.
624       case 3:  // Immediate.
625       case 4:  // Addressing mode.
626         // The addressing mode has been selected, just add all of the
627         // operands to the machine instruction.
628         for (; NumVals; --NumVals, ++i)
629           AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
630         break;
631       }
632     }
633     BB->insert(InsertPos, MI);
634     break;
635   }
636   }
637 }
638
639 /// EmitSchedule - Emit the machine code in scheduled order.
640 MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
641   DenseMap<SDValue, unsigned> VRBaseMap;
642   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
643   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
644     SUnit *SU = Sequence[i];
645     if (!SU) {
646       // Null SUnit* is a noop.
647       EmitNoop();
648       continue;
649     }
650
651     // For pre-regalloc scheduling, create instructions corresponding to the
652     // SDNode and any flagged SDNodes and append them to the block.
653     if (!SU->getNode()) {
654       // Emit a copy.
655       EmitPhysRegCopy(SU, CopyVRBaseMap);
656       continue;
657     }
658
659     SmallVector<SDNode *, 4> FlaggedNodes;
660     for (SDNode *N = SU->getNode()->getFlaggedNode(); N;
661          N = N->getFlaggedNode())
662       FlaggedNodes.push_back(N);
663     while (!FlaggedNodes.empty()) {
664       EmitNode(FlaggedNodes.back(), SU->OrigNode != SU, SU->isCloned,VRBaseMap);
665       FlaggedNodes.pop_back();
666     }
667     EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned, VRBaseMap);
668   }
669
670   return BB;
671 }