canClobberPhysRegDefs shouldn't called without checking hasPhysRegDefs;
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGRRList.cpp
1 //===----- ScheduleDAGList.cpp - Reg pressure reduction 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 bottom-up and top-down register pressure reduction list
11 // schedulers, using standard algorithms.  The basic approach uses a priority
12 // queue of available nodes to schedule.  One at a time, nodes are taken from
13 // the priority queue (thus in priority order), checked for legality to
14 // schedule, and emitted if legal.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "pre-RA-sched"
19 #include "llvm/CodeGen/ScheduleDAG.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/PriorityQueue.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include <climits>
34 #include "llvm/Support/CommandLine.h"
35 using namespace llvm;
36
37 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
38 STATISTIC(NumUnfolds,    "Number of nodes unfolded");
39 STATISTIC(NumDups,       "Number of duplicated nodes");
40 STATISTIC(NumCCCopies,   "Number of cross class copies");
41
42 static RegisterScheduler
43   burrListDAGScheduler("list-burr",
44                        "  Bottom-up register reduction list scheduling",
45                        createBURRListDAGScheduler);
46 static RegisterScheduler
47   tdrListrDAGScheduler("list-tdrr",
48                        "  Top-down register reduction list scheduling",
49                        createTDRRListDAGScheduler);
50
51 namespace {
52 //===----------------------------------------------------------------------===//
53 /// ScheduleDAGRRList - The actual register reduction list scheduler
54 /// implementation.  This supports both top-down and bottom-up scheduling.
55 ///
56 class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
57 private:
58   /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
59   /// it is top-down.
60   bool isBottomUp;
61   
62   /// AvailableQueue - The priority queue to use for the available SUnits.
63   SchedulingPriorityQueue *AvailableQueue;
64
65   /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
66   /// that are "live". These nodes must be scheduled before any other nodes that
67   /// modifies the registers can be scheduled.
68   SmallSet<unsigned, 4> LiveRegs;
69   std::vector<SUnit*> LiveRegDefs;
70   std::vector<unsigned> LiveRegCycles;
71
72 public:
73   ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
74                   const TargetMachine &tm, bool isbottomup,
75                   SchedulingPriorityQueue *availqueue)
76     : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
77       AvailableQueue(availqueue) {
78     }
79
80   ~ScheduleDAGRRList() {
81     delete AvailableQueue;
82   }
83
84   void Schedule();
85
86   /// IsReachable - Checks if SU is reachable from TargetSU.
87   bool IsReachable(SUnit *SU, SUnit *TargetSU);
88
89   /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
90   /// create a cycle.
91   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
92
93   /// AddPred - This adds the specified node X as a predecessor of 
94   /// the current node Y if not already.
95   /// This returns true if this is a new predecessor.
96   /// Updates the topological ordering if required.
97   bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
98                unsigned PhyReg = 0, int Cost = 1);
99
100   /// RemovePred - This removes the specified node N from the predecessors of 
101   /// the current node M. Updates the topological ordering if required.
102   bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
103
104 private:
105   void ReleasePred(SUnit*, bool, unsigned);
106   void ReleaseSucc(SUnit*, bool isChain, unsigned);
107   void CapturePred(SUnit*, SUnit*, bool);
108   void ScheduleNodeBottomUp(SUnit*, unsigned);
109   void ScheduleNodeTopDown(SUnit*, unsigned);
110   void UnscheduleNodeBottomUp(SUnit*);
111   void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
112   SUnit *CopyAndMoveSuccessors(SUnit*);
113   void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
114                                   const TargetRegisterClass*,
115                                   const TargetRegisterClass*,
116                                   SmallVector<SUnit*, 2>&);
117   bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
118   void ListScheduleTopDown();
119   void ListScheduleBottomUp();
120   void CommuteNodesToReducePressure();
121
122
123   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
124   /// Updates the topological ordering if required.
125   SUnit *CreateNewSUnit(SDNode *N) {
126     SUnit *NewNode = NewSUnit(N);
127     // Update the topological ordering.
128     if (NewNode->NodeNum >= Node2Index.size())
129       InitDAGTopologicalSorting();
130     return NewNode;
131   }
132
133   /// CreateClone - Creates a new SUnit from an existing one.
134   /// Updates the topological ordering if required.
135   SUnit *CreateClone(SUnit *N) {
136     SUnit *NewNode = Clone(N);
137     // Update the topological ordering.
138     if (NewNode->NodeNum >= Node2Index.size())
139       InitDAGTopologicalSorting();
140     return NewNode;
141   }
142
143   /// Functions for preserving the topological ordering
144   /// even after dynamic insertions of new edges.
145   /// This allows a very fast implementation of IsReachable.
146
147
148   /** 
149   The idea of the algorithm is taken from 
150   "Online algorithms for managing the topological order of
151   a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
152   This is the MNR algorithm, which was first introduced by 
153   A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in  
154   "Maintaining a topological order under edge insertions".
155
156   Short description of the algorithm: 
157   
158   Topological ordering, ord, of a DAG maps each node to a topological
159   index so that for all edges X->Y it is the case that ord(X) < ord(Y).
160   
161   This means that if there is a path from the node X to the node Z, 
162   then ord(X) < ord(Z).
163   
164   This property can be used to check for reachability of nodes:
165   if Z is reachable from X, then an insertion of the edge Z->X would 
166   create a cycle.
167    
168   The algorithm first computes a topological ordering for the DAG by initializing
169   the Index2Node and Node2Index arrays and then tries to keep the ordering
170   up-to-date after edge insertions by reordering the DAG.
171   
172   On insertion of the edge X->Y, the algorithm first marks by calling DFS the
173   nodes reachable from Y, and then shifts them using Shift to lie immediately
174   after X in Index2Node.
175   */
176
177   /// InitDAGTopologicalSorting - create the initial topological 
178   /// ordering from the DAG to be scheduled.
179   void InitDAGTopologicalSorting();
180
181   /// DFS - make a DFS traversal and mark all nodes affected by the 
182   /// edge insertion. These nodes will later get new topological indexes
183   /// by means of the Shift method.
184   void DFS(SUnit *SU, int UpperBound, bool& HasLoop);
185
186   /// Shift - reassign topological indexes for the nodes in the DAG
187   /// to preserve the topological ordering.
188   void Shift(BitVector& Visited, int LowerBound, int UpperBound);
189
190   /// Allocate - assign the topological index to the node n.
191   void Allocate(int n, int index);
192
193   /// Index2Node - Maps topological index to the node number.
194   std::vector<int> Index2Node;
195   /// Node2Index - Maps the node number to its topological index.
196   std::vector<int> Node2Index;
197   /// Visited - a set of nodes visited during a DFS traversal.
198   BitVector Visited;
199 };
200 }  // end anonymous namespace
201
202
203 /// Schedule - Schedule the DAG using list scheduling.
204 void ScheduleDAGRRList::Schedule() {
205   DOUT << "********** List Scheduling **********\n";
206
207   LiveRegDefs.resize(TRI->getNumRegs(), NULL);  
208   LiveRegCycles.resize(TRI->getNumRegs(), 0);
209
210   // Build scheduling units.
211   BuildSchedUnits();
212
213   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
214           SUnits[su].dumpAll(&DAG));
215   CalculateDepths();
216   CalculateHeights();
217   InitDAGTopologicalSorting();
218
219   AvailableQueue->initNodes(SUnits);
220   
221   // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
222   if (isBottomUp)
223     ListScheduleBottomUp();
224   else
225     ListScheduleTopDown();
226   
227   AvailableQueue->releaseState();
228   
229   CommuteNodesToReducePressure();
230   
231   DOUT << "*** Final schedule ***\n";
232   DEBUG(dumpSchedule());
233   DOUT << "\n";
234   
235   // Emit in scheduled order
236   EmitSchedule();
237 }
238
239 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
240 /// it is not the last use of its first operand, add it to the CommuteSet if
241 /// possible. It will be commuted when it is translated to a MI.
242 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
243   SmallPtrSet<SUnit*, 4> OperandSeen;
244   for (unsigned i = Sequence.size(); i != 0; ) {
245     --i;
246     SUnit *SU = Sequence[i];
247     if (!SU || !SU->Node) continue;
248     if (SU->isCommutable) {
249       unsigned Opc = SU->Node->getTargetOpcode();
250       const TargetInstrDesc &TID = TII->get(Opc);
251       unsigned NumRes = TID.getNumDefs();
252       unsigned NumOps = TID.getNumOperands() - NumRes;
253       for (unsigned j = 0; j != NumOps; ++j) {
254         if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
255           continue;
256
257         SDNode *OpN = SU->Node->getOperand(j).Val;
258         SUnit *OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
259         if (OpSU && OperandSeen.count(OpSU) == 1) {
260           // Ok, so SU is not the last use of OpSU, but SU is two-address so
261           // it will clobber OpSU. Try to commute SU if no other source operands
262           // are live below.
263           bool DoCommute = true;
264           for (unsigned k = 0; k < NumOps; ++k) {
265             if (k != j) {
266               OpN = SU->Node->getOperand(k).Val;
267               OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
268               if (OpSU && OperandSeen.count(OpSU) == 1) {
269                 DoCommute = false;
270                 break;
271               }
272             }
273           }
274           if (DoCommute)
275             CommuteSet.insert(SU->Node);
276         }
277
278         // Only look at the first use&def node for now.
279         break;
280       }
281     }
282
283     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
284          I != E; ++I) {
285       if (!I->isCtrl)
286         OperandSeen.insert(I->Dep->OrigNode);
287     }
288   }
289 }
290
291 //===----------------------------------------------------------------------===//
292 //  Bottom-Up Scheduling
293 //===----------------------------------------------------------------------===//
294
295 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
296 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
297 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain, 
298                                     unsigned CurCycle) {
299   // FIXME: the distance between two nodes is not always == the predecessor's
300   // latency. For example, the reader can very well read the register written
301   // by the predecessor later than the issue cycle. It also depends on the
302   // interrupt model (drain vs. freeze).
303   PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
304
305   --PredSU->NumSuccsLeft;
306   
307 #ifndef NDEBUG
308   if (PredSU->NumSuccsLeft < 0) {
309     cerr << "*** List scheduling failed! ***\n";
310     PredSU->dump(&DAG);
311     cerr << " has been released too many times!\n";
312     assert(0);
313   }
314 #endif
315   
316   if (PredSU->NumSuccsLeft == 0) {
317     PredSU->isAvailable = true;
318     AvailableQueue->push(PredSU);
319   }
320 }
321
322 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
323 /// count of its predecessors. If a predecessor pending count is zero, add it to
324 /// the Available queue.
325 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
326   DOUT << "*** Scheduling [" << CurCycle << "]: ";
327   DEBUG(SU->dump(&DAG));
328   SU->Cycle = CurCycle;
329
330   AvailableQueue->ScheduledNode(SU);
331
332   // Bottom up: release predecessors
333   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
334        I != E; ++I) {
335     ReleasePred(I->Dep, I->isCtrl, CurCycle);
336     if (I->Cost < 0)  {
337       // This is a physical register dependency and it's impossible or
338       // expensive to copy the register. Make sure nothing that can 
339       // clobber the register is scheduled between the predecessor and
340       // this node.
341       if (LiveRegs.insert(I->Reg)) {
342         LiveRegDefs[I->Reg] = I->Dep;
343         LiveRegCycles[I->Reg] = CurCycle;
344       }
345     }
346   }
347
348   // Release all the implicit physical register defs that are live.
349   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
350        I != E; ++I) {
351     if (I->Cost < 0)  {
352       if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
353         LiveRegs.erase(I->Reg);
354         assert(LiveRegDefs[I->Reg] == SU &&
355                "Physical register dependency violated?");
356         LiveRegDefs[I->Reg] = NULL;
357         LiveRegCycles[I->Reg] = 0;
358       }
359     }
360   }
361
362   SU->isScheduled = true;
363 }
364
365 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
366 /// unscheduled, incrcease the succ left count of its predecessors. Remove
367 /// them from AvailableQueue if necessary.
368 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {  
369   unsigned CycleBound = 0;
370   for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
371        I != E; ++I) {
372     if (I->Dep == SU)
373       continue;
374     CycleBound = std::max(CycleBound,
375                           I->Dep->Cycle + PredSU->Latency);
376   }
377
378   if (PredSU->isAvailable) {
379     PredSU->isAvailable = false;
380     if (!PredSU->isPending)
381       AvailableQueue->remove(PredSU);
382   }
383
384   PredSU->CycleBound = CycleBound;
385   ++PredSU->NumSuccsLeft;
386 }
387
388 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
389 /// its predecessor states to reflect the change.
390 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
391   DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
392   DEBUG(SU->dump(&DAG));
393
394   AvailableQueue->UnscheduledNode(SU);
395
396   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
397        I != E; ++I) {
398     CapturePred(I->Dep, SU, I->isCtrl);
399     if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg])  {
400       LiveRegs.erase(I->Reg);
401       assert(LiveRegDefs[I->Reg] == I->Dep &&
402              "Physical register dependency violated?");
403       LiveRegDefs[I->Reg] = NULL;
404       LiveRegCycles[I->Reg] = 0;
405     }
406   }
407
408   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
409        I != E; ++I) {
410     if (I->Cost < 0)  {
411       if (LiveRegs.insert(I->Reg)) {
412         assert(!LiveRegDefs[I->Reg] &&
413                "Physical register dependency violated?");
414         LiveRegDefs[I->Reg] = SU;
415       }
416       if (I->Dep->Cycle < LiveRegCycles[I->Reg])
417         LiveRegCycles[I->Reg] = I->Dep->Cycle;
418     }
419   }
420
421   SU->Cycle = 0;
422   SU->isScheduled = false;
423   SU->isAvailable = true;
424   AvailableQueue->push(SU);
425 }
426
427 /// IsReachable - Checks if SU is reachable from TargetSU.
428 bool ScheduleDAGRRList::IsReachable(SUnit *SU, SUnit *TargetSU) {
429   // If insertion of the edge SU->TargetSU would create a cycle
430   // then there is a path from TargetSU to SU.
431   int UpperBound, LowerBound;
432   LowerBound = Node2Index[TargetSU->NodeNum];
433   UpperBound = Node2Index[SU->NodeNum];
434   bool HasLoop = false;
435   // Is Ord(TargetSU) < Ord(SU) ?
436   if (LowerBound < UpperBound) {
437     Visited.reset();
438     // There may be a path from TargetSU to SU. Check for it. 
439     DFS(TargetSU, UpperBound, HasLoop);
440   }
441   return HasLoop;
442 }
443
444 /// Allocate - assign the topological index to the node n.
445 inline void ScheduleDAGRRList::Allocate(int n, int index) {
446   Node2Index[n] = index;
447   Index2Node[index] = n;
448 }
449
450 /// InitDAGTopologicalSorting - create the initial topological 
451 /// ordering from the DAG to be scheduled.
452 void ScheduleDAGRRList::InitDAGTopologicalSorting() {
453   unsigned DAGSize = SUnits.size();
454   std::vector<unsigned> InDegree(DAGSize);
455   std::vector<SUnit*> WorkList;
456   WorkList.reserve(DAGSize);
457   std::vector<SUnit*> TopOrder;
458   TopOrder.reserve(DAGSize);
459
460   // Initialize the data structures.
461   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
462     SUnit *SU = &SUnits[i];
463     int NodeNum = SU->NodeNum;
464     unsigned Degree = SU->Succs.size();
465     InDegree[NodeNum] = Degree;
466
467     // Is it a node without dependencies?
468     if (Degree == 0) {
469         assert(SU->Succs.empty() && "SUnit should have no successors");
470         // Collect leaf nodes.
471         WorkList.push_back(SU);
472     }
473   }  
474
475   while (!WorkList.empty()) {
476     SUnit *SU = WorkList.back();
477     WorkList.pop_back();
478     TopOrder.push_back(SU);
479     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
480          I != E; ++I) {
481       SUnit *SU = I->Dep;
482       if (!--InDegree[SU->NodeNum])
483         // If all dependencies of the node are processed already,
484         // then the node can be computed now.
485         WorkList.push_back(SU);
486     }
487   }
488
489   // Second pass, assign the actual topological order as node ids.
490   int Id = 0;
491
492   Index2Node.clear();
493   Node2Index.clear();
494   Index2Node.resize(DAGSize);
495   Node2Index.resize(DAGSize);
496   Visited.resize(DAGSize);
497
498   for (std::vector<SUnit*>::reverse_iterator TI = TopOrder.rbegin(),
499        TE = TopOrder.rend();TI != TE; ++TI) {
500     Allocate((*TI)->NodeNum, Id);
501     Id++;
502   }
503
504 #ifndef NDEBUG
505   // Check correctness of the ordering
506   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
507     SUnit *SU = &SUnits[i];
508     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
509          I != E; ++I) {
510        assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] && 
511        "Wrong topological sorting");
512     }
513   }
514 #endif
515 }
516
517 /// AddPred - adds an edge from SUnit X to SUnit Y.
518 /// Updates the topological ordering if required.
519 bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
520                  unsigned PhyReg, int Cost) {
521   int UpperBound, LowerBound;
522   LowerBound = Node2Index[Y->NodeNum];
523   UpperBound = Node2Index[X->NodeNum];
524   bool HasLoop = false;
525   // Is Ord(X) < Ord(Y) ?
526   if (LowerBound < UpperBound) {
527     // Update the topological order.
528     Visited.reset();
529     DFS(Y, UpperBound, HasLoop);
530     assert(!HasLoop && "Inserted edge creates a loop!");
531     // Recompute topological indexes.
532     Shift(Visited, LowerBound, UpperBound);
533   }
534   // Now really insert the edge.
535   return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
536 }
537
538 /// RemovePred - This removes the specified node N from the predecessors of 
539 /// the current node M. Updates the topological ordering if required.
540 bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N, 
541                                    bool isCtrl, bool isSpecial) {
542   // InitDAGTopologicalSorting();
543   return M->removePred(N, isCtrl, isSpecial);
544 }
545
546 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
547 /// all nodes affected by the edge insertion. These nodes will later get new
548 /// topological indexes by means of the Shift method.
549 void ScheduleDAGRRList::DFS(SUnit *SU, int UpperBound, bool& HasLoop) {
550   std::vector<SUnit*> WorkList;
551   WorkList.reserve(SUnits.size()); 
552
553   WorkList.push_back(SU);
554   while (!WorkList.empty()) {
555     SU = WorkList.back();
556     WorkList.pop_back();
557     Visited.set(SU->NodeNum);
558     for (int I = SU->Succs.size()-1; I >= 0; --I) {
559       int s = SU->Succs[I].Dep->NodeNum;
560       if (Node2Index[s] == UpperBound) {
561         HasLoop = true; 
562         return;
563       }
564       // Visit successors if not already and in affected region.
565       if (!Visited.test(s) && Node2Index[s] < UpperBound) {
566         WorkList.push_back(SU->Succs[I].Dep);
567       } 
568     } 
569   }
570 }
571
572 /// Shift - Renumber the nodes so that the topological ordering is 
573 /// preserved.
574 void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound, 
575                               int UpperBound) {
576   std::vector<int> L;
577   int shift = 0;
578   int i;
579
580   for (i = LowerBound; i <= UpperBound; ++i) {
581     // w is node at topological index i.
582     int w = Index2Node[i];
583     if (Visited.test(w)) {
584       // Unmark.
585       Visited.reset(w);
586       L.push_back(w);
587       shift = shift + 1;
588     } else {
589       Allocate(w, i - shift);
590     }
591   }
592
593   for (unsigned j = 0; j < L.size(); ++j) {
594     Allocate(L[j], i - shift);
595     i = i + 1;
596   }
597 }
598
599
600 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
601 /// create a cycle.
602 bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
603   if (IsReachable(TargetSU, SU))
604     return true;
605   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
606        I != E; ++I)
607     if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
608       return true;
609   return false;
610 }
611
612 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
613 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
614 /// SUnit. Also returns if a successor is unscheduled in the process.
615 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
616                                           unsigned &CurCycle) {
617   SUnit *OldSU = NULL;
618   while (CurCycle > BtCycle) {
619     OldSU = Sequence.back();
620     Sequence.pop_back();
621     if (SU->isSucc(OldSU))
622       // Don't try to remove SU from AvailableQueue.
623       SU->isAvailable = false;
624     UnscheduleNodeBottomUp(OldSU);
625     --CurCycle;
626   }
627
628       
629   if (SU->isSucc(OldSU)) {
630     assert(false && "Something is wrong!");
631     abort();
632   }
633
634   ++NumBacktracks;
635 }
636
637 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
638 /// successors to the newly created node.
639 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
640   if (SU->FlaggedNodes.size())
641     return NULL;
642
643   SDNode *N = SU->Node;
644   if (!N)
645     return NULL;
646
647   SUnit *NewSU;
648   bool TryUnfold = false;
649   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
650     MVT VT = N->getValueType(i);
651     if (VT == MVT::Flag)
652       return NULL;
653     else if (VT == MVT::Other)
654       TryUnfold = true;
655   }
656   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
657     const SDOperand &Op = N->getOperand(i);
658     MVT VT = Op.Val->getValueType(Op.ResNo);
659     if (VT == MVT::Flag)
660       return NULL;
661   }
662
663   if (TryUnfold) {
664     SmallVector<SDNode*, 2> NewNodes;
665     if (!TII->unfoldMemoryOperand(DAG, N, NewNodes))
666       return NULL;
667
668     DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
669     assert(NewNodes.size() == 2 && "Expected a load folding node!");
670
671     N = NewNodes[1];
672     SDNode *LoadNode = NewNodes[0];
673     unsigned NumVals = N->getNumValues();
674     unsigned OldNumVals = SU->Node->getNumValues();
675     for (unsigned i = 0; i != NumVals; ++i)
676       DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i), SDOperand(N, i));
677     DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
678                                   SDOperand(LoadNode, 1));
679
680     SUnit *NewSU = CreateNewSUnit(N);
681     assert(N->getNodeId() == -1 && "Node already inserted!");
682     N->setNodeId(NewSU->NodeNum);
683       
684     const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
685     for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
686       if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
687         NewSU->isTwoAddress = true;
688         break;
689       }
690     }
691     if (TID.isCommutable())
692       NewSU->isCommutable = true;
693     // FIXME: Calculate height / depth and propagate the changes?
694     NewSU->Depth = SU->Depth;
695     NewSU->Height = SU->Height;
696     ComputeLatency(NewSU);
697
698     // LoadNode may already exist. This can happen when there is another
699     // load from the same location and producing the same type of value
700     // but it has different alignment or volatileness.
701     bool isNewLoad = true;
702     SUnit *LoadSU;
703     if (LoadNode->getNodeId() != -1) {
704       LoadSU = &SUnits[LoadNode->getNodeId()];
705       isNewLoad = false;
706     } else {
707       LoadSU = CreateNewSUnit(LoadNode);
708       LoadNode->setNodeId(LoadSU->NodeNum);
709
710       LoadSU->Depth = SU->Depth;
711       LoadSU->Height = SU->Height;
712       ComputeLatency(LoadSU);
713     }
714
715     SUnit *ChainPred = NULL;
716     SmallVector<SDep, 4> ChainSuccs;
717     SmallVector<SDep, 4> LoadPreds;
718     SmallVector<SDep, 4> NodePreds;
719     SmallVector<SDep, 4> NodeSuccs;
720     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
721          I != E; ++I) {
722       if (I->isCtrl)
723         ChainPred = I->Dep;
724       else if (I->Dep->Node && I->Dep->Node->isOperandOf(LoadNode))
725         LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
726       else
727         NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
728     }
729     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
730          I != E; ++I) {
731       if (I->isCtrl)
732         ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
733                                   I->isCtrl, I->isSpecial));
734       else
735         NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
736                                  I->isCtrl, I->isSpecial));
737     }
738
739     if (ChainPred) {
740       RemovePred(SU, ChainPred, true, false);
741       if (isNewLoad)
742         AddPred(LoadSU, ChainPred, true, false);
743     }
744     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
745       SDep *Pred = &LoadPreds[i];
746       RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
747       if (isNewLoad) {
748         AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
749                 Pred->Reg, Pred->Cost);
750       }
751     }
752     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
753       SDep *Pred = &NodePreds[i];
754       RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
755       AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
756               Pred->Reg, Pred->Cost);
757     }
758     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
759       SDep *Succ = &NodeSuccs[i];
760       RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
761       AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
762               Succ->Reg, Succ->Cost);
763     }
764     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
765       SDep *Succ = &ChainSuccs[i];
766       RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
767       if (isNewLoad) {
768         AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
769                 Succ->Reg, Succ->Cost);
770       }
771     } 
772     if (isNewLoad) {
773       AddPred(NewSU, LoadSU, false, false);
774     }
775
776     if (isNewLoad)
777       AvailableQueue->addNode(LoadSU);
778     AvailableQueue->addNode(NewSU);
779
780     ++NumUnfolds;
781
782     if (NewSU->NumSuccsLeft == 0) {
783       NewSU->isAvailable = true;
784       return NewSU;
785     }
786     SU = NewSU;
787   }
788
789   DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
790   NewSU = CreateClone(SU);
791
792   // New SUnit has the exact same predecessors.
793   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
794        I != E; ++I)
795     if (!I->isSpecial) {
796       AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
797       NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
798     }
799
800   // Only copy scheduled successors. Cut them from old node's successor
801   // list and move them over.
802   SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
803   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
804        I != E; ++I) {
805     if (I->isSpecial)
806       continue;
807     if (I->Dep->isScheduled) {
808       NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
809       AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
810       DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
811     }
812   }
813   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
814     SUnit *Succ = DelDeps[i].first;
815     bool isCtrl = DelDeps[i].second;
816     RemovePred(Succ, SU, isCtrl, false);
817   }
818
819   AvailableQueue->updateNode(SU);
820   AvailableQueue->addNode(NewSU);
821
822   ++NumDups;
823   return NewSU;
824 }
825
826 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
827 /// and move all scheduled successors of the given SUnit to the last copy.
828 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
829                                               const TargetRegisterClass *DestRC,
830                                               const TargetRegisterClass *SrcRC,
831                                                SmallVector<SUnit*, 2> &Copies) {
832   SUnit *CopyFromSU = CreateNewSUnit(NULL);
833   CopyFromSU->CopySrcRC = SrcRC;
834   CopyFromSU->CopyDstRC = DestRC;
835   CopyFromSU->Depth = SU->Depth;
836   CopyFromSU->Height = SU->Height;
837
838   SUnit *CopyToSU = CreateNewSUnit(NULL);
839   CopyToSU->CopySrcRC = DestRC;
840   CopyToSU->CopyDstRC = SrcRC;
841
842   // Only copy scheduled successors. Cut them from old node's successor
843   // list and move them over.
844   SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
845   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
846        I != E; ++I) {
847     if (I->isSpecial)
848       continue;
849     if (I->Dep->isScheduled) {
850       CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
851       AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
852       DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
853     }
854   }
855   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
856     SUnit *Succ = DelDeps[i].first;
857     bool isCtrl = DelDeps[i].second;
858     RemovePred(Succ, SU, isCtrl, false);
859   }
860
861   AddPred(CopyFromSU, SU, false, false, Reg, -1);
862   AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
863
864   AvailableQueue->updateNode(SU);
865   AvailableQueue->addNode(CopyFromSU);
866   AvailableQueue->addNode(CopyToSU);
867   Copies.push_back(CopyFromSU);
868   Copies.push_back(CopyToSU);
869
870   ++NumCCCopies;
871 }
872
873 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
874 /// definition of the specified node.
875 /// FIXME: Move to SelectionDAG?
876 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
877                                  const TargetInstrInfo *TII) {
878   const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
879   assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
880   unsigned NumRes = TID.getNumDefs();
881   for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
882     if (Reg == *ImpDef)
883       break;
884     ++NumRes;
885   }
886   return N->getValueType(NumRes);
887 }
888
889 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
890 /// scheduling of the given node to satisfy live physical register dependencies.
891 /// If the specific node is the last one that's available to schedule, do
892 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
893 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
894                                                  SmallVector<unsigned, 4> &LRegs){
895   if (LiveRegs.empty())
896     return false;
897
898   SmallSet<unsigned, 4> RegAdded;
899   // If this node would clobber any "live" register, then it's not ready.
900   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
901        I != E; ++I) {
902     if (I->Cost < 0)  {
903       unsigned Reg = I->Reg;
904       if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
905         if (RegAdded.insert(Reg))
906           LRegs.push_back(Reg);
907       }
908       for (const unsigned *Alias = TRI->getAliasSet(Reg);
909            *Alias; ++Alias)
910         if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
911           if (RegAdded.insert(*Alias))
912             LRegs.push_back(*Alias);
913         }
914     }
915   }
916
917   for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
918     SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
919     if (!Node || !Node->isTargetOpcode())
920       continue;
921     const TargetInstrDesc &TID = TII->get(Node->getTargetOpcode());
922     if (!TID.ImplicitDefs)
923       continue;
924     for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
925       if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
926         if (RegAdded.insert(*Reg))
927           LRegs.push_back(*Reg);
928       }
929       for (const unsigned *Alias = TRI->getAliasSet(*Reg);
930            *Alias; ++Alias)
931         if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
932           if (RegAdded.insert(*Alias))
933             LRegs.push_back(*Alias);
934         }
935     }
936   }
937   return !LRegs.empty();
938 }
939
940
941 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
942 /// schedulers.
943 void ScheduleDAGRRList::ListScheduleBottomUp() {
944   unsigned CurCycle = 0;
945   // Add root to Available queue.
946   if (!SUnits.empty()) {
947     SUnit *RootSU = &SUnits[DAG.getRoot().Val->getNodeId()];
948     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
949     RootSU->isAvailable = true;
950     AvailableQueue->push(RootSU);
951   }
952
953   // While Available queue is not empty, grab the node with the highest
954   // priority. If it is not ready put it back.  Schedule the node.
955   SmallVector<SUnit*, 4> NotReady;
956   Sequence.reserve(SUnits.size());
957   while (!AvailableQueue->empty()) {
958     bool Delayed = false;
959     DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
960     SUnit *CurSU = AvailableQueue->pop();
961     while (CurSU) {
962       if (CurSU->CycleBound <= CurCycle) {
963         SmallVector<unsigned, 4> LRegs;
964         if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
965           break;
966         Delayed = true;
967         LRegsMap.insert(std::make_pair(CurSU, LRegs));
968       }
969
970       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
971       NotReady.push_back(CurSU);
972       CurSU = AvailableQueue->pop();
973     }
974
975     // All candidates are delayed due to live physical reg dependencies.
976     // Try backtracking, code duplication, or inserting cross class copies
977     // to resolve it.
978     if (Delayed && !CurSU) {
979       for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
980         SUnit *TrySU = NotReady[i];
981         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
982
983         // Try unscheduling up to the point where it's safe to schedule
984         // this node.
985         unsigned LiveCycle = CurCycle;
986         for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
987           unsigned Reg = LRegs[j];
988           unsigned LCycle = LiveRegCycles[Reg];
989           LiveCycle = std::min(LiveCycle, LCycle);
990         }
991         SUnit *OldSU = Sequence[LiveCycle];
992         if (!WillCreateCycle(TrySU, OldSU))  {
993           BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
994           // Force the current node to be scheduled before the node that
995           // requires the physical reg dep.
996           if (OldSU->isAvailable) {
997             OldSU->isAvailable = false;
998             AvailableQueue->remove(OldSU);
999           }
1000           AddPred(TrySU, OldSU, true, true);
1001           // If one or more successors has been unscheduled, then the current
1002           // node is no longer avaialable. Schedule a successor that's now
1003           // available instead.
1004           if (!TrySU->isAvailable)
1005             CurSU = AvailableQueue->pop();
1006           else {
1007             CurSU = TrySU;
1008             TrySU->isPending = false;
1009             NotReady.erase(NotReady.begin()+i);
1010           }
1011           break;
1012         }
1013       }
1014
1015       if (!CurSU) {
1016         // Can't backtrack. Try duplicating the nodes that produces these
1017         // "expensive to copy" values to break the dependency. In case even
1018         // that doesn't work, insert cross class copies.
1019         SUnit *TrySU = NotReady[0];
1020         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1021         assert(LRegs.size() == 1 && "Can't handle this yet!");
1022         unsigned Reg = LRegs[0];
1023         SUnit *LRDef = LiveRegDefs[Reg];
1024         SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1025         if (!NewDef) {
1026           // Issue expensive cross register class copies.
1027           MVT VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
1028           const TargetRegisterClass *RC =
1029             TRI->getPhysicalRegisterRegClass(Reg, VT);
1030           const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1031           if (!DestRC) {
1032             assert(false && "Don't know how to copy this physical register!");
1033             abort();
1034           }
1035           SmallVector<SUnit*, 2> Copies;
1036           InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1037           DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1038                << " to SU #" << Copies.front()->NodeNum << "\n";
1039           AddPred(TrySU, Copies.front(), true, true);
1040           NewDef = Copies.back();
1041         }
1042
1043         DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1044              << " to SU #" << TrySU->NodeNum << "\n";
1045         LiveRegDefs[Reg] = NewDef;
1046         AddPred(NewDef, TrySU, true, true);
1047         TrySU->isAvailable = false;
1048         CurSU = NewDef;
1049       }
1050
1051       if (!CurSU) {
1052         assert(false && "Unable to resolve live physical register dependencies!");
1053         abort();
1054       }
1055     }
1056
1057     // Add the nodes that aren't ready back onto the available list.
1058     for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1059       NotReady[i]->isPending = false;
1060       // May no longer be available due to backtracking.
1061       if (NotReady[i]->isAvailable)
1062         AvailableQueue->push(NotReady[i]);
1063     }
1064     NotReady.clear();
1065
1066     if (!CurSU)
1067       Sequence.push_back(0);
1068     else {
1069       ScheduleNodeBottomUp(CurSU, CurCycle);
1070       Sequence.push_back(CurSU);
1071     }
1072     ++CurCycle;
1073   }
1074
1075   // Reverse the order if it is bottom up.
1076   std::reverse(Sequence.begin(), Sequence.end());
1077   
1078   
1079 #ifndef NDEBUG
1080   // Verify that all SUnits were scheduled.
1081   bool AnyNotSched = false;
1082   unsigned DeadNodes = 0;
1083   unsigned Noops = 0;
1084   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1085     if (!SUnits[i].isScheduled) {
1086       if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1087         ++DeadNodes;
1088         continue;
1089       }
1090       if (!AnyNotSched)
1091         cerr << "*** List scheduling failed! ***\n";
1092       SUnits[i].dump(&DAG);
1093       cerr << "has not been scheduled!\n";
1094       AnyNotSched = true;
1095     }
1096     if (SUnits[i].NumSuccsLeft != 0) {
1097       if (!AnyNotSched)
1098         cerr << "*** List scheduling failed! ***\n";
1099       SUnits[i].dump(&DAG);
1100       cerr << "has successors left!\n";
1101       AnyNotSched = true;
1102     }
1103   }
1104   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1105     if (!Sequence[i])
1106       ++Noops;
1107   assert(!AnyNotSched);
1108   assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1109          "The number of nodes scheduled doesn't match the expected number!");
1110 #endif
1111 }
1112
1113 //===----------------------------------------------------------------------===//
1114 //  Top-Down Scheduling
1115 //===----------------------------------------------------------------------===//
1116
1117 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1118 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1119 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain, 
1120                                     unsigned CurCycle) {
1121   // FIXME: the distance between two nodes is not always == the predecessor's
1122   // latency. For example, the reader can very well read the register written
1123   // by the predecessor later than the issue cycle. It also depends on the
1124   // interrupt model (drain vs. freeze).
1125   SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
1126
1127   --SuccSU->NumPredsLeft;
1128   
1129 #ifndef NDEBUG
1130   if (SuccSU->NumPredsLeft < 0) {
1131     cerr << "*** List scheduling failed! ***\n";
1132     SuccSU->dump(&DAG);
1133     cerr << " has been released too many times!\n";
1134     assert(0);
1135   }
1136 #endif
1137   
1138   if (SuccSU->NumPredsLeft == 0) {
1139     SuccSU->isAvailable = true;
1140     AvailableQueue->push(SuccSU);
1141   }
1142 }
1143
1144
1145 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1146 /// count of its successors. If a successor pending count is zero, add it to
1147 /// the Available queue.
1148 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1149   DOUT << "*** Scheduling [" << CurCycle << "]: ";
1150   DEBUG(SU->dump(&DAG));
1151   SU->Cycle = CurCycle;
1152
1153   AvailableQueue->ScheduledNode(SU);
1154
1155   // Top down: release successors
1156   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1157        I != E; ++I)
1158     ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
1159   SU->isScheduled = true;
1160 }
1161
1162 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1163 /// schedulers.
1164 void ScheduleDAGRRList::ListScheduleTopDown() {
1165   unsigned CurCycle = 0;
1166
1167   // All leaves to Available queue.
1168   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1169     // It is available if it has no predecessors.
1170     if (SUnits[i].Preds.empty()) {
1171       AvailableQueue->push(&SUnits[i]);
1172       SUnits[i].isAvailable = true;
1173     }
1174   }
1175   
1176   // While Available queue is not empty, grab the node with the highest
1177   // priority. If it is not ready put it back.  Schedule the node.
1178   std::vector<SUnit*> NotReady;
1179   Sequence.reserve(SUnits.size());
1180   while (!AvailableQueue->empty()) {
1181     SUnit *CurSU = AvailableQueue->pop();
1182     while (CurSU && CurSU->CycleBound > CurCycle) {
1183       NotReady.push_back(CurSU);
1184       CurSU = AvailableQueue->pop();
1185     }
1186     
1187     // Add the nodes that aren't ready back onto the available list.
1188     AvailableQueue->push_all(NotReady);
1189     NotReady.clear();
1190
1191     if (!CurSU)
1192       Sequence.push_back(0);
1193     else {
1194       ScheduleNodeTopDown(CurSU, CurCycle);
1195       Sequence.push_back(CurSU);
1196     }
1197     ++CurCycle;
1198   }
1199   
1200   
1201 #ifndef NDEBUG
1202   // Verify that all SUnits were scheduled.
1203   bool AnyNotSched = false;
1204   unsigned DeadNodes = 0;
1205   unsigned Noops = 0;
1206   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1207     if (!SUnits[i].isScheduled) {
1208       if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1209         ++DeadNodes;
1210         continue;
1211       }
1212       if (!AnyNotSched)
1213         cerr << "*** List scheduling failed! ***\n";
1214       SUnits[i].dump(&DAG);
1215       cerr << "has not been scheduled!\n";
1216       AnyNotSched = true;
1217     }
1218     if (SUnits[i].NumPredsLeft != 0) {
1219       if (!AnyNotSched)
1220         cerr << "*** List scheduling failed! ***\n";
1221       SUnits[i].dump(&DAG);
1222       cerr << "has predecessors left!\n";
1223       AnyNotSched = true;
1224     }
1225   }
1226   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1227     if (!Sequence[i])
1228       ++Noops;
1229   assert(!AnyNotSched);
1230   assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1231          "The number of nodes scheduled doesn't match the expected number!");
1232 #endif
1233 }
1234
1235
1236
1237 //===----------------------------------------------------------------------===//
1238 //                RegReductionPriorityQueue Implementation
1239 //===----------------------------------------------------------------------===//
1240 //
1241 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1242 // to reduce register pressure.
1243 // 
1244 namespace {
1245   template<class SF>
1246   class RegReductionPriorityQueue;
1247   
1248   /// Sorting functions for the Available queue.
1249   struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1250     RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1251     bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1252     bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1253     
1254     bool operator()(const SUnit* left, const SUnit* right) const;
1255   };
1256
1257   struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1258     RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1259     td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1260     td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1261     
1262     bool operator()(const SUnit* left, const SUnit* right) const;
1263   };
1264 }  // end anonymous namespace
1265
1266 static inline bool isCopyFromLiveIn(const SUnit *SU) {
1267   SDNode *N = SU->Node;
1268   return N && N->getOpcode() == ISD::CopyFromReg &&
1269     N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1270 }
1271
1272 namespace {
1273   template<class SF>
1274   class VISIBILITY_HIDDEN RegReductionPriorityQueue
1275    : public SchedulingPriorityQueue {
1276     PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
1277     unsigned currentQueueId;
1278
1279   public:
1280     RegReductionPriorityQueue() :
1281     Queue(SF(this)), currentQueueId(0) {}
1282     
1283     virtual void initNodes(std::vector<SUnit> &sunits) {}
1284
1285     virtual void addNode(const SUnit *SU) {}
1286
1287     virtual void updateNode(const SUnit *SU) {}
1288
1289     virtual void releaseState() {}
1290     
1291     virtual unsigned getNodePriority(const SUnit *SU) const {
1292       return 0;
1293     }
1294     
1295     unsigned size() const { return Queue.size(); }
1296
1297     bool empty() const { return Queue.empty(); }
1298     
1299     void push(SUnit *U) {
1300       assert(!U->NodeQueueId && "Node in the queue already");
1301       U->NodeQueueId = ++currentQueueId;
1302       Queue.push(U);
1303     }
1304
1305     void push_all(const std::vector<SUnit *> &Nodes) {
1306       for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1307         push(Nodes[i]);
1308     }
1309     
1310     SUnit *pop() {
1311       if (empty()) return NULL;
1312       SUnit *V = Queue.top();
1313       Queue.pop();
1314       V->NodeQueueId = 0;
1315       return V;
1316     }
1317
1318     void remove(SUnit *SU) {
1319       assert(!Queue.empty() && "Queue is empty!");
1320       assert(SU->NodeQueueId != 0 && "Not in queue!");
1321       Queue.erase_one(SU);
1322       SU->NodeQueueId = 0;
1323     }
1324   };
1325
1326   class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1327    : public RegReductionPriorityQueue<bu_ls_rr_sort> {
1328     // SUnits - The SUnits for the current graph.
1329     const std::vector<SUnit> *SUnits;
1330     
1331     // SethiUllmanNumbers - The SethiUllman number for each node.
1332     std::vector<unsigned> SethiUllmanNumbers;
1333
1334     const TargetInstrInfo *TII;
1335     const TargetRegisterInfo *TRI;
1336     ScheduleDAGRRList *scheduleDAG;
1337   public:
1338     explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii,
1339                                          const TargetRegisterInfo *tri)
1340       : TII(tii), TRI(tri), scheduleDAG(NULL) {}
1341
1342     void initNodes(std::vector<SUnit> &sunits) {
1343       SUnits = &sunits;
1344       // Add pseudo dependency edges for two-address nodes.
1345       AddPseudoTwoAddrDeps();
1346       // Calculate node priorities.
1347       CalculateSethiUllmanNumbers();
1348     }
1349
1350     void addNode(const SUnit *SU) {
1351       SethiUllmanNumbers.resize(SUnits->size(), 0);
1352       CalcNodeSethiUllmanNumber(SU);
1353     }
1354
1355     void updateNode(const SUnit *SU) {
1356       SethiUllmanNumbers[SU->NodeNum] = 0;
1357       CalcNodeSethiUllmanNumber(SU);
1358     }
1359
1360     void releaseState() {
1361       SUnits = 0;
1362       SethiUllmanNumbers.clear();
1363     }
1364
1365     unsigned getNodePriority(const SUnit *SU) const {
1366       assert(SU->NodeNum < SethiUllmanNumbers.size());
1367       unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1368       if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1369         // CopyFromReg should be close to its def because it restricts
1370         // allocation choices. But if it is a livein then perhaps we want it
1371         // closer to its uses so it can be coalesced.
1372         return 0xffff;
1373       else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1374         // CopyToReg should be close to its uses to facilitate coalescing and
1375         // avoid spilling.
1376         return 0;
1377       else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1378                Opc == TargetInstrInfo::INSERT_SUBREG)
1379         // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1380         // facilitate coalescing.
1381         return 0;
1382       else if (SU->NumSuccs == 0)
1383         // If SU does not have a use, i.e. it doesn't produce a value that would
1384         // be consumed (e.g. store), then it terminates a chain of computation.
1385         // Give it a large SethiUllman number so it will be scheduled right
1386         // before its predecessors that it doesn't lengthen their live ranges.
1387         return 0xffff;
1388       else if (SU->NumPreds == 0)
1389         // If SU does not have a def, schedule it close to its uses because it
1390         // does not lengthen any live ranges.
1391         return 0;
1392       else
1393         return SethiUllmanNumbers[SU->NodeNum];
1394     }
1395
1396     void setScheduleDAG(ScheduleDAGRRList *scheduleDag) { 
1397       scheduleDAG = scheduleDag; 
1398     }
1399
1400   private:
1401     bool canClobber(const SUnit *SU, const SUnit *Op);
1402     void AddPseudoTwoAddrDeps();
1403     void CalculateSethiUllmanNumbers();
1404     unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1405   };
1406
1407
1408   class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1409    : public RegReductionPriorityQueue<td_ls_rr_sort> {
1410     // SUnits - The SUnits for the current graph.
1411     const std::vector<SUnit> *SUnits;
1412     
1413     // SethiUllmanNumbers - The SethiUllman number for each node.
1414     std::vector<unsigned> SethiUllmanNumbers;
1415
1416   public:
1417     TDRegReductionPriorityQueue() {}
1418
1419     void initNodes(std::vector<SUnit> &sunits) {
1420       SUnits = &sunits;
1421       // Calculate node priorities.
1422       CalculateSethiUllmanNumbers();
1423     }
1424
1425     void addNode(const SUnit *SU) {
1426       SethiUllmanNumbers.resize(SUnits->size(), 0);
1427       CalcNodeSethiUllmanNumber(SU);
1428     }
1429
1430     void updateNode(const SUnit *SU) {
1431       SethiUllmanNumbers[SU->NodeNum] = 0;
1432       CalcNodeSethiUllmanNumber(SU);
1433     }
1434
1435     void releaseState() {
1436       SUnits = 0;
1437       SethiUllmanNumbers.clear();
1438     }
1439
1440     unsigned getNodePriority(const SUnit *SU) const {
1441       assert(SU->NodeNum < SethiUllmanNumbers.size());
1442       return SethiUllmanNumbers[SU->NodeNum];
1443     }
1444
1445   private:
1446     void CalculateSethiUllmanNumbers();
1447     unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1448   };
1449 }
1450
1451 /// closestSucc - Returns the scheduled cycle of the successor which is
1452 /// closet to the current cycle.
1453 static unsigned closestSucc(const SUnit *SU) {
1454   unsigned MaxCycle = 0;
1455   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1456        I != E; ++I) {
1457     unsigned Cycle = I->Dep->Cycle;
1458     // If there are bunch of CopyToRegs stacked up, they should be considered
1459     // to be at the same position.
1460     if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
1461       Cycle = closestSucc(I->Dep)+1;
1462     if (Cycle > MaxCycle)
1463       MaxCycle = Cycle;
1464   }
1465   return MaxCycle;
1466 }
1467
1468 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1469 /// for scratch registers. Live-in operands and live-out results don't count
1470 /// since they are "fixed".
1471 static unsigned calcMaxScratches(const SUnit *SU) {
1472   unsigned Scratches = 0;
1473   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1474        I != E; ++I) {
1475     if (I->isCtrl) continue;  // ignore chain preds
1476     if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyFromReg)
1477       Scratches++;
1478   }
1479   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1480        I != E; ++I) {
1481     if (I->isCtrl) continue;  // ignore chain succs
1482     if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyToReg)
1483       Scratches += 10;
1484   }
1485   return Scratches;
1486 }
1487
1488 // Bottom up
1489 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1490
1491   unsigned LPriority = SPQ->getNodePriority(left);
1492   unsigned RPriority = SPQ->getNodePriority(right);
1493   if (LPriority != RPriority)
1494     return LPriority > RPriority;
1495
1496   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1497   // e.g.
1498   // t1 = op t2, c1
1499   // t3 = op t4, c2
1500   //
1501   // and the following instructions are both ready.
1502   // t2 = op c3
1503   // t4 = op c4
1504   //
1505   // Then schedule t2 = op first.
1506   // i.e.
1507   // t4 = op c4
1508   // t2 = op c3
1509   // t1 = op t2, c1
1510   // t3 = op t4, c2
1511   //
1512   // This creates more short live intervals.
1513   unsigned LDist = closestSucc(left);
1514   unsigned RDist = closestSucc(right);
1515   if (LDist != RDist)
1516     return LDist < RDist;
1517
1518   // Intuitively, it's good to push down instructions whose results are
1519   // liveout so their long live ranges won't conflict with other values
1520   // which are needed inside the BB. Further prioritize liveout instructions
1521   // by the number of operands which are calculated within the BB.
1522   unsigned LScratch = calcMaxScratches(left);
1523   unsigned RScratch = calcMaxScratches(right);
1524   if (LScratch != RScratch)
1525     return LScratch > RScratch;
1526
1527   if (left->Height != right->Height)
1528     return left->Height > right->Height;
1529   
1530   if (left->Depth != right->Depth)
1531     return left->Depth < right->Depth;
1532
1533   if (left->CycleBound != right->CycleBound)
1534     return left->CycleBound > right->CycleBound;
1535
1536   assert(left->NodeQueueId && right->NodeQueueId && 
1537          "NodeQueueId cannot be zero");
1538   return (left->NodeQueueId > right->NodeQueueId);
1539 }
1540
1541 bool
1542 BURegReductionPriorityQueue::canClobber(const SUnit *SU, const SUnit *Op) {
1543   if (SU->isTwoAddress) {
1544     unsigned Opc = SU->Node->getTargetOpcode();
1545     const TargetInstrDesc &TID = TII->get(Opc);
1546     unsigned NumRes = TID.getNumDefs();
1547     unsigned NumOps = TID.getNumOperands() - NumRes;
1548     for (unsigned i = 0; i != NumOps; ++i) {
1549       if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1550         SDNode *DU = SU->Node->getOperand(i).Val;
1551         if (DU->getNodeId() != -1 &&
1552             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1553           return true;
1554       }
1555     }
1556   }
1557   return false;
1558 }
1559
1560
1561 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1562 /// CopyToReg node.
1563 static bool hasCopyToRegUse(SUnit *SU) {
1564   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1565        I != E; ++I) {
1566     if (I->isCtrl) continue;
1567     SUnit *SuccSU = I->Dep;
1568     if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1569       return true;
1570   }
1571   return false;
1572 }
1573
1574 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1575 /// physical register defs.
1576 static bool canClobberPhysRegDefs(SUnit *SuccSU, SUnit *SU,
1577                                   const TargetInstrInfo *TII,
1578                                   const TargetRegisterInfo *TRI) {
1579   SDNode *N = SuccSU->Node;
1580   unsigned NumDefs = TII->get(N->getTargetOpcode()).getNumDefs();
1581   const unsigned *ImpDefs = TII->get(N->getTargetOpcode()).getImplicitDefs();
1582   assert(ImpDefs && "Caller should check hasPhysRegDefs");
1583   const unsigned *SUImpDefs =
1584     TII->get(SU->Node->getTargetOpcode()).getImplicitDefs();
1585   if (!SUImpDefs)
1586     return false;
1587   for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1588     MVT VT = N->getValueType(i);
1589     if (VT == MVT::Flag || VT == MVT::Other)
1590       continue;
1591     unsigned Reg = ImpDefs[i - NumDefs];
1592     for (;*SUImpDefs; ++SUImpDefs) {
1593       unsigned SUReg = *SUImpDefs;
1594       if (TRI->regsOverlap(Reg, SUReg))
1595         return true;
1596     }
1597   }
1598   return false;
1599 }
1600
1601 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1602 /// it as a def&use operand. Add a pseudo control edge from it to the other
1603 /// node (if it won't create a cycle) so the two-address one will be scheduled
1604 /// first (lower in the schedule). If both nodes are two-address, favor the
1605 /// one that has a CopyToReg use (more likely to be a loop induction update).
1606 /// If both are two-address, but one is commutable while the other is not
1607 /// commutable, favor the one that's not commutable.
1608 void BURegReductionPriorityQueue::AddPseudoTwoAddrDeps() {
1609   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1610     SUnit *SU = (SUnit *)&((*SUnits)[i]);
1611     if (!SU->isTwoAddress)
1612       continue;
1613
1614     SDNode *Node = SU->Node;
1615     if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
1616       continue;
1617
1618     unsigned Opc = Node->getTargetOpcode();
1619     const TargetInstrDesc &TID = TII->get(Opc);
1620     unsigned NumRes = TID.getNumDefs();
1621     unsigned NumOps = TID.getNumOperands() - NumRes;
1622     for (unsigned j = 0; j != NumOps; ++j) {
1623       if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) != -1) {
1624         SDNode *DU = SU->Node->getOperand(j).Val;
1625         if (DU->getNodeId() == -1)
1626           continue;
1627         const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1628         if (!DUSU) continue;
1629         for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1630              E = DUSU->Succs.end(); I != E; ++I) {
1631           if (I->isCtrl) continue;
1632           SUnit *SuccSU = I->Dep;
1633           if (SuccSU == SU)
1634             continue;
1635           // Be conservative. Ignore if nodes aren't at roughly the same
1636           // depth and height.
1637           if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1638             continue;
1639           if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1640             continue;
1641           // Don't constrain nodes with physical register defs if the
1642           // predecessor can clobber them.
1643           if (SuccSU->hasPhysRegDefs) {
1644             if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1645               continue;
1646           }
1647           // Don't constraint extract_subreg / insert_subreg these may be
1648           // coalesced away. We don't them close to their uses.
1649           unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1650           if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1651               SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1652             continue;
1653           if ((!canClobber(SuccSU, DUSU) ||
1654                (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1655                (!SU->isCommutable && SuccSU->isCommutable)) &&
1656               !scheduleDAG->IsReachable(SuccSU, SU)) {
1657             DOUT << "Adding an edge from SU # " << SU->NodeNum
1658                  << " to SU #" << SuccSU->NodeNum << "\n";
1659             scheduleDAG->AddPred(SU, SuccSU, true, true);
1660           }
1661         }
1662       }
1663     }
1664   }
1665 }
1666
1667 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number. 
1668 /// Smaller number is the higher priority.
1669 unsigned BURegReductionPriorityQueue::
1670 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1671   unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1672   if (SethiUllmanNumber != 0)
1673     return SethiUllmanNumber;
1674
1675   unsigned Extra = 0;
1676   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1677        I != E; ++I) {
1678     if (I->isCtrl) continue;  // ignore chain preds
1679     SUnit *PredSU = I->Dep;
1680     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1681     if (PredSethiUllman > SethiUllmanNumber) {
1682       SethiUllmanNumber = PredSethiUllman;
1683       Extra = 0;
1684     } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1685       ++Extra;
1686   }
1687
1688   SethiUllmanNumber += Extra;
1689
1690   if (SethiUllmanNumber == 0)
1691     SethiUllmanNumber = 1;
1692   
1693   return SethiUllmanNumber;
1694 }
1695
1696 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1697 /// scheduling units.
1698 void BURegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1699   SethiUllmanNumbers.assign(SUnits->size(), 0);
1700   
1701   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1702     CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1703 }
1704
1705 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1706 /// predecessors of the successors of the SUnit SU. Stop when the provided
1707 /// limit is exceeded.
1708 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU, 
1709                                                     unsigned Limit) {
1710   unsigned Sum = 0;
1711   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1712        I != E; ++I) {
1713     SUnit *SuccSU = I->Dep;
1714     for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1715          EE = SuccSU->Preds.end(); II != EE; ++II) {
1716       SUnit *PredSU = II->Dep;
1717       if (!PredSU->isScheduled)
1718         if (++Sum > Limit)
1719           return Sum;
1720     }
1721   }
1722   return Sum;
1723 }
1724
1725
1726 // Top down
1727 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1728   unsigned LPriority = SPQ->getNodePriority(left);
1729   unsigned RPriority = SPQ->getNodePriority(right);
1730   bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1731   bool RIsTarget = right->Node && right->Node->isTargetOpcode();
1732   bool LIsFloater = LIsTarget && left->NumPreds == 0;
1733   bool RIsFloater = RIsTarget && right->NumPreds == 0;
1734   unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1735   unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1736
1737   if (left->NumSuccs == 0 && right->NumSuccs != 0)
1738     return false;
1739   else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1740     return true;
1741
1742   if (LIsFloater)
1743     LBonus -= 2;
1744   if (RIsFloater)
1745     RBonus -= 2;
1746   if (left->NumSuccs == 1)
1747     LBonus += 2;
1748   if (right->NumSuccs == 1)
1749     RBonus += 2;
1750
1751   if (LPriority+LBonus != RPriority+RBonus)
1752     return LPriority+LBonus < RPriority+RBonus;
1753
1754   if (left->Depth != right->Depth)
1755     return left->Depth < right->Depth;
1756
1757   if (left->NumSuccsLeft != right->NumSuccsLeft)
1758     return left->NumSuccsLeft > right->NumSuccsLeft;
1759
1760   if (left->CycleBound != right->CycleBound)
1761     return left->CycleBound > right->CycleBound;
1762
1763   assert(left->NodeQueueId && right->NodeQueueId && 
1764          "NodeQueueId cannot be zero");
1765   return (left->NodeQueueId > right->NodeQueueId);
1766 }
1767
1768 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number. 
1769 /// Smaller number is the higher priority.
1770 unsigned TDRegReductionPriorityQueue::
1771 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1772   unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1773   if (SethiUllmanNumber != 0)
1774     return SethiUllmanNumber;
1775
1776   unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1777   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1778     SethiUllmanNumber = 0xffff;
1779   else if (SU->NumSuccsLeft == 0)
1780     // If SU does not have a use, i.e. it doesn't produce a value that would
1781     // be consumed (e.g. store), then it terminates a chain of computation.
1782     // Give it a small SethiUllman number so it will be scheduled right before
1783     // its predecessors that it doesn't lengthen their live ranges.
1784     SethiUllmanNumber = 0;
1785   else if (SU->NumPredsLeft == 0 &&
1786            (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1787     SethiUllmanNumber = 0xffff;
1788   else {
1789     int Extra = 0;
1790     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1791          I != E; ++I) {
1792       if (I->isCtrl) continue;  // ignore chain preds
1793       SUnit *PredSU = I->Dep;
1794       unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1795       if (PredSethiUllman > SethiUllmanNumber) {
1796         SethiUllmanNumber = PredSethiUllman;
1797         Extra = 0;
1798       } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1799         ++Extra;
1800     }
1801
1802     SethiUllmanNumber += Extra;
1803   }
1804   
1805   return SethiUllmanNumber;
1806 }
1807
1808 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1809 /// scheduling units.
1810 void TDRegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1811   SethiUllmanNumbers.assign(SUnits->size(), 0);
1812   
1813   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1814     CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1815 }
1816
1817 //===----------------------------------------------------------------------===//
1818 //                         Public Constructor Functions
1819 //===----------------------------------------------------------------------===//
1820
1821 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1822                                                     SelectionDAG *DAG,
1823                                                     MachineBasicBlock *BB) {
1824   const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
1825   const TargetRegisterInfo *TRI = DAG->getTarget().getRegisterInfo();
1826   
1827   BURegReductionPriorityQueue *priorityQueue = 
1828     new BURegReductionPriorityQueue(TII, TRI);
1829
1830   ScheduleDAGRRList * scheduleDAG = 
1831     new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true, priorityQueue);
1832   priorityQueue->setScheduleDAG(scheduleDAG);
1833   return scheduleDAG;  
1834 }
1835
1836 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1837                                                     SelectionDAG *DAG,
1838                                                     MachineBasicBlock *BB) {
1839   return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
1840                               new TDRegReductionPriorityQueue());
1841 }
1842