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