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