Livein copy scheduling fixes: do not coalesce physical register copies, correctly...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAG.cpp
1 //===---- ScheduleDAG.cpp - Implement 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 a simple two pass scheduler.  The first pass attempts to push
11 // backward any lengthy instructions and critical paths.  The second pass packs
12 // instructions into semi-optimal time slots.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "pre-RA-sched"
17 #include "llvm/Constants.h"
18 #include "llvm/Type.h"
19 #include "llvm/CodeGen/ScheduleDAG.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunction.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/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 using namespace llvm;
32
33 STATISTIC(NumCommutes,   "Number of instructions commuted");
34
35 namespace {
36   static cl::opt<bool>
37   SchedLiveInCopies("schedule-livein-copies",
38                     cl::desc("Schedule copies of livein registers"),
39                     cl::init(false));
40 }
41
42 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
43                          const TargetMachine &tm)
44   : DAG(dag), BB(bb), TM(tm), MRI(BB->getParent()->getRegInfo()) {
45     TII = TM.getInstrInfo();
46     MF  = &DAG.getMachineFunction();
47     TRI = TM.getRegisterInfo();
48     ConstPool = BB->getParent()->getConstantPool();
49 }
50
51 /// CheckForPhysRegDependency - Check if the dependency between def and use of
52 /// a specified operand is a physical register dependency. If so, returns the
53 /// register and the cost of copying the register.
54 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
55                                       const TargetRegisterInfo *TRI, 
56                                       const TargetInstrInfo *TII,
57                                       unsigned &PhysReg, int &Cost) {
58   if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
59     return;
60
61   unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
62   if (TargetRegisterInfo::isVirtualRegister(Reg))
63     return;
64
65   unsigned ResNo = Use->getOperand(2).ResNo;
66   if (Def->isTargetOpcode()) {
67     const TargetInstrDesc &II = TII->get(Def->getTargetOpcode());
68     if (ResNo >= II.getNumDefs() &&
69         II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
70       PhysReg = Reg;
71       const TargetRegisterClass *RC =
72         TRI->getPhysicalRegisterRegClass(Reg, Def->getValueType(ResNo));
73       Cost = RC->getCopyCost();
74     }
75   }
76 }
77
78 SUnit *ScheduleDAG::Clone(SUnit *Old) {
79   SUnit *SU = NewSUnit(Old->Node);
80   SU->FlaggedNodes = Old->FlaggedNodes;
81   SU->InstanceNo = SUnitMap[Old->Node].size();
82   SU->Latency = Old->Latency;
83   SU->isTwoAddress = Old->isTwoAddress;
84   SU->isCommutable = Old->isCommutable;
85   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
86   SUnitMap[Old->Node].push_back(SU);
87   return SU;
88 }
89
90
91 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
92 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
93 /// together nodes with a single SUnit.
94 void ScheduleDAG::BuildSchedUnits() {
95   // Reserve entries in the vector for each of the SUnits we are creating.  This
96   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
97   // invalidated.
98   SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
99   
100   for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
101        E = DAG.allnodes_end(); NI != E; ++NI) {
102     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
103       continue;
104     
105     // If this node has already been processed, stop now.
106     if (SUnitMap[NI].size()) continue;
107     
108     SUnit *NodeSUnit = NewSUnit(NI);
109     
110     // See if anything is flagged to this node, if so, add them to flagged
111     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
112     // are required the be the last operand and result of a node.
113     
114     // Scan up, adding flagged preds to FlaggedNodes.
115     SDNode *N = NI;
116     if (N->getNumOperands() &&
117         N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
118       do {
119         N = N->getOperand(N->getNumOperands()-1).Val;
120         NodeSUnit->FlaggedNodes.push_back(N);
121         SUnitMap[N].push_back(NodeSUnit);
122       } while (N->getNumOperands() &&
123                N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
124       std::reverse(NodeSUnit->FlaggedNodes.begin(),
125                    NodeSUnit->FlaggedNodes.end());
126     }
127     
128     // Scan down, adding this node and any flagged succs to FlaggedNodes if they
129     // have a user of the flag operand.
130     N = NI;
131     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
132       SDOperand FlagVal(N, N->getNumValues()-1);
133       
134       // There are either zero or one users of the Flag result.
135       bool HasFlagUse = false;
136       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
137            UI != E; ++UI)
138         if (FlagVal.isOperandOf(*UI)) {
139           HasFlagUse = true;
140           NodeSUnit->FlaggedNodes.push_back(N);
141           SUnitMap[N].push_back(NodeSUnit);
142           N = *UI;
143           break;
144         }
145       if (!HasFlagUse) break;
146     }
147     
148     // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
149     // Update the SUnit
150     NodeSUnit->Node = N;
151     SUnitMap[N].push_back(NodeSUnit);
152
153     ComputeLatency(NodeSUnit);
154   }
155   
156   // Pass 2: add the preds, succs, etc.
157   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
158     SUnit *SU = &SUnits[su];
159     SDNode *MainNode = SU->Node;
160     
161     if (MainNode->isTargetOpcode()) {
162       unsigned Opc = MainNode->getTargetOpcode();
163       const TargetInstrDesc &TID = TII->get(Opc);
164       for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
165         if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
166           SU->isTwoAddress = true;
167           break;
168         }
169       }
170       if (TID.isCommutable())
171         SU->isCommutable = true;
172     }
173     
174     // Find all predecessors and successors of the group.
175     // Temporarily add N to make code simpler.
176     SU->FlaggedNodes.push_back(MainNode);
177     
178     for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
179       SDNode *N = SU->FlaggedNodes[n];
180       if (N->isTargetOpcode() &&
181           TII->get(N->getTargetOpcode()).getImplicitDefs() &&
182           CountResults(N) > TII->get(N->getTargetOpcode()).getNumDefs())
183         SU->hasPhysRegDefs = true;
184       
185       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
186         SDNode *OpN = N->getOperand(i).Val;
187         if (isPassiveNode(OpN)) continue;   // Not scheduled.
188         SUnit *OpSU = SUnitMap[OpN].front();
189         assert(OpSU && "Node has no SUnit!");
190         if (OpSU == SU) continue;           // In the same group.
191
192         MVT::ValueType OpVT = N->getOperand(i).getValueType();
193         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
194         bool isChain = OpVT == MVT::Other;
195
196         unsigned PhysReg = 0;
197         int Cost = 1;
198         // Determine if this is a physical register dependency.
199         CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
200         SU->addPred(OpSU, isChain, false, PhysReg, Cost);
201       }
202     }
203     
204     // Remove MainNode from FlaggedNodes again.
205     SU->FlaggedNodes.pop_back();
206   }
207   
208   return;
209 }
210
211 void ScheduleDAG::ComputeLatency(SUnit *SU) {
212   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
213   
214   // Compute the latency for the node.  We use the sum of the latencies for
215   // all nodes flagged together into this SUnit.
216   if (InstrItins.isEmpty()) {
217     // No latency information.
218     SU->Latency = 1;
219   } else {
220     SU->Latency = 0;
221     if (SU->Node->isTargetOpcode()) {
222       unsigned SchedClass =
223         TII->get(SU->Node->getTargetOpcode()).getSchedClass();
224       InstrStage *S = InstrItins.begin(SchedClass);
225       InstrStage *E = InstrItins.end(SchedClass);
226       for (; S != E; ++S)
227         SU->Latency += S->Cycles;
228     }
229     for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
230       SDNode *FNode = SU->FlaggedNodes[i];
231       if (FNode->isTargetOpcode()) {
232         unsigned SchedClass =TII->get(FNode->getTargetOpcode()).getSchedClass();
233         InstrStage *S = InstrItins.begin(SchedClass);
234         InstrStage *E = InstrItins.end(SchedClass);
235         for (; S != E; ++S)
236           SU->Latency += S->Cycles;
237       }
238     }
239   }
240 }
241
242 /// CalculateDepths - compute depths using algorithms for the longest
243 /// paths in the DAG
244 void ScheduleDAG::CalculateDepths() {
245   unsigned DAGSize = SUnits.size();
246   std::vector<unsigned> InDegree(DAGSize);
247   std::vector<SUnit*> WorkList;
248   WorkList.reserve(DAGSize);
249
250   // Initialize the data structures
251   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
252     SUnit *SU = &SUnits[i];
253     int NodeNum = SU->NodeNum;
254     unsigned Degree = SU->Preds.size();
255     InDegree[NodeNum] = Degree;
256     SU->Depth = 0;
257
258     // Is it a node without dependencies?
259     if (Degree == 0) {
260         assert(SU->Preds.empty() && "SUnit should have no predecessors");
261         // Collect leaf nodes
262         WorkList.push_back(SU);
263     }
264   }
265
266   // Process nodes in the topological order
267   while (!WorkList.empty()) {
268     SUnit *SU = WorkList.back();
269     WorkList.pop_back();
270     unsigned &SUDepth  = SU->Depth;
271
272     // Use dynamic programming:
273     // When current node is being processed, all of its dependencies
274     // are already processed.
275     // So, just iterate over all predecessors and take the longest path
276     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
277          I != E; ++I) {
278       unsigned PredDepth = I->Dep->Depth;
279       if (PredDepth+1 > SUDepth) {
280           SUDepth = PredDepth + 1;
281       }
282     }
283
284     // Update InDegrees of all nodes depending on current SUnit
285     for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
286          I != E; ++I) {
287       SUnit *SU = I->Dep;
288       if (!--InDegree[SU->NodeNum])
289         // If all dependencies of the node are processed already,
290         // then the longest path for the node can be computed now
291         WorkList.push_back(SU);
292     }
293   }
294 }
295
296 /// CalculateHeights - compute heights using algorithms for the longest
297 /// paths in the DAG
298 void ScheduleDAG::CalculateHeights() {
299   unsigned DAGSize = SUnits.size();
300   std::vector<unsigned> InDegree(DAGSize);
301   std::vector<SUnit*> WorkList;
302   WorkList.reserve(DAGSize);
303
304   // Initialize the data structures
305   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
306     SUnit *SU = &SUnits[i];
307     int NodeNum = SU->NodeNum;
308     unsigned Degree = SU->Succs.size();
309     InDegree[NodeNum] = Degree;
310     SU->Height = 0;
311
312     // Is it a node without dependencies?
313     if (Degree == 0) {
314         assert(SU->Succs.empty() && "Something wrong");
315         assert(WorkList.empty() && "Should be empty");
316         // Collect leaf nodes
317         WorkList.push_back(SU);
318     }
319   }
320
321   // Process nodes in the topological order
322   while (!WorkList.empty()) {
323     SUnit *SU = WorkList.back();
324     WorkList.pop_back();
325     unsigned &SUHeight  = SU->Height;
326
327     // Use dynamic programming:
328     // When current node is being processed, all of its dependencies
329     // are already processed.
330     // So, just iterate over all successors and take the longest path
331     for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
332          I != E; ++I) {
333       unsigned SuccHeight = I->Dep->Height;
334       if (SuccHeight+1 > SUHeight) {
335           SUHeight = SuccHeight + 1;
336       }
337     }
338
339     // Update InDegrees of all nodes depending on current SUnit
340     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
341          I != E; ++I) {
342       SUnit *SU = I->Dep;
343       if (!--InDegree[SU->NodeNum])
344         // If all dependencies of the node are processed already,
345         // then the longest path for the node can be computed now
346         WorkList.push_back(SU);
347     }
348   }
349 }
350
351 /// CountResults - The results of target nodes have register or immediate
352 /// operands first, then an optional chain, and optional flag operands (which do
353 /// not go into the resulting MachineInstr).
354 unsigned ScheduleDAG::CountResults(SDNode *Node) {
355   unsigned N = Node->getNumValues();
356   while (N && Node->getValueType(N - 1) == MVT::Flag)
357     --N;
358   if (N && Node->getValueType(N - 1) == MVT::Other)
359     --N;    // Skip over chain result.
360   return N;
361 }
362
363 /// CountOperands - The inputs to target nodes have any actual inputs first,
364 /// followed by special operands that describe memory references, then an
365 /// optional chain operand, then flag operands.  Compute the number of
366 /// actual operands that will go into the resulting MachineInstr.
367 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
368   unsigned N = ComputeMemOperandsEnd(Node);
369   while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
370     --N; // Ignore MemOperand nodes
371   return N;
372 }
373
374 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
375 /// operand
376 unsigned ScheduleDAG::ComputeMemOperandsEnd(SDNode *Node) {
377   unsigned N = Node->getNumOperands();
378   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
379     --N;
380   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
381     --N; // Ignore chain if it exists.
382   return N;
383 }
384
385 static const TargetRegisterClass *getInstrOperandRegClass(
386         const TargetRegisterInfo *TRI, 
387         const TargetInstrInfo *TII,
388         const TargetInstrDesc &II,
389         unsigned Op) {
390   if (Op >= II.getNumOperands()) {
391     assert(II.isVariadic() && "Invalid operand # of instruction");
392     return NULL;
393   }
394   if (II.OpInfo[Op].isLookupPtrRegClass())
395     return TII->getPointerRegClass();
396   return TRI->getRegClass(II.OpInfo[Op].RegClass);
397 }
398
399 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
400                                   unsigned InstanceNo, unsigned SrcReg,
401                                   DenseMap<SDOperand, unsigned> &VRBaseMap) {
402   unsigned VRBase = 0;
403   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
404     // Just use the input register directly!
405     if (InstanceNo > 0)
406       VRBaseMap.erase(SDOperand(Node, ResNo));
407     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
408     assert(isNew && "Node emitted out of order - early");
409     return;
410   }
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   bool MatchReg = true;
415   for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
416        UI != E; ++UI) {
417     SDNode *Use = *UI;
418     bool Match = true;
419     if (Use->getOpcode() == ISD::CopyToReg && 
420         Use->getOperand(2).Val == Node &&
421         Use->getOperand(2).ResNo == ResNo) {
422       unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
423       if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
424         VRBase = DestReg;
425         Match = false;
426       } else if (DestReg != SrcReg)
427         Match = false;
428     } else {
429       for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
430         SDOperand Op = Use->getOperand(i);
431         if (Op.Val != Node || Op.ResNo != ResNo)
432           continue;
433         MVT::ValueType VT = Node->getValueType(Op.ResNo);
434         if (VT != MVT::Other && VT != MVT::Flag)
435           Match = false;
436       }
437     }
438     MatchReg &= Match;
439     if (VRBase)
440       break;
441   }
442
443   const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
444   SrcRC = TRI->getPhysicalRegisterRegClass(SrcReg, Node->getValueType(ResNo));
445   
446   // Figure out the register class to create for the destreg.
447   if (VRBase) {
448     DstRC = MRI.getRegClass(VRBase);
449   } else {
450     DstRC = DAG.getTargetLoweringInfo()
451              .getRegClassFor(Node->getValueType(ResNo));
452   }
453     
454   // If all uses are reading from the src physical register and copying the
455   // register is either impossible or very expensive, then don't create a copy.
456   if (MatchReg && SrcRC->getCopyCost() < 0) {
457     VRBase = SrcReg;
458   } else {
459     // Create the reg, emit the copy.
460     VRBase = MRI.createVirtualRegister(DstRC);
461     TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, DstRC, SrcRC);
462   }
463
464   if (InstanceNo > 0)
465     VRBaseMap.erase(SDOperand(Node, ResNo));
466   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
467   assert(isNew && "Node emitted out of order - early");
468 }
469
470 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
471                                          MachineInstr *MI,
472                                          const TargetInstrDesc &II,
473                                      DenseMap<SDOperand, unsigned> &VRBaseMap) {
474   for (unsigned i = 0; i < II.getNumDefs(); ++i) {
475     // If the specific node value is only used by a CopyToReg and the dest reg
476     // is a vreg, use the CopyToReg'd destination register instead of creating
477     // a new vreg.
478     unsigned VRBase = 0;
479     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
480          UI != E; ++UI) {
481       SDNode *Use = *UI;
482       if (Use->getOpcode() == ISD::CopyToReg && 
483           Use->getOperand(2).Val == Node &&
484           Use->getOperand(2).ResNo == i) {
485         unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
486         if (TargetRegisterInfo::isVirtualRegister(Reg)) {
487           VRBase = Reg;
488           MI->addOperand(MachineOperand::CreateReg(Reg, true));
489           break;
490         }
491       }
492     }
493
494     // Create the result registers for this node and add the result regs to
495     // the machine instruction.
496     if (VRBase == 0) {
497       const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
498       assert(RC && "Isn't a register operand!");
499       VRBase = MRI.createVirtualRegister(RC);
500       MI->addOperand(MachineOperand::CreateReg(VRBase, true));
501     }
502
503     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
504     assert(isNew && "Node emitted out of order - early");
505   }
506 }
507
508 /// getVR - Return the virtual register corresponding to the specified result
509 /// of the specified node.
510 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
511   DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
512   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
513   return I->second;
514 }
515
516
517 /// AddOperand - Add the specified operand to the specified machine instr.  II
518 /// specifies the instruction information for the node, and IIOpNum is the
519 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
520 /// assertions only.
521 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
522                              unsigned IIOpNum,
523                              const TargetInstrDesc *II,
524                              DenseMap<SDOperand, unsigned> &VRBaseMap) {
525   if (Op.isTargetOpcode()) {
526     // Note that this case is redundant with the final else block, but we
527     // include it because it is the most common and it makes the logic
528     // simpler here.
529     assert(Op.getValueType() != MVT::Other &&
530            Op.getValueType() != MVT::Flag &&
531            "Chain and flag operands should occur at end of operand list!");
532     
533     // Get/emit the operand.
534     unsigned VReg = getVR(Op, VRBaseMap);
535     const TargetInstrDesc &TID = MI->getDesc();
536     bool isOptDef = (IIOpNum < TID.getNumOperands())
537       ? (TID.OpInfo[IIOpNum].isOptionalDef()) : false;
538     MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
539     
540     // Verify that it is right.
541     assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
542 #ifndef NDEBUG
543     if (II) {
544       // There may be no register class for this operand if it is a variadic
545       // argument (RC will be NULL in this case).  In this case, we just assume
546       // the regclass is ok.
547       const TargetRegisterClass *RC =
548                           getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
549       assert((RC || II->isVariadic()) && "Expected reg class info!");
550       const TargetRegisterClass *VRC = MRI.getRegClass(VReg);
551       if (RC && VRC != RC) {
552         cerr << "Register class of operand and regclass of use don't agree!\n";
553         cerr << "Operand = " << IIOpNum << "\n";
554         cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
555         cerr << "MI = "; MI->print(cerr);
556         cerr << "VReg = " << VReg << "\n";
557         cerr << "VReg RegClass     size = " << VRC->getSize()
558              << ", align = " << VRC->getAlignment() << "\n";
559         cerr << "Expected RegClass size = " << RC->getSize()
560              << ", align = " << RC->getAlignment() << "\n";
561         cerr << "Fatal error, aborting.\n";
562         abort();
563       }
564     }
565 #endif
566   } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
567     MI->addOperand(MachineOperand::CreateImm(C->getValue()));
568   } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
569     const Type *FType = MVT::getTypeForValueType(Op.getValueType());
570     ConstantFP *CFP = ConstantFP::get(FType, F->getValueAPF());
571     MI->addOperand(MachineOperand::CreateFPImm(CFP));
572   } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
573     MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
574   } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
575     MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
576   } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
577     MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
578   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
579     MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
580   } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
581     MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
582   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
583     int Offset = CP->getOffset();
584     unsigned Align = CP->getAlignment();
585     const Type *Type = CP->getType();
586     // MachineConstantPool wants an explicit alignment.
587     if (Align == 0) {
588       Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
589       if (Align == 0) {
590         // Alignment of vector types.  FIXME!
591         Align = TM.getTargetData()->getABITypeSize(Type);
592         Align = Log2_64(Align);
593       }
594     }
595     
596     unsigned Idx;
597     if (CP->isMachineConstantPoolEntry())
598       Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
599     else
600       Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
601     MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
602   } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
603     MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
604   } else {
605     assert(Op.getValueType() != MVT::Other &&
606            Op.getValueType() != MVT::Flag &&
607            "Chain and flag operands should occur at end of operand list!");
608     unsigned VReg = getVR(Op, VRBaseMap);
609     MI->addOperand(MachineOperand::CreateReg(VReg, false));
610     
611     // Verify that it is right.  Note that the reg class of the physreg and the
612     // vreg don't necessarily need to match, but the target copy insertion has
613     // to be able to handle it.  This handles things like copies from ST(0) to
614     // an FP vreg on x86.
615     assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
616     if (II && !II->isVariadic()) {
617       assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
618              "Don't have operand info for this instruction!");
619     }
620   }
621   
622 }
623
624 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MemOperand &MO) {
625   MI->addMemOperand(MO);
626 }
627
628 // Returns the Register Class of a subregister
629 static const TargetRegisterClass *getSubRegisterRegClass(
630         const TargetRegisterClass *TRC,
631         unsigned SubIdx) {
632   // Pick the register class of the subregister
633   TargetRegisterInfo::regclass_iterator I =
634     TRC->subregclasses_begin() + SubIdx-1;
635   assert(I < TRC->subregclasses_end() && 
636          "Invalid subregister index for register class");
637   return *I;
638 }
639
640 static const TargetRegisterClass *getSuperregRegisterClass(
641         const TargetRegisterClass *TRC,
642         unsigned SubIdx,
643         MVT::ValueType VT) {
644   // Pick the register class of the superegister for this type
645   for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
646          E = TRC->superregclasses_end(); I != E; ++I)
647     if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
648       return *I;
649   assert(false && "Couldn't find the register class");
650   return 0;
651 }
652
653 /// EmitSubregNode - Generate machine code for subreg nodes.
654 ///
655 void ScheduleDAG::EmitSubregNode(SDNode *Node, 
656                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
657   unsigned VRBase = 0;
658   unsigned Opc = Node->getTargetOpcode();
659   if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
660     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
661     // the CopyToReg'd destination register instead of creating a new vreg.
662     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
663          UI != E; ++UI) {
664       SDNode *Use = *UI;
665       if (Use->getOpcode() == ISD::CopyToReg && 
666           Use->getOperand(2).Val == Node) {
667         unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
668         if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
669           VRBase = DestReg;
670           break;
671         }
672       }
673     }
674     
675     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
676     
677     // TODO: If the node is a use of a CopyFromReg from a physical register
678     // fold the extract into the copy now
679
680     // Create the extract_subreg machine instruction.
681     MachineInstr *MI =
682       new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
683
684     // Figure out the register class to create for the destreg.
685     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
686     const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
687     const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
688
689     if (VRBase) {
690       // Grab the destination register
691       const TargetRegisterClass *DRC = MRI.getRegClass(VRBase);
692       assert(SRC && DRC && SRC == DRC && 
693              "Source subregister and destination must have the same class");
694     } else {
695       // Create the reg
696       assert(SRC && "Couldn't find source register class");
697       VRBase = MRI.createVirtualRegister(SRC);
698     }
699     
700     // Add def, source, and subreg index
701     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
702     AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
703     MI->addOperand(MachineOperand::CreateImm(SubIdx));
704     
705   } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
706     SDOperand N0 = Node->getOperand(0);
707     SDOperand N1 = Node->getOperand(1);
708     SDOperand N2 = Node->getOperand(2);
709     unsigned SubReg = getVR(N1, VRBaseMap);
710     unsigned SubIdx = cast<ConstantSDNode>(N2)->getValue();
711     
712     // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
713     // to allow coalescing in the allocator
714           
715     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
716     // the CopyToReg'd destination register instead of creating a new vreg.
717     // If the CopyToReg'd destination register is physical, then fold the
718     // insert into the copy
719     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
720          UI != E; ++UI) {
721       SDNode *Use = *UI;
722       if (Use->getOpcode() == ISD::CopyToReg && 
723           Use->getOperand(2).Val == Node) {
724         unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
725         if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
726           VRBase = DestReg;
727           break;
728         }
729       }
730     }
731     
732     // Create the insert_subreg machine instruction.
733     MachineInstr *MI =
734       new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
735       
736     // Figure out the register class to create for the destreg.
737     const TargetRegisterClass *TRC = 0;
738     if (VRBase) {
739       TRC = MRI.getRegClass(VRBase);
740     } else {
741       TRC = getSuperregRegisterClass(MRI.getRegClass(SubReg), SubIdx, 
742                                      Node->getValueType(0));
743       assert(TRC && "Couldn't determine register class for insert_subreg");
744       VRBase = MRI.createVirtualRegister(TRC); // Create the reg
745     }
746     
747     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
748     
749     // If N0 is a constant then it indicates the insert is being done
750     // into a target specific constant value, not a register.
751     if (const ConstantSDNode *SD = dyn_cast<ConstantSDNode>(N0))
752       MI->addOperand(MachineOperand::CreateImm(SD->getValue()));
753     else
754       AddOperand(MI, N0, 0, 0, VRBaseMap);
755     // Add the subregster being inserted
756     AddOperand(MI, N1, 0, 0, VRBaseMap);
757     MI->addOperand(MachineOperand::CreateImm(SubIdx));
758   } else
759     assert(0 && "Node is not a subreg insert or extract");
760      
761   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
762   assert(isNew && "Node emitted out of order - early");
763 }
764
765 /// EmitNode - Generate machine code for an node and needed dependencies.
766 ///
767 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
768                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
769   // If machine instruction
770   if (Node->isTargetOpcode()) {
771     unsigned Opc = Node->getTargetOpcode();
772     
773     // Handle subreg insert/extract specially
774     if (Opc == TargetInstrInfo::EXTRACT_SUBREG || 
775         Opc == TargetInstrInfo::INSERT_SUBREG) {
776       EmitSubregNode(Node, VRBaseMap);
777       return;
778     }
779     
780     const TargetInstrDesc &II = TII->get(Opc);
781
782     unsigned NumResults = CountResults(Node);
783     unsigned NodeOperands = CountOperands(Node);
784     unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
785     unsigned NumMIOperands = NodeOperands + NumResults;
786     bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
787                           II.getImplicitDefs() != 0;
788 #ifndef NDEBUG
789     assert((II.getNumOperands() == NumMIOperands ||
790             HasPhysRegOuts || II.isVariadic()) &&
791            "#operands for dag node doesn't match .td file!"); 
792 #endif
793
794     // Create the new machine instruction.
795     MachineInstr *MI = new MachineInstr(II);
796     
797     // Add result register values for things that are defined by this
798     // instruction.
799     if (NumResults)
800       CreateVirtualRegisters(Node, MI, II, VRBaseMap);
801     
802     // Emit all of the actual operands of this instruction, adding them to the
803     // instruction as appropriate.
804     for (unsigned i = 0; i != NodeOperands; ++i)
805       AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
806
807     // Emit all of the memory operands of this instruction
808     for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
809       AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
810
811     // Commute node if it has been determined to be profitable.
812     if (CommuteSet.count(Node)) {
813       MachineInstr *NewMI = TII->commuteInstruction(MI);
814       if (NewMI == 0)
815         DOUT << "Sched: COMMUTING FAILED!\n";
816       else {
817         DOUT << "Sched: COMMUTED TO: " << *NewMI;
818         if (MI != NewMI) {
819           delete MI;
820           MI = NewMI;
821         }
822         ++NumCommutes;
823       }
824     }
825
826     if (II.usesCustomDAGSchedInsertionHook())
827       // Insert this instruction into the basic block using a target
828       // specific inserter which may returns a new basic block.
829       BB = DAG.getTargetLoweringInfo().EmitInstrWithCustomInserter(MI, BB);
830     else
831       BB->push_back(MI);
832
833     // Additional results must be an physical register def.
834     if (HasPhysRegOuts) {
835       for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
836         unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
837         if (Node->hasAnyUseOfValue(i))
838           EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
839       }
840     }
841   } else {
842     switch (Node->getOpcode()) {
843     default:
844 #ifndef NDEBUG
845       Node->dump(&DAG);
846 #endif
847       assert(0 && "This target-independent node should have been selected!");
848     case ISD::EntryToken: // fall thru
849     case ISD::TokenFactor:
850     case ISD::LABEL:
851     case ISD::DECLARE:
852     case ISD::SRCVALUE:
853       break;
854     case ISD::CopyToReg: {
855       unsigned SrcReg;
856       SDOperand SrcVal = Node->getOperand(2);
857       if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
858         SrcReg = R->getReg();
859       else
860         SrcReg = getVR(SrcVal, VRBaseMap);
861       
862       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
863       if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
864         break;
865       
866       const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
867       // Get the register classes of the src/dst.
868       if (TargetRegisterInfo::isVirtualRegister(SrcReg))
869         SrcTRC = MRI.getRegClass(SrcReg);
870       else
871         SrcTRC = TRI->getPhysicalRegisterRegClass(SrcReg,SrcVal.getValueType());
872
873       if (TargetRegisterInfo::isVirtualRegister(DestReg))
874         DstTRC = MRI.getRegClass(DestReg);
875       else
876         DstTRC = TRI->getPhysicalRegisterRegClass(DestReg,
877                                             Node->getOperand(1).getValueType());
878       TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
879       break;
880     }
881     case ISD::CopyFromReg: {
882       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
883       EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
884       break;
885     }
886     case ISD::INLINEASM: {
887       unsigned NumOps = Node->getNumOperands();
888       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
889         --NumOps;  // Ignore the flag operand.
890       
891       // Create the inline asm machine instruction.
892       MachineInstr *MI =
893         new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
894
895       // Add the asm string as an external symbol operand.
896       const char *AsmStr =
897         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
898       MI->addOperand(MachineOperand::CreateES(AsmStr));
899       
900       // Add all of the operand registers to the instruction.
901       for (unsigned i = 2; i != NumOps;) {
902         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
903         unsigned NumVals = Flags >> 3;
904         
905         MI->addOperand(MachineOperand::CreateImm(Flags));
906         ++i;  // Skip the ID value.
907         
908         switch (Flags & 7) {
909         default: assert(0 && "Bad flags!");
910         case 1:  // Use of register.
911           for (; NumVals; --NumVals, ++i) {
912             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
913             MI->addOperand(MachineOperand::CreateReg(Reg, false));
914           }
915           break;
916         case 2:   // Def of register.
917           for (; NumVals; --NumVals, ++i) {
918             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
919             MI->addOperand(MachineOperand::CreateReg(Reg, true));
920           }
921           break;
922         case 3: { // Immediate.
923           for (; NumVals; --NumVals, ++i) {
924             if (ConstantSDNode *CS =
925                    dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
926               MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
927             } else if (GlobalAddressSDNode *GA = 
928                   dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
929               MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
930                                                       GA->getOffset()));
931             } else {
932               BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
933               MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
934             }
935           }
936           break;
937         }
938         case 4:  // Addressing mode.
939           // The addressing mode has been selected, just add all of the
940           // operands to the machine instruction.
941           for (; NumVals; --NumVals, ++i)
942             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
943           break;
944         }
945       }
946       break;
947     }
948     }
949   }
950 }
951
952 void ScheduleDAG::EmitNoop() {
953   TII->insertNoop(*BB, BB->end());
954 }
955
956 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
957                                   DenseMap<SUnit*, unsigned> &VRBaseMap) {
958   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
959        I != E; ++I) {
960     if (I->isCtrl) continue;  // ignore chain preds
961     if (!I->Dep->Node) {
962       // Copy to physical register.
963       DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
964       assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
965       // Find the destination physical register.
966       unsigned Reg = 0;
967       for (SUnit::const_succ_iterator II = SU->Succs.begin(),
968              EE = SU->Succs.end(); II != EE; ++II) {
969         if (I->Reg) {
970           Reg = I->Reg;
971           break;
972         }
973       }
974       assert(I->Reg && "Unknown physical register!");
975       TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
976                         SU->CopyDstRC, SU->CopySrcRC);
977     } else {
978       // Copy from physical register.
979       assert(I->Reg && "Unknown physical register!");
980       unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
981       bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
982       assert(isNew && "Node emitted out of order - early");
983       TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
984                         SU->CopyDstRC, SU->CopySrcRC);
985     }
986     break;
987   }
988 }
989
990 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
991 /// physical register has only a single copy use, then coalesced the copy
992 /// if possible.
993 void ScheduleDAG::EmitLiveInCopy(MachineBasicBlock *MBB,
994                                  MachineBasicBlock::iterator &InsertPos,
995                                  unsigned VirtReg, unsigned PhysReg,
996                                  const TargetRegisterClass *RC,
997                                  DenseMap<MachineInstr*, unsigned> &CopyRegMap){
998   unsigned NumUses = 0;
999   MachineInstr *UseMI = NULL;
1000   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
1001          UE = MRI.use_end(); UI != UE; ++UI) {
1002     UseMI = &*UI;
1003     if (++NumUses > 1)
1004       break;
1005   }
1006
1007   // If the number of uses is not one, or the use is not a move instruction,
1008   // don't coalesce. Also, only coalesce away a virtual register to virtual
1009   // register copy.
1010   bool Coalesced = false;
1011   unsigned SrcReg, DstReg;
1012   if (NumUses == 1 &&
1013       TII->isMoveInstr(*UseMI, SrcReg, DstReg) &&
1014       TargetRegisterInfo::isVirtualRegister(DstReg)) {
1015     VirtReg = DstReg;
1016     Coalesced = true;
1017   }
1018
1019   // Now find an ideal location to insert the copy.
1020   MachineBasicBlock::iterator Pos = InsertPos;
1021   while (Pos != MBB->begin()) {
1022     MachineInstr *PrevMI = prior(Pos);
1023     DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
1024     // copyRegToReg might emit multiple instructions to do a copy.
1025     unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
1026     if (CopyDstReg && !TRI->regsOverlap(CopyDstReg, PhysReg))
1027       // This is what the BB looks like right now:
1028       // r1024 = mov r0
1029       // ...
1030       // r1    = mov r1024
1031       //
1032       // We want to insert "r1025 = mov r1". Inserting this copy below the
1033       // move to r1024 makes it impossible for that move to be coalesced.
1034       //
1035       // r1025 = mov r1
1036       // r1024 = mov r0
1037       // ...
1038       // r1    = mov 1024
1039       // r2    = mov 1025
1040       break; // Woot! Found a good location.
1041     --Pos;
1042   }
1043
1044   TII->copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
1045   CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
1046   if (Coalesced) {
1047     if (&*InsertPos == UseMI) ++InsertPos;
1048     MBB->erase(UseMI);
1049   }
1050 }
1051
1052 /// EmitLiveInCopies - If this is the first basic block in the function,
1053 /// and if it has live ins that need to be copied into vregs, emit the
1054 /// copies into the top of the block.
1055 void ScheduleDAG::EmitLiveInCopies(MachineBasicBlock *MBB) {
1056   DenseMap<MachineInstr*, unsigned> CopyRegMap;
1057   MachineBasicBlock::iterator InsertPos = MBB->begin();
1058   for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1059          E = MRI.livein_end(); LI != E; ++LI)
1060     if (LI->second) {
1061       const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1062       EmitLiveInCopy(MBB, InsertPos, LI->second, LI->first, RC, CopyRegMap);
1063     }
1064 }
1065
1066 /// EmitSchedule - Emit the machine code in scheduled order.
1067 void ScheduleDAG::EmitSchedule() {
1068   bool isEntryBB = &MF->front() == BB;
1069
1070   if (isEntryBB && !SchedLiveInCopies) {
1071     // If this is the first basic block in the function, and if it has live ins
1072     // that need to be copied into vregs, emit the copies into the top of the
1073     // block before emitting the code for the block.
1074     for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1075            E = MRI.livein_end(); LI != E; ++LI)
1076       if (LI->second) {
1077         const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1078         TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
1079                           LI->first, RC, RC);
1080       }
1081   }
1082
1083   // Finally, emit the code for all of the scheduled instructions.
1084   DenseMap<SDOperand, unsigned> VRBaseMap;
1085   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
1086   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1087     if (SUnit *SU = Sequence[i]) {
1088       for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
1089         EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
1090       if (SU->Node)
1091         EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
1092       else
1093         EmitCrossRCCopy(SU, CopyVRBaseMap);
1094     } else {
1095       // Null SUnit* is a noop.
1096       EmitNoop();
1097     }
1098   }
1099
1100   if (isEntryBB && SchedLiveInCopies)
1101     EmitLiveInCopies(MF->begin());
1102 }
1103
1104 /// dump - dump the schedule.
1105 void ScheduleDAG::dumpSchedule() const {
1106   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1107     if (SUnit *SU = Sequence[i])
1108       SU->dump(&DAG);
1109     else
1110       cerr << "**** NOOP ****\n";
1111   }
1112 }
1113
1114
1115 /// Run - perform scheduling.
1116 ///
1117 MachineBasicBlock *ScheduleDAG::Run() {
1118   Schedule();
1119   return BB;
1120 }
1121
1122 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
1123 /// a group of nodes flagged together.
1124 void SUnit::dump(const SelectionDAG *G) const {
1125   cerr << "SU(" << NodeNum << "): ";
1126   if (Node)
1127     Node->dump(G);
1128   else
1129     cerr << "CROSS RC COPY ";
1130   cerr << "\n";
1131   if (FlaggedNodes.size() != 0) {
1132     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
1133       cerr << "    ";
1134       FlaggedNodes[i]->dump(G);
1135       cerr << "\n";
1136     }
1137   }
1138 }
1139
1140 void SUnit::dumpAll(const SelectionDAG *G) const {
1141   dump(G);
1142
1143   cerr << "  # preds left       : " << NumPredsLeft << "\n";
1144   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
1145   cerr << "  Latency            : " << Latency << "\n";
1146   cerr << "  Depth              : " << Depth << "\n";
1147   cerr << "  Height             : " << Height << "\n";
1148
1149   if (Preds.size() != 0) {
1150     cerr << "  Predecessors:\n";
1151     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
1152          I != E; ++I) {
1153       if (I->isCtrl)
1154         cerr << "   ch  #";
1155       else
1156         cerr << "   val #";
1157       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1158       if (I->isSpecial)
1159         cerr << " *";
1160       cerr << "\n";
1161     }
1162   }
1163   if (Succs.size() != 0) {
1164     cerr << "  Successors:\n";
1165     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1166          I != E; ++I) {
1167       if (I->isCtrl)
1168         cerr << "   ch  #";
1169       else
1170         cerr << "   val #";
1171       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1172       if (I->isSpecial)
1173         cerr << " *";
1174       cerr << "\n";
1175     }
1176   }
1177   cerr << "\n";
1178 }