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