Avoid using a loop in ReleasePred and ReleaseSucc methods to compute the
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGFast.cpp
1 //===----- ScheduleDAGFast.cpp - Fast poor list scheduler -----------------===//
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 fast scheduler.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "pre-RA-sched"
15 #include "llvm/CodeGen/ScheduleDAG.h"
16 #include "llvm/CodeGen/SchedulerRegistry.h"
17 #include "llvm/Target/TargetRegisterInfo.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/CommandLine.h"
27 using namespace llvm;
28
29 STATISTIC(NumUnfolds,    "Number of nodes unfolded");
30 STATISTIC(NumDups,       "Number of duplicated nodes");
31 STATISTIC(NumCCCopies,   "Number of cross class copies");
32
33 static RegisterScheduler
34   fastDAGScheduler("fast", "Fast suboptimal list scheduling",
35                    createFastDAGScheduler);
36
37 namespace {
38   /// FastPriorityQueue - A degenerate priority queue that considers
39   /// all nodes to have the same priority.
40   ///
41   struct VISIBILITY_HIDDEN FastPriorityQueue {
42     SmallVector<SUnit *, 16> Queue;
43
44     bool empty() const { return Queue.empty(); }
45     
46     void push(SUnit *U) {
47       Queue.push_back(U);
48     }
49
50     SUnit *pop() {
51       if (empty()) return NULL;
52       SUnit *V = Queue.back();
53       Queue.pop_back();
54       return V;
55     }
56   };
57
58 //===----------------------------------------------------------------------===//
59 /// ScheduleDAGFast - The actual "fast" list scheduler implementation.
60 ///
61 class VISIBILITY_HIDDEN ScheduleDAGFast : public ScheduleDAG {
62 private:
63   /// AvailableQueue - The priority queue to use for the available SUnits.
64   FastPriorityQueue AvailableQueue;
65
66   /// LiveRegDefs - A set of physical registers and their definition
67   /// that are "live". These nodes must be scheduled before any other nodes that
68   /// modifies the registers can be scheduled.
69   unsigned NumLiveRegs;
70   std::vector<SUnit*> LiveRegDefs;
71   std::vector<unsigned> LiveRegCycles;
72
73 public:
74   ScheduleDAGFast(SelectionDAG *dag, MachineBasicBlock *bb,
75                   const TargetMachine &tm)
76     : ScheduleDAG(dag, bb, tm) {}
77
78   void Schedule();
79
80   /// AddPred - This adds the specified node X as a predecessor of 
81   /// the current node Y if not already.
82   /// This returns true if this is a new predecessor.
83   bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
84                unsigned PhyReg = 0, int Cost = 1);
85
86   /// RemovePred - This removes the specified node N from the predecessors of 
87   /// the current node M.
88   bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
89
90 private:
91   void ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain);
92   void ScheduleNodeBottomUp(SUnit*, unsigned);
93   SUnit *CopyAndMoveSuccessors(SUnit*);
94   void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
95                                   const TargetRegisterClass*,
96                                   const TargetRegisterClass*,
97                                   SmallVector<SUnit*, 2>&);
98   bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
99   void ListScheduleBottomUp();
100
101   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
102   SUnit *CreateNewSUnit(SDNode *N) {
103     SUnit *NewNode = NewSUnit(N);
104     return NewNode;
105   }
106
107   /// CreateClone - Creates a new SUnit from an existing one.
108   SUnit *CreateClone(SUnit *N) {
109     SUnit *NewNode = Clone(N);
110     return NewNode;
111   }
112 };
113 }  // end anonymous namespace
114
115
116 /// Schedule - Schedule the DAG using list scheduling.
117 void ScheduleDAGFast::Schedule() {
118   DOUT << "********** List Scheduling **********\n";
119
120   NumLiveRegs = 0;
121   LiveRegDefs.resize(TRI->getNumRegs(), NULL);  
122   LiveRegCycles.resize(TRI->getNumRegs(), 0);
123
124   // Build scheduling units.
125   BuildSchedUnits();
126
127   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
128           SUnits[su].dumpAll(DAG));
129
130   // Execute the actual scheduling loop.
131   ListScheduleBottomUp();
132 }
133
134 //===----------------------------------------------------------------------===//
135 //  Bottom-Up Scheduling
136 //===----------------------------------------------------------------------===//
137
138 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
139 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
140 void ScheduleDAGFast::ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain) {
141   --PredSU->NumSuccsLeft;
142   
143 #ifndef NDEBUG
144   if (PredSU->NumSuccsLeft < 0) {
145     cerr << "*** Scheduling failed! ***\n";
146     PredSU->dump(DAG);
147     cerr << " has been released too many times!\n";
148     assert(0);
149   }
150 #endif
151   
152   if (PredSU->NumSuccsLeft == 0) {
153     PredSU->isAvailable = true;
154     AvailableQueue.push(PredSU);
155   }
156 }
157
158 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
159 /// count of its predecessors. If a predecessor pending count is zero, add it to
160 /// the Available queue.
161 void ScheduleDAGFast::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
162   DOUT << "*** Scheduling [" << CurCycle << "]: ";
163   DEBUG(SU->dump(DAG));
164   SU->Cycle = CurCycle;
165
166   // Bottom up: release predecessors
167   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
168        I != E; ++I) {
169     ReleasePred(SU, I->Dep, I->isCtrl);
170     if (I->Cost < 0)  {
171       // This is a physical register dependency and it's impossible or
172       // expensive to copy the register. Make sure nothing that can 
173       // clobber the register is scheduled between the predecessor and
174       // this node.
175       if (!LiveRegDefs[I->Reg]) {
176         ++NumLiveRegs;
177         LiveRegDefs[I->Reg] = I->Dep;
178         LiveRegCycles[I->Reg] = CurCycle;
179       }
180     }
181   }
182
183   // Release all the implicit physical register defs that are live.
184   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
185        I != E; ++I) {
186     if (I->Cost < 0)  {
187       if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
188         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
189         assert(LiveRegDefs[I->Reg] == SU &&
190                "Physical register dependency violated?");
191         --NumLiveRegs;
192         LiveRegDefs[I->Reg] = NULL;
193         LiveRegCycles[I->Reg] = 0;
194       }
195     }
196   }
197
198   SU->isScheduled = true;
199 }
200
201 /// AddPred - adds an edge from SUnit X to SUnit Y.
202 bool ScheduleDAGFast::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
203                               unsigned PhyReg, int Cost) {
204   return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
205 }
206
207 /// RemovePred - This removes the specified node N from the predecessors of 
208 /// the current node M.
209 bool ScheduleDAGFast::RemovePred(SUnit *M, SUnit *N, 
210                                  bool isCtrl, bool isSpecial) {
211   return M->removePred(N, isCtrl, isSpecial);
212 }
213
214 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
215 /// successors to the newly created node.
216 SUnit *ScheduleDAGFast::CopyAndMoveSuccessors(SUnit *SU) {
217   if (SU->getNode()->getFlaggedNode())
218     return NULL;
219
220   SDNode *N = SU->getNode();
221   if (!N)
222     return NULL;
223
224   SUnit *NewSU;
225   bool TryUnfold = false;
226   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
227     MVT VT = N->getValueType(i);
228     if (VT == MVT::Flag)
229       return NULL;
230     else if (VT == MVT::Other)
231       TryUnfold = true;
232   }
233   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
234     const SDValue &Op = N->getOperand(i);
235     MVT VT = Op.getNode()->getValueType(Op.getResNo());
236     if (VT == MVT::Flag)
237       return NULL;
238   }
239
240   if (TryUnfold) {
241     SmallVector<SDNode*, 2> NewNodes;
242     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
243       return NULL;
244
245     DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
246     assert(NewNodes.size() == 2 && "Expected a load folding node!");
247
248     N = NewNodes[1];
249     SDNode *LoadNode = NewNodes[0];
250     unsigned NumVals = N->getNumValues();
251     unsigned OldNumVals = SU->getNode()->getNumValues();
252     for (unsigned i = 0; i != NumVals; ++i)
253       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
254     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
255                                    SDValue(LoadNode, 1));
256
257     SUnit *NewSU = CreateNewSUnit(N);
258     assert(N->getNodeId() == -1 && "Node already inserted!");
259     N->setNodeId(NewSU->NodeNum);
260       
261     const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
262     for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
263       if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
264         NewSU->isTwoAddress = true;
265         break;
266       }
267     }
268     if (TID.isCommutable())
269       NewSU->isCommutable = true;
270     // FIXME: Calculate height / depth and propagate the changes?
271     NewSU->Depth = SU->Depth;
272     NewSU->Height = SU->Height;
273
274     // LoadNode may already exist. This can happen when there is another
275     // load from the same location and producing the same type of value
276     // but it has different alignment or volatileness.
277     bool isNewLoad = true;
278     SUnit *LoadSU;
279     if (LoadNode->getNodeId() != -1) {
280       LoadSU = &SUnits[LoadNode->getNodeId()];
281       isNewLoad = false;
282     } else {
283       LoadSU = CreateNewSUnit(LoadNode);
284       LoadNode->setNodeId(LoadSU->NodeNum);
285
286       LoadSU->Depth = SU->Depth;
287       LoadSU->Height = SU->Height;
288     }
289
290     SUnit *ChainPred = NULL;
291     SmallVector<SDep, 4> ChainSuccs;
292     SmallVector<SDep, 4> LoadPreds;
293     SmallVector<SDep, 4> NodePreds;
294     SmallVector<SDep, 4> NodeSuccs;
295     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
296          I != E; ++I) {
297       if (I->isCtrl)
298         ChainPred = I->Dep;
299       else if (I->Dep->getNode() && I->Dep->getNode()->isOperandOf(LoadNode))
300         LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
301       else
302         NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
303     }
304     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
305          I != E; ++I) {
306       if (I->isCtrl)
307         ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
308                                   I->isCtrl, I->isSpecial));
309       else
310         NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
311                                  I->isCtrl, I->isSpecial));
312     }
313
314     if (ChainPred) {
315       RemovePred(SU, ChainPred, true, false);
316       if (isNewLoad)
317         AddPred(LoadSU, ChainPred, true, false);
318     }
319     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
320       SDep *Pred = &LoadPreds[i];
321       RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
322       if (isNewLoad) {
323         AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
324                 Pred->Reg, Pred->Cost);
325       }
326     }
327     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
328       SDep *Pred = &NodePreds[i];
329       RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
330       AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
331               Pred->Reg, Pred->Cost);
332     }
333     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
334       SDep *Succ = &NodeSuccs[i];
335       RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
336       AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
337               Succ->Reg, Succ->Cost);
338     }
339     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
340       SDep *Succ = &ChainSuccs[i];
341       RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
342       if (isNewLoad) {
343         AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
344                 Succ->Reg, Succ->Cost);
345       }
346     } 
347     if (isNewLoad) {
348       AddPred(NewSU, LoadSU, false, false);
349     }
350
351     ++NumUnfolds;
352
353     if (NewSU->NumSuccsLeft == 0) {
354       NewSU->isAvailable = true;
355       return NewSU;
356     }
357     SU = NewSU;
358   }
359
360   DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
361   NewSU = CreateClone(SU);
362
363   // New SUnit has the exact same predecessors.
364   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
365        I != E; ++I)
366     if (!I->isSpecial) {
367       AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
368       NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
369     }
370
371   // Only copy scheduled successors. Cut them from old node's successor
372   // list and move them over.
373   SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
374   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
375        I != E; ++I) {
376     if (I->isSpecial)
377       continue;
378     if (I->Dep->isScheduled) {
379       NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
380       AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
381       DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
382     }
383   }
384   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
385     SUnit *Succ = DelDeps[i].first;
386     bool isCtrl = DelDeps[i].second;
387     RemovePred(Succ, SU, isCtrl, false);
388   }
389
390   ++NumDups;
391   return NewSU;
392 }
393
394 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
395 /// and move all scheduled successors of the given SUnit to the last copy.
396 void ScheduleDAGFast::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
397                                               const TargetRegisterClass *DestRC,
398                                               const TargetRegisterClass *SrcRC,
399                                                SmallVector<SUnit*, 2> &Copies) {
400   SUnit *CopyFromSU = CreateNewSUnit(NULL);
401   CopyFromSU->CopySrcRC = SrcRC;
402   CopyFromSU->CopyDstRC = DestRC;
403
404   SUnit *CopyToSU = CreateNewSUnit(NULL);
405   CopyToSU->CopySrcRC = DestRC;
406   CopyToSU->CopyDstRC = SrcRC;
407
408   // Only copy scheduled successors. Cut them from old node's successor
409   // list and move them over.
410   SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
411   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
412        I != E; ++I) {
413     if (I->isSpecial)
414       continue;
415     if (I->Dep->isScheduled) {
416       AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
417       DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
418     }
419   }
420   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
421     SUnit *Succ = DelDeps[i].first;
422     bool isCtrl = DelDeps[i].second;
423     RemovePred(Succ, SU, isCtrl, false);
424   }
425
426   AddPred(CopyFromSU, SU, false, false, Reg, -1);
427   AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
428
429   Copies.push_back(CopyFromSU);
430   Copies.push_back(CopyToSU);
431
432   ++NumCCCopies;
433 }
434
435 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
436 /// definition of the specified node.
437 /// FIXME: Move to SelectionDAG?
438 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
439                                  const TargetInstrInfo *TII) {
440   const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
441   assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
442   unsigned NumRes = TID.getNumDefs();
443   for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
444     if (Reg == *ImpDef)
445       break;
446     ++NumRes;
447   }
448   return N->getValueType(NumRes);
449 }
450
451 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
452 /// scheduling of the given node to satisfy live physical register dependencies.
453 /// If the specific node is the last one that's available to schedule, do
454 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
455 bool ScheduleDAGFast::DelayForLiveRegsBottomUp(SUnit *SU,
456                                                SmallVector<unsigned, 4> &LRegs){
457   if (NumLiveRegs == 0)
458     return false;
459
460   SmallSet<unsigned, 4> RegAdded;
461   // If this node would clobber any "live" register, then it's not ready.
462   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
463        I != E; ++I) {
464     if (I->Cost < 0)  {
465       unsigned Reg = I->Reg;
466       if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->Dep) {
467         if (RegAdded.insert(Reg))
468           LRegs.push_back(Reg);
469       }
470       for (const unsigned *Alias = TRI->getAliasSet(Reg);
471            *Alias; ++Alias)
472         if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->Dep) {
473           if (RegAdded.insert(*Alias))
474             LRegs.push_back(*Alias);
475         }
476     }
477   }
478
479   for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
480     if (!Node->isMachineOpcode())
481       continue;
482     const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
483     if (!TID.ImplicitDefs)
484       continue;
485     for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
486       if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
487         if (RegAdded.insert(*Reg))
488           LRegs.push_back(*Reg);
489       }
490       for (const unsigned *Alias = TRI->getAliasSet(*Reg);
491            *Alias; ++Alias)
492         if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
493           if (RegAdded.insert(*Alias))
494             LRegs.push_back(*Alias);
495         }
496     }
497   }
498   return !LRegs.empty();
499 }
500
501
502 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
503 /// schedulers.
504 void ScheduleDAGFast::ListScheduleBottomUp() {
505   unsigned CurCycle = 0;
506   // Add root to Available queue.
507   if (!SUnits.empty()) {
508     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
509     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
510     RootSU->isAvailable = true;
511     AvailableQueue.push(RootSU);
512   }
513
514   // While Available queue is not empty, grab the node with the highest
515   // priority. If it is not ready put it back.  Schedule the node.
516   SmallVector<SUnit*, 4> NotReady;
517   DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
518   Sequence.reserve(SUnits.size());
519   while (!AvailableQueue.empty()) {
520     bool Delayed = false;
521     LRegsMap.clear();
522     SUnit *CurSU = AvailableQueue.pop();
523     while (CurSU) {
524       SmallVector<unsigned, 4> LRegs;
525       if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
526         break;
527       Delayed = true;
528       LRegsMap.insert(std::make_pair(CurSU, LRegs));
529
530       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
531       NotReady.push_back(CurSU);
532       CurSU = AvailableQueue.pop();
533     }
534
535     // All candidates are delayed due to live physical reg dependencies.
536     // Try code duplication or inserting cross class copies
537     // to resolve it.
538     if (Delayed && !CurSU) {
539       if (!CurSU) {
540         // Try duplicating the nodes that produces these
541         // "expensive to copy" values to break the dependency. In case even
542         // that doesn't work, insert cross class copies.
543         SUnit *TrySU = NotReady[0];
544         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
545         assert(LRegs.size() == 1 && "Can't handle this yet!");
546         unsigned Reg = LRegs[0];
547         SUnit *LRDef = LiveRegDefs[Reg];
548         SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
549         if (!NewDef) {
550           // Issue expensive cross register class copies.
551           MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
552           const TargetRegisterClass *RC =
553             TRI->getPhysicalRegisterRegClass(Reg, VT);
554           const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
555           if (!DestRC) {
556             assert(false && "Don't know how to copy this physical register!");
557             abort();
558           }
559           SmallVector<SUnit*, 2> Copies;
560           InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
561           DOUT << "Adding an edge from SU # " << TrySU->NodeNum
562                << " to SU #" << Copies.front()->NodeNum << "\n";
563           AddPred(TrySU, Copies.front(), true, true);
564           NewDef = Copies.back();
565         }
566
567         DOUT << "Adding an edge from SU # " << NewDef->NodeNum
568              << " to SU #" << TrySU->NodeNum << "\n";
569         LiveRegDefs[Reg] = NewDef;
570         AddPred(NewDef, TrySU, true, true);
571         TrySU->isAvailable = false;
572         CurSU = NewDef;
573       }
574
575       if (!CurSU) {
576         assert(false && "Unable to resolve live physical register dependencies!");
577         abort();
578       }
579     }
580
581     // Add the nodes that aren't ready back onto the available list.
582     for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
583       NotReady[i]->isPending = false;
584       // May no longer be available due to backtracking.
585       if (NotReady[i]->isAvailable)
586         AvailableQueue.push(NotReady[i]);
587     }
588     NotReady.clear();
589
590     if (!CurSU)
591       Sequence.push_back(0);
592     else {
593       ScheduleNodeBottomUp(CurSU, CurCycle);
594       Sequence.push_back(CurSU);
595     }
596     ++CurCycle;
597   }
598
599   // Reverse the order if it is bottom up.
600   std::reverse(Sequence.begin(), Sequence.end());
601   
602   
603 #ifndef NDEBUG
604   // Verify that all SUnits were scheduled.
605   bool AnyNotSched = false;
606   unsigned DeadNodes = 0;
607   unsigned Noops = 0;
608   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
609     if (!SUnits[i].isScheduled) {
610       if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
611         ++DeadNodes;
612         continue;
613       }
614       if (!AnyNotSched)
615         cerr << "*** List scheduling failed! ***\n";
616       SUnits[i].dump(DAG);
617       cerr << "has not been scheduled!\n";
618       AnyNotSched = true;
619     }
620     if (SUnits[i].NumSuccsLeft != 0) {
621       if (!AnyNotSched)
622         cerr << "*** List scheduling failed! ***\n";
623       SUnits[i].dump(DAG);
624       cerr << "has successors left!\n";
625       AnyNotSched = true;
626     }
627   }
628   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
629     if (!Sequence[i])
630       ++Noops;
631   assert(!AnyNotSched);
632   assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
633          "The number of nodes scheduled doesn't match the expected number!");
634 #endif
635 }
636
637 //===----------------------------------------------------------------------===//
638 //                         Public Constructor Functions
639 //===----------------------------------------------------------------------===//
640
641 llvm::ScheduleDAG* llvm::createFastDAGScheduler(SelectionDAGISel *IS,
642                                                 SelectionDAG *DAG,
643                                                 const TargetMachine *TM,
644                                                 MachineBasicBlock *BB, bool) {
645   return new ScheduleDAGFast(DAG, BB, *TM);
646 }