Backed out 53031.
[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     return;
228   }
229
230   SU->Latency = 0;
231   if (SU->Node->isTargetOpcode()) {
232     unsigned SchedClass = TII->get(SU->Node->getTargetOpcode()).getSchedClass();
233     const InstrStage *S = InstrItins.begin(SchedClass);
234     const InstrStage *E = InstrItins.end(SchedClass);
235     for (; S != E; ++S)
236       SU->Latency += S->Cycles;
237   }
238   for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
239     SDNode *FNode = SU->FlaggedNodes[i];
240     if (FNode->isTargetOpcode()) {
241       unsigned SchedClass = TII->get(FNode->getTargetOpcode()).getSchedClass();
242       const InstrStage *S = InstrItins.begin(SchedClass);
243       const InstrStage *E = InstrItins.end(SchedClass);
244       for (; S != E; ++S)
245         SU->Latency += S->Cycles;
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 /// getInstrOperandRegClass - Return register class of the operand of an
394 /// instruction of the specified TargetInstrDesc.
395 static const TargetRegisterClass*
396 getInstrOperandRegClass(const TargetRegisterInfo *TRI, 
397                         const TargetInstrInfo *TII, const TargetInstrDesc &II,
398                         unsigned Op) {
399   if (Op >= II.getNumOperands()) {
400     assert(II.isVariadic() && "Invalid operand # of instruction");
401     return NULL;
402   }
403   if (II.OpInfo[Op].isLookupPtrRegClass())
404     return TII->getPointerRegClass();
405   return TRI->getRegClass(II.OpInfo[Op].RegClass);
406 }
407
408 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
409 /// implicit physical register output.
410 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
411                                   bool IsClone, unsigned SrcReg,
412                                   DenseMap<SDOperand, unsigned> &VRBaseMap) {
413   unsigned VRBase = 0;
414   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
415     // Just use the input register directly!
416     if (IsClone)
417       VRBaseMap.erase(SDOperand(Node, ResNo));
418     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
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 *Use = UI->getUser();
430     bool Match = true;
431     if (Use->getOpcode() == ISD::CopyToReg && 
432         Use->getOperand(2).Val == Node &&
433         Use->getOperand(2).ResNo == ResNo) {
434       unsigned DestReg = cast<RegisterSDNode>(Use->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 = Use->getNumOperands(); i != e; ++i) {
442         SDOperand Op = Use->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   if (IsClone)
476     VRBaseMap.erase(SDOperand(Node, ResNo));
477   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
478   isNew = isNew; // Silence compiler warning.
479   assert(isNew && "Node emitted out of order - early");
480 }
481
482 /// getDstOfCopyToRegUse - If the only use of the specified result number of
483 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
484 unsigned ScheduleDAG::getDstOfOnlyCopyToRegUse(SDNode *Node,
485                                                unsigned ResNo) const {
486   if (!Node->hasOneUse())
487     return 0;
488
489   SDNode *Use = Node->use_begin()->getUser();
490   if (Use->getOpcode() == ISD::CopyToReg && 
491       Use->getOperand(2).Val == Node &&
492       Use->getOperand(2).ResNo == ResNo) {
493     unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
494     if (TargetRegisterInfo::isVirtualRegister(Reg))
495       return Reg;
496   }
497   return 0;
498 }
499
500 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
501                                  const TargetInstrDesc &II,
502                                  DenseMap<SDOperand, unsigned> &VRBaseMap) {
503   assert(Node->getTargetOpcode() != TargetInstrInfo::IMPLICIT_DEF &&
504          "IMPLICIT_DEF should have been handled as a special case elsewhere!");
505
506   for (unsigned i = 0; i < II.getNumDefs(); ++i) {
507     // If the specific node value is only used by a CopyToReg and the dest reg
508     // is a vreg, use the CopyToReg'd destination register instead of creating
509     // a new vreg.
510     unsigned VRBase = 0;
511     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
512          UI != E; ++UI) {
513       SDNode *Use = UI->getUser();
514       if (Use->getOpcode() == ISD::CopyToReg && 
515           Use->getOperand(2).Val == Node &&
516           Use->getOperand(2).ResNo == i) {
517         unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
518         if (TargetRegisterInfo::isVirtualRegister(Reg)) {
519           VRBase = Reg;
520           MI->addOperand(MachineOperand::CreateReg(Reg, true));
521           break;
522         }
523       }
524     }
525
526     // Create the result registers for this node and add the result regs to
527     // the machine instruction.
528     if (VRBase == 0) {
529       const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
530       assert(RC && "Isn't a register operand!");
531       VRBase = MRI.createVirtualRegister(RC);
532       MI->addOperand(MachineOperand::CreateReg(VRBase, true));
533     }
534
535     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
536     isNew = isNew; // Silence compiler warning.
537     assert(isNew && "Node emitted out of order - early");
538   }
539 }
540
541 /// getVR - Return the virtual register corresponding to the specified result
542 /// of the specified node.
543 unsigned ScheduleDAG::getVR(SDOperand Op,
544                             DenseMap<SDOperand, unsigned> &VRBaseMap) {
545   if (Op.isTargetOpcode() &&
546       Op.getTargetOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
547     // Add an IMPLICIT_DEF instruction before every use.
548     unsigned VReg = getDstOfOnlyCopyToRegUse(Op.Val, Op.ResNo);
549     // IMPLICIT_DEF can produce any type of result so its TargetInstrDesc
550     // does not include operand register class info.
551     if (!VReg) {
552       const TargetRegisterClass *RC = TLI->getRegClassFor(Op.getValueType());
553       VReg = MRI.createVirtualRegister(RC);
554     }
555     BuildMI(BB, TII->get(TargetInstrInfo::IMPLICIT_DEF), VReg);
556     return VReg;
557   }
558
559   DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
560   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
561   return I->second;
562 }
563
564
565 /// AddOperand - Add the specified operand to the specified machine instr.  II
566 /// specifies the instruction information for the node, and IIOpNum is the
567 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
568 /// assertions only.
569 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
570                              unsigned IIOpNum,
571                              const TargetInstrDesc *II,
572                              DenseMap<SDOperand, unsigned> &VRBaseMap) {
573   if (Op.isTargetOpcode()) {
574     // Note that this case is redundant with the final else block, but we
575     // include it because it is the most common and it makes the logic
576     // simpler here.
577     assert(Op.getValueType() != MVT::Other &&
578            Op.getValueType() != MVT::Flag &&
579            "Chain and flag operands should occur at end of operand list!");
580     // Get/emit the operand.
581     unsigned VReg = getVR(Op, VRBaseMap);
582     const TargetInstrDesc &TID = MI->getDesc();
583     bool isOptDef = IIOpNum < TID.getNumOperands() &&
584       TID.OpInfo[IIOpNum].isOptionalDef();
585     MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
586     
587     // Verify that it is right.
588     assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
589 #ifndef NDEBUG
590     if (II) {
591       // There may be no register class for this operand if it is a variadic
592       // argument (RC will be NULL in this case).  In this case, we just assume
593       // the regclass is ok.
594       const TargetRegisterClass *RC =
595                           getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
596       assert((RC || II->isVariadic()) && "Expected reg class info!");
597       const TargetRegisterClass *VRC = MRI.getRegClass(VReg);
598       if (RC && VRC != RC) {
599         cerr << "Register class of operand and regclass of use don't agree!\n";
600         cerr << "Operand = " << IIOpNum << "\n";
601         cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
602         cerr << "MI = "; MI->print(cerr);
603         cerr << "VReg = " << VReg << "\n";
604         cerr << "VReg RegClass     size = " << VRC->getSize()
605              << ", align = " << VRC->getAlignment() << "\n";
606         cerr << "Expected RegClass size = " << RC->getSize()
607              << ", align = " << RC->getAlignment() << "\n";
608         cerr << "Fatal error, aborting.\n";
609         abort();
610       }
611     }
612 #endif
613   } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
614     MI->addOperand(MachineOperand::CreateImm(C->getValue()));
615   } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
616     ConstantFP *CFP = ConstantFP::get(F->getValueAPF());
617     MI->addOperand(MachineOperand::CreateFPImm(CFP));
618   } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
619     MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
620   } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
621     MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
622   } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
623     MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
624   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
625     MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
626   } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
627     MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
628   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
629     int Offset = CP->getOffset();
630     unsigned Align = CP->getAlignment();
631     const Type *Type = CP->getType();
632     // MachineConstantPool wants an explicit alignment.
633     if (Align == 0) {
634       Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
635       if (Align == 0) {
636         // Alignment of vector types.  FIXME!
637         Align = TM.getTargetData()->getABITypeSize(Type);
638         Align = Log2_64(Align);
639       }
640     }
641     
642     unsigned Idx;
643     if (CP->isMachineConstantPoolEntry())
644       Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
645     else
646       Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
647     MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
648   } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
649     MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
650   } else {
651     assert(Op.getValueType() != MVT::Other &&
652            Op.getValueType() != MVT::Flag &&
653            "Chain and flag operands should occur at end of operand list!");
654     unsigned VReg = getVR(Op, VRBaseMap);
655     MI->addOperand(MachineOperand::CreateReg(VReg, false));
656     
657     // Verify that it is right.  Note that the reg class of the physreg and the
658     // vreg don't necessarily need to match, but the target copy insertion has
659     // to be able to handle it.  This handles things like copies from ST(0) to
660     // an FP vreg on x86.
661     assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
662     if (II && !II->isVariadic()) {
663       assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
664              "Don't have operand info for this instruction!");
665     }
666   }  
667 }
668
669 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO) {
670   MI->addMemOperand(MO);
671 }
672
673 /// getSubRegisterRegClass - Returns the register class of specified register
674 /// class' "SubIdx"'th sub-register class.
675 static const TargetRegisterClass*
676 getSubRegisterRegClass(const TargetRegisterClass *TRC, unsigned SubIdx) {
677   // Pick the register class of the subregister
678   TargetRegisterInfo::regclass_iterator I =
679     TRC->subregclasses_begin() + SubIdx-1;
680   assert(I < TRC->subregclasses_end() && 
681          "Invalid subregister index for register class");
682   return *I;
683 }
684
685 /// getSuperRegisterRegClass - Returns the register class of a superreg A whose
686 /// "SubIdx"'th sub-register class is the specified register class and whose
687 /// type matches the specified type.
688 static const TargetRegisterClass*
689 getSuperRegisterRegClass(const TargetRegisterClass *TRC,
690                          unsigned SubIdx, MVT VT) {
691   // Pick the register class of the superegister for this type
692   for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
693          E = TRC->superregclasses_end(); I != E; ++I)
694     if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
695       return *I;
696   assert(false && "Couldn't find the register class");
697   return 0;
698 }
699
700 /// EmitSubregNode - Generate machine code for subreg nodes.
701 ///
702 void ScheduleDAG::EmitSubregNode(SDNode *Node, 
703                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
704   unsigned VRBase = 0;
705   unsigned Opc = Node->getTargetOpcode();
706   
707   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
708   // the CopyToReg'd destination register instead of creating a new vreg.
709   for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
710        UI != E; ++UI) {
711     SDNode *Use = UI->getUser();
712     if (Use->getOpcode() == ISD::CopyToReg && 
713         Use->getOperand(2).Val == Node) {
714       unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
715       if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
716         VRBase = DestReg;
717         break;
718       }
719     }
720   }
721   
722   if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
723     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
724
725     // Create the extract_subreg machine instruction.
726     MachineInstr *MI = BuildMI(TII->get(TargetInstrInfo::EXTRACT_SUBREG));
727
728     // Figure out the register class to create for the destreg.
729     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
730     const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
731     const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
732
733     if (VRBase) {
734       // Grab the destination register
735 #ifndef NDEBUG
736       const TargetRegisterClass *DRC = MRI.getRegClass(VRBase);
737       assert(SRC && DRC && SRC == DRC && 
738              "Source subregister and destination must have the same class");
739 #endif
740     } else {
741       // Create the reg
742       assert(SRC && "Couldn't find source register class");
743       VRBase = MRI.createVirtualRegister(SRC);
744     }
745     
746     // Add def, source, and subreg index
747     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
748     AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
749     MI->addOperand(MachineOperand::CreateImm(SubIdx));
750     BB->push_back(MI);    
751   } else if (Opc == TargetInstrInfo::INSERT_SUBREG ||
752              Opc == TargetInstrInfo::SUBREG_TO_REG) {
753     SDOperand N0 = Node->getOperand(0);
754     SDOperand N1 = Node->getOperand(1);
755     SDOperand N2 = Node->getOperand(2);
756     unsigned SubReg = getVR(N1, VRBaseMap);
757     unsigned SubIdx = cast<ConstantSDNode>(N2)->getValue();
758     
759       
760     // Figure out the register class to create for the destreg.
761     const TargetRegisterClass *TRC = 0;
762     if (VRBase) {
763       TRC = MRI.getRegClass(VRBase);
764     } else {
765       TRC = getSuperRegisterRegClass(MRI.getRegClass(SubReg), SubIdx, 
766                                      Node->getValueType(0));
767       assert(TRC && "Couldn't determine register class for insert_subreg");
768       VRBase = MRI.createVirtualRegister(TRC); // Create the reg
769     }
770     
771     // Create the insert_subreg or subreg_to_reg machine instruction.
772     MachineInstr *MI = BuildMI(TII->get(Opc));
773     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
774     
775     // If creating a subreg_to_reg, then the first input operand
776     // is an implicit value immediate, otherwise it's a register
777     if (Opc == TargetInstrInfo::SUBREG_TO_REG) {
778       const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
779       MI->addOperand(MachineOperand::CreateImm(SD->getValue()));
780     } else
781       AddOperand(MI, N0, 0, 0, VRBaseMap);
782     // Add the subregster being inserted
783     AddOperand(MI, N1, 0, 0, VRBaseMap);
784     MI->addOperand(MachineOperand::CreateImm(SubIdx));
785     BB->push_back(MI);
786   } else
787     assert(0 && "Node is not insert_subreg, extract_subreg, or subreg_to_reg");
788      
789   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
790   isNew = isNew; // Silence compiler warning.
791   assert(isNew && "Node emitted out of order - early");
792 }
793
794 /// EmitNode - Generate machine code for an node and needed dependencies.
795 ///
796 void ScheduleDAG::EmitNode(SDNode *Node, bool IsClone,
797                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
798   // If machine instruction
799   if (Node->isTargetOpcode()) {
800     unsigned Opc = Node->getTargetOpcode();
801     
802     // Handle subreg insert/extract specially
803     if (Opc == TargetInstrInfo::EXTRACT_SUBREG || 
804         Opc == TargetInstrInfo::INSERT_SUBREG ||
805         Opc == TargetInstrInfo::SUBREG_TO_REG) {
806       EmitSubregNode(Node, VRBaseMap);
807       return;
808     }
809
810     if (Opc == TargetInstrInfo::IMPLICIT_DEF)
811       // We want a unique VR for each IMPLICIT_DEF use.
812       return;
813     
814     const TargetInstrDesc &II = TII->get(Opc);
815     unsigned NumResults = CountResults(Node);
816     unsigned NodeOperands = CountOperands(Node);
817     unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
818     bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
819                           II.getImplicitDefs() != 0;
820 #ifndef NDEBUG
821     unsigned NumMIOperands = NodeOperands + NumResults;
822     assert((II.getNumOperands() == NumMIOperands ||
823             HasPhysRegOuts || II.isVariadic()) &&
824            "#operands for dag node doesn't match .td file!"); 
825 #endif
826
827     // Create the new machine instruction.
828     MachineInstr *MI = BuildMI(II);
829     
830     // Add result register values for things that are defined by this
831     // instruction.
832     if (NumResults)
833       CreateVirtualRegisters(Node, MI, II, VRBaseMap);
834     
835     // Emit all of the actual operands of this instruction, adding them to the
836     // instruction as appropriate.
837     for (unsigned i = 0; i != NodeOperands; ++i)
838       AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
839
840     // Emit all of the memory operands of this instruction
841     for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
842       AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
843
844     // Commute node if it has been determined to be profitable.
845     if (CommuteSet.count(Node)) {
846       MachineInstr *NewMI = TII->commuteInstruction(MI);
847       if (NewMI == 0)
848         DOUT << "Sched: COMMUTING FAILED!\n";
849       else {
850         DOUT << "Sched: COMMUTED TO: " << *NewMI;
851         if (MI != NewMI) {
852           delete MI;
853           MI = NewMI;
854         }
855         ++NumCommutes;
856       }
857     }
858
859     if (II.usesCustomDAGSchedInsertionHook())
860       // Insert this instruction into the basic block using a target
861       // specific inserter which may returns a new basic block.
862       BB = TLI->EmitInstrWithCustomInserter(MI, BB);
863     else
864       BB->push_back(MI);
865
866     // Additional results must be an physical register def.
867     if (HasPhysRegOuts) {
868       for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
869         unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
870         if (Node->hasAnyUseOfValue(i))
871           EmitCopyFromReg(Node, i, IsClone, Reg, VRBaseMap);
872       }
873     }
874     return;
875   }
876
877   switch (Node->getOpcode()) {
878   default:
879 #ifndef NDEBUG
880     Node->dump(&DAG);
881 #endif
882     assert(0 && "This target-independent node should have been selected!");
883     break;
884   case ISD::EntryToken:
885     assert(0 && "EntryToken should have been excluded from the schedule!");
886     break;
887   case ISD::TokenFactor: // fall thru
888     break;
889   case ISD::CopyToReg: {
890     unsigned SrcReg;
891     SDOperand SrcVal = Node->getOperand(2);
892     if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
893       SrcReg = R->getReg();
894     else
895       SrcReg = getVR(SrcVal, VRBaseMap);
896       
897     unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
898     if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
899       break;
900       
901     const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
902     // Get the register classes of the src/dst.
903     if (TargetRegisterInfo::isVirtualRegister(SrcReg))
904       SrcTRC = MRI.getRegClass(SrcReg);
905     else
906       SrcTRC = TRI->getPhysicalRegisterRegClass(SrcReg,SrcVal.getValueType());
907
908     if (TargetRegisterInfo::isVirtualRegister(DestReg))
909       DstTRC = MRI.getRegClass(DestReg);
910     else
911       DstTRC = TRI->getPhysicalRegisterRegClass(DestReg,
912                                             Node->getOperand(1).getValueType());
913     TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
914     break;
915   }
916   case ISD::CopyFromReg: {
917     unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
918     EmitCopyFromReg(Node, 0, IsClone, SrcReg, VRBaseMap);
919     break;
920   }
921   case ISD::INLINEASM: {
922     unsigned NumOps = Node->getNumOperands();
923     if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
924       --NumOps;  // Ignore the flag operand.
925       
926     // Create the inline asm machine instruction.
927     MachineInstr *MI = BuildMI(TII->get(TargetInstrInfo::INLINEASM));
928
929     // Add the asm string as an external symbol operand.
930     const char *AsmStr =
931       cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
932     MI->addOperand(MachineOperand::CreateES(AsmStr));
933       
934     // Add all of the operand registers to the instruction.
935     for (unsigned i = 2; i != NumOps;) {
936       unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
937       unsigned NumVals = Flags >> 3;
938         
939       MI->addOperand(MachineOperand::CreateImm(Flags));
940       ++i;  // Skip the ID value.
941         
942       switch (Flags & 7) {
943       default: assert(0 && "Bad flags!");
944       case 2:   // Def of register.
945         for (; NumVals; --NumVals, ++i) {
946           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
947           MI->addOperand(MachineOperand::CreateReg(Reg, true));
948         }
949         break;
950       case 1:  // Use of register.
951       case 3:  // Immediate.
952       case 4:  // Addressing mode.
953         // The addressing mode has been selected, just add all of the
954         // operands to the machine instruction.
955         for (; NumVals; --NumVals, ++i)
956           AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
957         break;
958       }
959     }
960     BB->push_back(MI);
961     break;
962   }
963   }
964 }
965
966 void ScheduleDAG::EmitNoop() {
967   TII->insertNoop(*BB, BB->end());
968 }
969
970 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
971                                   DenseMap<SUnit*, unsigned> &VRBaseMap) {
972   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
973        I != E; ++I) {
974     if (I->isCtrl) continue;  // ignore chain preds
975     if (!I->Dep->Node) {
976       // Copy to physical register.
977       DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
978       assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
979       // Find the destination physical register.
980       unsigned Reg = 0;
981       for (SUnit::const_succ_iterator II = SU->Succs.begin(),
982              EE = SU->Succs.end(); II != EE; ++II) {
983         if (I->Reg) {
984           Reg = I->Reg;
985           break;
986         }
987       }
988       assert(I->Reg && "Unknown physical register!");
989       TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
990                         SU->CopyDstRC, SU->CopySrcRC);
991     } else {
992       // Copy from physical register.
993       assert(I->Reg && "Unknown physical register!");
994       unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
995       bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
996       isNew = isNew; // Silence compiler warning.
997       assert(isNew && "Node emitted out of order - early");
998       TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
999                         SU->CopyDstRC, SU->CopySrcRC);
1000     }
1001     break;
1002   }
1003 }
1004
1005 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
1006 /// physical register has only a single copy use, then coalesced the copy
1007 /// if possible.
1008 void ScheduleDAG::EmitLiveInCopy(MachineBasicBlock *MBB,
1009                                  MachineBasicBlock::iterator &InsertPos,
1010                                  unsigned VirtReg, unsigned PhysReg,
1011                                  const TargetRegisterClass *RC,
1012                                  DenseMap<MachineInstr*, unsigned> &CopyRegMap){
1013   unsigned NumUses = 0;
1014   MachineInstr *UseMI = NULL;
1015   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
1016          UE = MRI.use_end(); UI != UE; ++UI) {
1017     UseMI = &*UI;
1018     if (++NumUses > 1)
1019       break;
1020   }
1021
1022   // If the number of uses is not one, or the use is not a move instruction,
1023   // don't coalesce. Also, only coalesce away a virtual register to virtual
1024   // register copy.
1025   bool Coalesced = false;
1026   unsigned SrcReg, DstReg;
1027   if (NumUses == 1 &&
1028       TII->isMoveInstr(*UseMI, SrcReg, DstReg) &&
1029       TargetRegisterInfo::isVirtualRegister(DstReg)) {
1030     VirtReg = DstReg;
1031     Coalesced = true;
1032   }
1033
1034   // Now find an ideal location to insert the copy.
1035   MachineBasicBlock::iterator Pos = InsertPos;
1036   while (Pos != MBB->begin()) {
1037     MachineInstr *PrevMI = prior(Pos);
1038     DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
1039     // copyRegToReg might emit multiple instructions to do a copy.
1040     unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
1041     if (CopyDstReg && !TRI->regsOverlap(CopyDstReg, PhysReg))
1042       // This is what the BB looks like right now:
1043       // r1024 = mov r0
1044       // ...
1045       // r1    = mov r1024
1046       //
1047       // We want to insert "r1025 = mov r1". Inserting this copy below the
1048       // move to r1024 makes it impossible for that move to be coalesced.
1049       //
1050       // r1025 = mov r1
1051       // r1024 = mov r0
1052       // ...
1053       // r1    = mov 1024
1054       // r2    = mov 1025
1055       break; // Woot! Found a good location.
1056     --Pos;
1057   }
1058
1059   TII->copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
1060   CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
1061   if (Coalesced) {
1062     if (&*InsertPos == UseMI) ++InsertPos;
1063     MBB->erase(UseMI);
1064   }
1065 }
1066
1067 /// EmitLiveInCopies - If this is the first basic block in the function,
1068 /// and if it has live ins that need to be copied into vregs, emit the
1069 /// copies into the top of the block.
1070 void ScheduleDAG::EmitLiveInCopies(MachineBasicBlock *MBB) {
1071   DenseMap<MachineInstr*, unsigned> CopyRegMap;
1072   MachineBasicBlock::iterator InsertPos = MBB->begin();
1073   for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1074          E = MRI.livein_end(); LI != E; ++LI)
1075     if (LI->second) {
1076       const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1077       EmitLiveInCopy(MBB, InsertPos, LI->second, LI->first, RC, CopyRegMap);
1078     }
1079 }
1080
1081 /// EmitSchedule - Emit the machine code in scheduled order.
1082 void ScheduleDAG::EmitSchedule() {
1083   bool isEntryBB = &MF->front() == BB;
1084
1085   if (isEntryBB && !SchedLiveInCopies) {
1086     // If this is the first basic block in the function, and if it has live ins
1087     // that need to be copied into vregs, emit the copies into the top of the
1088     // block before emitting the code for the block.
1089     for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1090            E = MRI.livein_end(); LI != E; ++LI)
1091       if (LI->second) {
1092         const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1093         TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
1094                           LI->first, RC, RC);
1095       }
1096   }
1097
1098   // Finally, emit the code for all of the scheduled instructions.
1099   DenseMap<SDOperand, unsigned> VRBaseMap;
1100   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
1101   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1102     SUnit *SU = Sequence[i];
1103     if (!SU) {
1104       // Null SUnit* is a noop.
1105       EmitNoop();
1106       continue;
1107     }
1108     for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
1109       EmitNode(SU->FlaggedNodes[j], SU->OrigNode != SU, VRBaseMap);
1110     if (!SU->Node)
1111       EmitCrossRCCopy(SU, CopyVRBaseMap);
1112     else
1113       EmitNode(SU->Node, SU->OrigNode != SU, VRBaseMap);
1114   }
1115
1116   if (isEntryBB && SchedLiveInCopies)
1117     EmitLiveInCopies(MF->begin());
1118 }
1119
1120 /// dump - dump the schedule.
1121 void ScheduleDAG::dumpSchedule() const {
1122   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1123     if (SUnit *SU = Sequence[i])
1124       SU->dump(&DAG);
1125     else
1126       cerr << "**** NOOP ****\n";
1127   }
1128 }
1129
1130
1131 /// Run - perform scheduling.
1132 ///
1133 MachineBasicBlock *ScheduleDAG::Run() {
1134   Schedule();
1135   return BB;
1136 }
1137
1138 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
1139 /// a group of nodes flagged together.
1140 void SUnit::dump(const SelectionDAG *G) const {
1141   cerr << "SU(" << NodeNum << "): ";
1142   if (Node)
1143     Node->dump(G);
1144   else
1145     cerr << "CROSS RC COPY ";
1146   cerr << "\n";
1147   if (FlaggedNodes.size() != 0) {
1148     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
1149       cerr << "    ";
1150       FlaggedNodes[i]->dump(G);
1151       cerr << "\n";
1152     }
1153   }
1154 }
1155
1156 void SUnit::dumpAll(const SelectionDAG *G) const {
1157   dump(G);
1158
1159   cerr << "  # preds left       : " << NumPredsLeft << "\n";
1160   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
1161   cerr << "  Latency            : " << Latency << "\n";
1162   cerr << "  Depth              : " << Depth << "\n";
1163   cerr << "  Height             : " << Height << "\n";
1164
1165   if (Preds.size() != 0) {
1166     cerr << "  Predecessors:\n";
1167     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
1168          I != E; ++I) {
1169       if (I->isCtrl)
1170         cerr << "   ch  #";
1171       else
1172         cerr << "   val #";
1173       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1174       if (I->isSpecial)
1175         cerr << " *";
1176       cerr << "\n";
1177     }
1178   }
1179   if (Succs.size() != 0) {
1180     cerr << "  Successors:\n";
1181     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1182          I != E; ++I) {
1183       if (I->isCtrl)
1184         cerr << "   ch  #";
1185       else
1186         cerr << "   val #";
1187       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1188       if (I->isSpecial)
1189         cerr << " *";
1190       cerr << "\n";
1191     }
1192   }
1193   cerr << "\n";
1194 }