3fd082439c3add29d47a2021d50fc3458c41c7ba
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGList.cpp
1 //===---- ScheduleDAGList.cpp - Implement a list scheduler for isel DAG ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Evan Cheng and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements bottom-up and top-down list schedulers, using standard
11 // algorithms.  The basic approach uses a priority queue of available nodes to
12 // schedule.  One at a time, nodes are taken from the priority queue (thus in
13 // priority order), checked for legality to schedule, and emitted if legal.
14 //
15 // Nodes may not be legal to schedule either due to structural hazards (e.g.
16 // pipeline or resource constraints) or because an input to the instruction has
17 // not completed execution.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "sched"
22 #include "llvm/CodeGen/ScheduleDAG.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include <climits>
28 #include <iostream>
29 #include <queue>
30 #include <set>
31 #include <vector>
32 #include "llvm/Support/CommandLine.h"
33 using namespace llvm;
34
35 namespace {
36   Statistic<> NumNoops ("scheduler", "Number of noops inserted");
37   Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
38
39   /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
40   /// a group of nodes flagged together.
41   struct SUnit {
42     SDNode *Node;                       // Representative node.
43     std::vector<SDNode*> FlaggedNodes;  // All nodes flagged to Node.
44     
45     // Preds/Succs - The SUnits before/after us in the graph.  The boolean value
46     // is true if the edge is a token chain edge, false if it is a value edge. 
47     std::set<std::pair<SUnit*,bool> > Preds;  // All sunit predecessors.
48     std::set<std::pair<SUnit*,bool> > Succs;  // All sunit successors.
49
50     short NumPredsLeft;                 // # of preds not scheduled.
51     short NumSuccsLeft;                 // # of succs not scheduled.
52     short NumChainPredsLeft;            // # of chain preds not scheduled.
53     short NumChainSuccsLeft;            // # of chain succs not scheduled.
54     bool isTwoAddress     : 1;          // Is a two-address instruction.
55     bool isDefNUseOperand : 1;          // Is a def&use operand.
56     bool isAvailable      : 1;          // True once available.
57     bool isScheduled      : 1;          // True once scheduled.
58     unsigned short Latency;             // Node latency.
59     unsigned CycleBound;                // Upper/lower cycle to be scheduled at.
60     unsigned NodeNum;                   // Entry # of node in the node vector.
61     
62     SUnit(SDNode *node, unsigned nodenum)
63       : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
64       NumChainPredsLeft(0), NumChainSuccsLeft(0),
65       isTwoAddress(false), isDefNUseOperand(false),
66       isAvailable(false), isScheduled(false), 
67       Latency(0), CycleBound(0), NodeNum(nodenum) {}
68     
69     void dump(const SelectionDAG *G) const;
70     void dumpAll(const SelectionDAG *G) const;
71   };
72 }
73
74 void SUnit::dump(const SelectionDAG *G) const {
75   std::cerr << "SU: ";
76   Node->dump(G);
77   std::cerr << "\n";
78   if (FlaggedNodes.size() != 0) {
79     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
80       std::cerr << "    ";
81       FlaggedNodes[i]->dump(G);
82       std::cerr << "\n";
83     }
84   }
85 }
86
87 void SUnit::dumpAll(const SelectionDAG *G) const {
88   dump(G);
89
90   std::cerr << "  # preds left       : " << NumPredsLeft << "\n";
91   std::cerr << "  # succs left       : " << NumSuccsLeft << "\n";
92   std::cerr << "  # chain preds left : " << NumChainPredsLeft << "\n";
93   std::cerr << "  # chain succs left : " << NumChainSuccsLeft << "\n";
94   std::cerr << "  Latency            : " << Latency << "\n";
95
96   if (Preds.size() != 0) {
97     std::cerr << "  Predecessors:\n";
98     for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
99            E = Preds.end(); I != E; ++I) {
100       if (I->second)
101         std::cerr << "   ch  ";
102       else
103         std::cerr << "   val ";
104       I->first->dump(G);
105     }
106   }
107   if (Succs.size() != 0) {
108     std::cerr << "  Successors:\n";
109     for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
110            E = Succs.end(); I != E; ++I) {
111       if (I->second)
112         std::cerr << "   ch  ";
113       else
114         std::cerr << "   val ";
115       I->first->dump(G);
116     }
117   }
118   std::cerr << "\n";
119 }
120
121 //===----------------------------------------------------------------------===//
122 /// SchedulingPriorityQueue - This interface is used to plug different
123 /// priorities computation algorithms into the list scheduler. It implements the
124 /// interface of a standard priority queue, where nodes are inserted in 
125 /// arbitrary order and returned in priority order.  The computation of the
126 /// priority and the representation of the queue are totally up to the
127 /// implementation to decide.
128 /// 
129 namespace {
130 class SchedulingPriorityQueue {
131 public:
132   virtual ~SchedulingPriorityQueue() {}
133   
134   virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
135   virtual void releaseState() = 0;
136   
137   virtual bool empty() const = 0;
138   virtual void push(SUnit *U) = 0;
139   
140   virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
141   virtual SUnit *pop() = 0;
142   
143   /// ScheduledNode - As each node is scheduled, this method is invoked.  This
144   /// allows the priority function to adjust the priority of node that have
145   /// already been emitted.
146   virtual void ScheduledNode(SUnit *Node) {}
147 };
148 }
149
150
151
152 namespace {
153 //===----------------------------------------------------------------------===//
154 /// ScheduleDAGList - The actual list scheduler implementation.  This supports
155 /// both top-down and bottom-up scheduling.
156 ///
157 class ScheduleDAGList : public ScheduleDAG {
158 private:
159   // SDNode to SUnit mapping (many to one).
160   std::map<SDNode*, SUnit*> SUnitMap;
161   // The schedule.  Null SUnit*'s represent noop instructions.
162   std::vector<SUnit*> Sequence;
163   // Current scheduling cycle.
164   unsigned CurrCycle;
165   
166   // The scheduling units.
167   std::vector<SUnit> SUnits;
168
169   /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
170   /// it is top-down.
171   bool isBottomUp;
172   
173   /// PriorityQueue - The priority queue to use.
174   SchedulingPriorityQueue *PriorityQueue;
175   
176   /// HazardRec - The hazard recognizer to use.
177   HazardRecognizer *HazardRec;
178   
179 public:
180   ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
181                   const TargetMachine &tm, bool isbottomup,
182                   SchedulingPriorityQueue *priorityqueue,
183                   HazardRecognizer *HR)
184     : ScheduleDAG(dag, bb, tm),
185       CurrCycle(0), isBottomUp(isbottomup), 
186       PriorityQueue(priorityqueue), HazardRec(HR) {
187     }
188
189   ~ScheduleDAGList() {
190     delete HazardRec;
191     delete PriorityQueue;
192   }
193
194   void Schedule();
195
196   void dumpSchedule() const;
197
198 private:
199   SUnit *NewSUnit(SDNode *N);
200   void ReleasePred(SUnit *PredSU, bool isChain);
201   void ReleaseSucc(SUnit *SuccSU, bool isChain);
202   void ScheduleNodeBottomUp(SUnit *SU);
203   void ScheduleNodeTopDown(SUnit *SU);
204   void ListScheduleTopDown();
205   void ListScheduleBottomUp();
206   void BuildSchedUnits();
207   void EmitSchedule();
208 };
209 }  // end anonymous namespace
210
211 HazardRecognizer::~HazardRecognizer() {}
212
213
214 /// NewSUnit - Creates a new SUnit and return a ptr to it.
215 SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
216   SUnits.push_back(SUnit(N, SUnits.size()));
217   return &SUnits.back();
218 }
219
220 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
221 /// the Available queue is the count reaches zero. Also update its cycle bound.
222 void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain) {
223   // FIXME: the distance between two nodes is not always == the predecessor's
224   // latency. For example, the reader can very well read the register written
225   // by the predecessor later than the issue cycle. It also depends on the
226   // interrupt model (drain vs. freeze).
227   PredSU->CycleBound = std::max(PredSU->CycleBound,CurrCycle + PredSU->Latency);
228
229   if (!isChain)
230     PredSU->NumSuccsLeft--;
231   else
232     PredSU->NumChainSuccsLeft--;
233   
234 #ifndef NDEBUG
235   if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
236     std::cerr << "*** List scheduling failed! ***\n";
237     PredSU->dump(&DAG);
238     std::cerr << " has been released too many times!\n";
239     assert(0);
240   }
241 #endif
242   
243   if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
244     // EntryToken has to go last!  Special case it here.
245     if (PredSU->Node->getOpcode() != ISD::EntryToken) {
246       PredSU->isAvailable = true;
247       PriorityQueue->push(PredSU);
248     }
249   }
250 }
251
252 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
253 /// the Available queue is the count reaches zero. Also update its cycle bound.
254 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
255   // FIXME: the distance between two nodes is not always == the predecessor's
256   // latency. For example, the reader can very well read the register written
257   // by the predecessor later than the issue cycle. It also depends on the
258   // interrupt model (drain vs. freeze).
259   SuccSU->CycleBound = std::max(SuccSU->CycleBound,CurrCycle + SuccSU->Latency);
260   
261   if (!isChain)
262     SuccSU->NumPredsLeft--;
263   else
264     SuccSU->NumChainPredsLeft--;
265   
266 #ifndef NDEBUG
267   if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
268     std::cerr << "*** List scheduling failed! ***\n";
269     SuccSU->dump(&DAG);
270     std::cerr << " has been released too many times!\n";
271     abort();
272   }
273 #endif
274   
275   if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
276     SuccSU->isAvailable = true;
277     PriorityQueue->push(SuccSU);
278   }
279 }
280
281 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
282 /// count of its predecessors. If a predecessor pending count is zero, add it to
283 /// the Available queue.
284 void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU) {
285   DEBUG(std::cerr << "*** Scheduling: ");
286   DEBUG(SU->dump(&DAG));
287
288   Sequence.push_back(SU);
289
290   // Bottom up: release predecessors
291   for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
292          E = SU->Preds.end(); I != E; ++I) {
293     ReleasePred(I->first, I->second);
294     if (!I->second)
295       SU->NumPredsLeft--;
296   }
297   CurrCycle++;
298 }
299
300 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
301 /// count of its successors. If a successor pending count is zero, add it to
302 /// the Available queue.
303 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU) {
304   DEBUG(std::cerr << "*** Scheduling: ");
305   DEBUG(SU->dump(&DAG));
306   
307   Sequence.push_back(SU);
308   
309   // Bottom up: release successors.
310   for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
311        E = SU->Succs.end(); I != E; ++I) {
312     ReleaseSucc(I->first, I->second);
313     if (!I->second)
314       SU->NumSuccsLeft--;
315   }
316   CurrCycle++;
317 }
318
319 /// isReady - True if node's lower cycle bound is less or equal to the current
320 /// scheduling cycle. Always true if all nodes have uniform latency 1.
321 static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
322   return SU->CycleBound <= CurrCycle;
323 }
324
325 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
326 /// schedulers.
327 void ScheduleDAGList::ListScheduleBottomUp() {
328   // Add root to Available queue.
329   PriorityQueue->push(SUnitMap[DAG.getRoot().Val]);
330
331   // While Available queue is not empty, grab the node with the highest
332   // priority. If it is not ready put it back. Schedule the node.
333   std::vector<SUnit*> NotReady;
334   while (!PriorityQueue->empty()) {
335     SUnit *CurrNode = PriorityQueue->pop();
336
337     while (!isReady(CurrNode, CurrCycle)) {
338       NotReady.push_back(CurrNode);
339       CurrNode = PriorityQueue->pop();
340     }
341     
342     // Add the nodes that aren't ready back onto the available list.
343     PriorityQueue->push_all(NotReady);
344     NotReady.clear();
345
346     ScheduleNodeBottomUp(CurrNode);
347     CurrNode->isScheduled = true;
348     PriorityQueue->ScheduledNode(CurrNode);
349   }
350
351   // Add entry node last
352   if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
353     SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
354     Sequence.push_back(Entry);
355   }
356
357   // Reverse the order if it is bottom up.
358   std::reverse(Sequence.begin(), Sequence.end());
359   
360   
361 #ifndef NDEBUG
362   // Verify that all SUnits were scheduled.
363   bool AnyNotSched = false;
364   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
365     if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
366       if (!AnyNotSched)
367         std::cerr << "*** List scheduling failed! ***\n";
368       SUnits[i].dump(&DAG);
369       std::cerr << "has not been scheduled!\n";
370       AnyNotSched = true;
371     }
372   }
373   assert(!AnyNotSched);
374 #endif
375 }
376
377 /// ListScheduleTopDown - The main loop of list scheduling for top-down
378 /// schedulers.
379 void ScheduleDAGList::ListScheduleTopDown() {
380   // Emit the entry node first.
381   SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
382   ScheduleNodeTopDown(Entry);
383   HazardRec->EmitInstruction(Entry->Node);
384                       
385   // All leaves to Available queue.
386   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
387     // It is available if it has no predecessors.
388     if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry)
389       PriorityQueue->push(&SUnits[i]);
390   }
391   
392   // While Available queue is not empty, grab the node with the highest
393   // priority. If it is not ready put it back.  Schedule the node.
394   std::vector<SUnit*> NotReady;
395   while (!PriorityQueue->empty()) {
396     SUnit *FoundNode = 0;
397
398     bool HasNoopHazards = false;
399     do {
400       SUnit *CurNode = PriorityQueue->pop();
401       
402       // Get the node represented by this SUnit.
403       SDNode *N = CurNode->Node;
404       // If this is a pseudo op, like copyfromreg, look to see if there is a
405       // real target node flagged to it.  If so, use the target node.
406       for (unsigned i = 0, e = CurNode->FlaggedNodes.size(); 
407            N->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
408         N = CurNode->FlaggedNodes[i];
409       
410       HazardRecognizer::HazardType HT = HazardRec->getHazardType(N);
411       if (HT == HazardRecognizer::NoHazard) {
412         FoundNode = CurNode;
413         break;
414       }
415       
416       // Remember if this is a noop hazard.
417       HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
418       
419       NotReady.push_back(CurNode);
420     } while (!PriorityQueue->empty());
421     
422     // Add the nodes that aren't ready back onto the available list.
423     PriorityQueue->push_all(NotReady);
424     NotReady.clear();
425
426     // If we found a node to schedule, do it now.
427     if (FoundNode) {
428       ScheduleNodeTopDown(FoundNode);
429       HazardRec->EmitInstruction(FoundNode->Node);
430       FoundNode->isScheduled = true;
431       PriorityQueue->ScheduledNode(FoundNode);
432     } else if (!HasNoopHazards) {
433       // Otherwise, we have a pipeline stall, but no other problem, just advance
434       // the current cycle and try again.
435       DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
436       HazardRec->AdvanceCycle();
437       ++NumStalls;
438     } else {
439       // Otherwise, we have no instructions to issue and we have instructions
440       // that will fault if we don't do this right.  This is the case for
441       // processors without pipeline interlocks and other cases.
442       DEBUG(std::cerr << "*** Emitting noop\n");
443       HazardRec->EmitNoop();
444       Sequence.push_back(0);   // NULL SUnit* -> noop
445       ++NumNoops;
446     }
447   }
448
449 #ifndef NDEBUG
450   // Verify that all SUnits were scheduled.
451   bool AnyNotSched = false;
452   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
453     if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
454       if (!AnyNotSched)
455         std::cerr << "*** List scheduling failed! ***\n";
456       SUnits[i].dump(&DAG);
457       std::cerr << "has not been scheduled!\n";
458       AnyNotSched = true;
459     }
460   }
461   assert(!AnyNotSched);
462 #endif
463 }
464
465
466 void ScheduleDAGList::BuildSchedUnits() {
467   // Reserve entries in the vector for each of the SUnits we are creating.  This
468   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
469   // invalidated.
470   SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
471   
472   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
473
474   for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
475        E = DAG.allnodes_end(); NI != E; ++NI) {
476     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
477       continue;
478     
479     // If this node has already been processed, stop now.
480     if (SUnitMap[NI]) continue;
481     
482     SUnit *NodeSUnit = NewSUnit(NI);
483
484     // See if anything is flagged to this node, if so, add them to flagged
485     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
486     // are required the be the last operand and result of a node.
487     
488     // Scan up, adding flagged preds to FlaggedNodes.
489     SDNode *N = NI;
490     while (N->getNumOperands() &&
491            N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
492       N = N->getOperand(N->getNumOperands()-1).Val;
493       NodeSUnit->FlaggedNodes.push_back(N);
494       SUnitMap[N] = NodeSUnit;
495     }
496     
497     // Scan down, adding this node and any flagged succs to FlaggedNodes if they
498     // have a user of the flag operand.
499     N = NI;
500     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
501       SDOperand FlagVal(N, N->getNumValues()-1);
502       
503       // There are either zero or one users of the Flag result.
504       bool HasFlagUse = false;
505       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
506            UI != E; ++UI)
507         if (FlagVal.isOperand(*UI)) {
508           HasFlagUse = true;
509           NodeSUnit->FlaggedNodes.push_back(N);
510           SUnitMap[N] = NodeSUnit;
511           N = *UI;
512           break;
513         }
514       if (!HasFlagUse) break;
515     }
516   
517     // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
518     // Update the SUnit
519     NodeSUnit->Node = N;
520     SUnitMap[N] = NodeSUnit;
521     
522     // Compute the latency for the node.  We use the sum of the latencies for
523     // all nodes flagged together into this SUnit.
524     if (InstrItins.isEmpty()) {
525       // No latency information.
526       NodeSUnit->Latency = 1;
527     } else {
528       NodeSUnit->Latency = 0;
529       if (N->isTargetOpcode()) {
530         unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
531         InstrStage *S = InstrItins.begin(SchedClass);
532         InstrStage *E = InstrItins.end(SchedClass);
533         for (; S != E; ++S)
534           NodeSUnit->Latency += S->Cycles;
535       }
536       for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
537         SDNode *FNode = NodeSUnit->FlaggedNodes[i];
538         if (FNode->isTargetOpcode()) {
539           unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
540           InstrStage *S = InstrItins.begin(SchedClass);
541           InstrStage *E = InstrItins.end(SchedClass);
542           for (; S != E; ++S)
543             NodeSUnit->Latency += S->Cycles;
544         }
545       }
546     }
547   }
548
549   // Pass 2: add the preds, succs, etc.
550   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
551     SUnit *SU = &SUnits[su];
552     SDNode *MainNode = SU->Node;
553     
554     if (MainNode->isTargetOpcode() &&
555         TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
556       SU->isTwoAddress = true;
557
558     // Find all predecessors and successors of the group.
559     // Temporarily add N to make code simpler.
560     SU->FlaggedNodes.push_back(MainNode);
561     
562     for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
563       SDNode *N = SU->FlaggedNodes[n];
564       
565       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
566         SDNode *OpN = N->getOperand(i).Val;
567         if (isPassiveNode(OpN)) continue;   // Not scheduled.
568         SUnit *OpSU = SUnitMap[OpN];
569         assert(OpSU && "Node has no SUnit!");
570         if (OpSU == SU) continue;           // In the same group.
571         
572         MVT::ValueType OpVT = N->getOperand(i).getValueType();
573         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
574         bool isChain = OpVT == MVT::Other;
575           
576         if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
577           if (!isChain) {
578             SU->NumPredsLeft++;
579           } else {
580             SU->NumChainPredsLeft++;
581           }
582         }
583         if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
584           if (!isChain) {
585             OpSU->NumSuccsLeft++;
586           } else {
587             OpSU->NumChainSuccsLeft++;
588           }
589         }
590       }
591     }
592     
593     // Remove MainNode from FlaggedNodes again.
594     SU->FlaggedNodes.pop_back();
595   }
596   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
597           SUnits[su].dumpAll(&DAG));
598 }
599
600 /// EmitSchedule - Emit the machine code in scheduled order.
601 void ScheduleDAGList::EmitSchedule() {
602   std::map<SDNode*, unsigned> VRBaseMap;
603   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
604     if (SUnit *SU = Sequence[i]) {
605       for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
606         EmitNode(SU->FlaggedNodes[j], VRBaseMap);
607       EmitNode(SU->Node, VRBaseMap);
608     } else {
609       // Null SUnit* is a noop.
610       EmitNoop();
611     }
612   }
613 }
614
615 /// dump - dump the schedule.
616 void ScheduleDAGList::dumpSchedule() const {
617   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
618     if (SUnit *SU = Sequence[i])
619       SU->dump(&DAG);
620     else
621       std::cerr << "**** NOOP ****\n";
622   }
623 }
624
625 /// Schedule - Schedule the DAG using list scheduling.
626 /// FIXME: Right now it only supports the burr (bottom up register reducing)
627 /// heuristic.
628 void ScheduleDAGList::Schedule() {
629   DEBUG(std::cerr << "********** List Scheduling **********\n");
630
631   // Build scheduling units.
632   BuildSchedUnits();
633   
634   PriorityQueue->initNodes(SUnits);
635   
636   // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
637   if (isBottomUp)
638     ListScheduleBottomUp();
639   else
640     ListScheduleTopDown();
641
642   PriorityQueue->releaseState();
643
644   DEBUG(std::cerr << "*** Final schedule ***\n");
645   DEBUG(dumpSchedule());
646   DEBUG(std::cerr << "\n");
647   
648   // Emit in scheduled order
649   EmitSchedule();
650 }
651
652 //===----------------------------------------------------------------------===//
653 //                RegReductionPriorityQueue Implementation
654 //===----------------------------------------------------------------------===//
655 //
656 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
657 // to reduce register pressure.
658 // 
659 namespace {
660   class RegReductionPriorityQueue;
661   
662   /// Sorting functions for the Available queue.
663   struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
664     RegReductionPriorityQueue *SPQ;
665     ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
666     ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
667     
668     bool operator()(const SUnit* left, const SUnit* right) const;
669   };
670 }  // end anonymous namespace
671
672 namespace {
673   class RegReductionPriorityQueue : public SchedulingPriorityQueue {
674     // SUnits - The SUnits for the current graph.
675     const std::vector<SUnit> *SUnits;
676     
677     // SethiUllmanNumbers - The SethiUllman number for each node.
678     std::vector<int> SethiUllmanNumbers;
679     
680     std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
681   public:
682     RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
683     }
684     
685     void initNodes(const std::vector<SUnit> &sunits) {
686       SUnits = &sunits;
687       // Calculate node priorities.
688       CalculatePriorities();
689     }
690     void releaseState() {
691       SUnits = 0;
692       SethiUllmanNumbers.clear();
693     }
694     
695     unsigned getSethiUllmanNumber(unsigned NodeNum) const {
696       assert(NodeNum < SethiUllmanNumbers.size());
697       return SethiUllmanNumbers[NodeNum];
698     }
699     
700     bool empty() const { return Queue.empty(); }
701     
702     void push(SUnit *U) {
703       Queue.push(U);
704     }
705     void push_all(const std::vector<SUnit *> &Nodes) {
706       for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
707         Queue.push(Nodes[i]);
708     }
709     
710     SUnit *pop() {
711       SUnit *V = Queue.top();
712       Queue.pop();
713       return V;
714     }
715   private:
716     void CalculatePriorities();
717     int CalcNodePriority(const SUnit *SU);
718   };
719 }
720
721 bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
722   unsigned LeftNum  = left->NodeNum;
723   unsigned RightNum = right->NodeNum;
724   
725   int LBonus = (int)left ->isDefNUseOperand;
726   int RBonus = (int)right->isDefNUseOperand;
727   
728   // Special tie breaker: if two nodes share a operand, the one that
729   // use it as a def&use operand is preferred.
730   if (left->isTwoAddress && !right->isTwoAddress) {
731     SDNode *DUNode = left->Node->getOperand(0).Val;
732     if (DUNode->isOperand(right->Node))
733       LBonus++;
734   }
735   if (!left->isTwoAddress && right->isTwoAddress) {
736     SDNode *DUNode = right->Node->getOperand(0).Val;
737     if (DUNode->isOperand(left->Node))
738       RBonus++;
739   }
740   
741   // Priority1 is just the number of live range genned.
742   int LPriority1 = left ->NumPredsLeft - LBonus;
743   int RPriority1 = right->NumPredsLeft - RBonus;
744   int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
745   int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
746   
747   if (LPriority1 > RPriority1)
748     return true;
749   else if (LPriority1 == RPriority1)
750     if (LPriority2 < RPriority2)
751       return true;
752     else if (LPriority2 == RPriority2)
753       if (left->CycleBound > right->CycleBound) 
754         return true;
755   
756   return false;
757 }
758
759
760 /// CalcNodePriority - Priority is the Sethi Ullman number. 
761 /// Smaller number is the higher priority.
762 int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
763   int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
764   if (SethiUllmanNumber != INT_MIN)
765     return SethiUllmanNumber;
766   
767   if (SU->Preds.size() == 0) {
768     SethiUllmanNumber = 1;
769   } else {
770     int Extra = 0;
771     for (std::set<std::pair<SUnit*, bool> >::const_iterator
772          I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
773       if (I->second) continue;  // ignore chain preds.
774       SUnit *PredSU = I->first;
775       int PredSethiUllman = CalcNodePriority(PredSU);
776       if (PredSethiUllman > SethiUllmanNumber) {
777         SethiUllmanNumber = PredSethiUllman;
778         Extra = 0;
779       } else if (PredSethiUllman == SethiUllmanNumber)
780         Extra++;
781     }
782     
783     if (SU->Node->getOpcode() != ISD::TokenFactor)
784       SethiUllmanNumber += Extra;
785     else
786       SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
787   }
788   
789   return SethiUllmanNumber;
790 }
791
792 /// CalculatePriorities - Calculate priorities of all scheduling units.
793 void RegReductionPriorityQueue::CalculatePriorities() {
794   SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
795   
796   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
797     CalcNodePriority(&(*SUnits)[i]);
798 }
799
800 //===----------------------------------------------------------------------===//
801 //                    LatencyPriorityQueue Implementation
802 //===----------------------------------------------------------------------===//
803 //
804 // This is a SchedulingPriorityQueue that schedules using latency information to
805 // reduce the length of the critical path through the basic block.
806 // 
807 namespace {
808   class LatencyPriorityQueue;
809   
810   /// Sorting functions for the Available queue.
811   struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
812     LatencyPriorityQueue *PQ;
813     latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
814     latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
815     
816     bool operator()(const SUnit* left, const SUnit* right) const;
817   };
818 }  // end anonymous namespace
819
820 namespace {
821   class LatencyPriorityQueue : public SchedulingPriorityQueue {
822     // SUnits - The SUnits for the current graph.
823     const std::vector<SUnit> *SUnits;
824     
825     // Latencies - The latency (max of latency from this node to the bb exit)
826     // for each node.
827     std::vector<int> Latencies;
828
829     /// NumNodesSolelyBlocking - This vector contains, for every node in the
830     /// Queue, the number of nodes that the node is the sole unscheduled
831     /// predecessor for.  This is used as a tie-breaker heuristic for better
832     /// mobility.
833     std::vector<unsigned> NumNodesSolelyBlocking;
834
835     std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
836 public:
837     LatencyPriorityQueue() : Queue(latency_sort(this)) {
838     }
839     
840     void initNodes(const std::vector<SUnit> &sunits) {
841       SUnits = &sunits;
842       // Calculate node priorities.
843       CalculatePriorities();
844     }
845     void releaseState() {
846       SUnits = 0;
847       Latencies.clear();
848     }
849     
850     unsigned getLatency(unsigned NodeNum) const {
851       assert(NodeNum < Latencies.size());
852       return Latencies[NodeNum];
853     }
854     
855     unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
856       assert(NodeNum < NumNodesSolelyBlocking.size());
857       return NumNodesSolelyBlocking[NodeNum];
858     }
859     
860     bool empty() const { return Queue.empty(); }
861     
862     virtual void push(SUnit *U) {
863       push_impl(U);
864     }
865     void push_impl(SUnit *U);
866     
867     void push_all(const std::vector<SUnit *> &Nodes) {
868       for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
869         push_impl(Nodes[i]);
870     }
871     
872     SUnit *pop() {
873       SUnit *V = Queue.top();
874       Queue.pop();
875       return V;
876     }
877     
878     // ScheduledNode - As nodes are scheduled, we look to see if there are any
879     // successor nodes that have a single unscheduled predecessor.  If so, that
880     // single predecessor has a higher priority, since scheduling it will make
881     // the node available.
882     void ScheduledNode(SUnit *Node);
883     
884 private:
885     void CalculatePriorities();
886     int CalcLatency(const SUnit &SU);
887     void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
888     
889     /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
890     /// node from a priority queue.  We should roll our own heap to make this
891     /// better or something.
892     void RemoveFromPriorityQueue(SUnit *SU) {
893       std::vector<SUnit*> Temp;
894       
895       assert(!Queue.empty() && "Not in queue!");
896       while (Queue.top() != SU) {
897         Temp.push_back(Queue.top());
898         Queue.pop();
899         assert(!Queue.empty() && "Not in queue!");
900       }
901
902       // Remove the node from the PQ.
903       Queue.pop();
904       
905       // Add all the other nodes back.
906       for (unsigned i = 0, e = Temp.size(); i != e; ++i)
907         Queue.push(Temp[i]);
908     }
909   };
910 }
911
912 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
913   unsigned LHSNum = LHS->NodeNum;
914   unsigned RHSNum = RHS->NodeNum;
915
916   // The most important heuristic is scheduling the critical path.
917   unsigned LHSLatency = PQ->getLatency(LHSNum);
918   unsigned RHSLatency = PQ->getLatency(RHSNum);
919   if (LHSLatency < RHSLatency) return true;
920   if (LHSLatency > RHSLatency) return false;
921   
922   // After that, if two nodes have identical latencies, look to see if one will
923   // unblock more other nodes than the other.
924   unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
925   unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
926   if (LHSBlocked < RHSBlocked) return true;
927   if (LHSBlocked > RHSBlocked) return false;
928   
929   // Finally, just to provide a stable ordering, use the node number as a
930   // deciding factor.
931   return LHSNum < RHSNum;
932 }
933
934
935 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
936 ///
937 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
938   int &Latency = Latencies[SU.NodeNum];
939   if (Latency != -1)
940     return Latency;
941   
942   int MaxSuccLatency = 0;
943   for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
944        E = SU.Succs.end(); I != E; ++I)
945     MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
946
947   return Latency = MaxSuccLatency + SU.Latency;
948 }
949
950 /// CalculatePriorities - Calculate priorities of all scheduling units.
951 void LatencyPriorityQueue::CalculatePriorities() {
952   Latencies.assign(SUnits->size(), -1);
953   NumNodesSolelyBlocking.assign(SUnits->size(), 0);
954   
955   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
956     CalcLatency((*SUnits)[i]);
957 }
958
959 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
960 /// of SU, return it, otherwise return null.
961 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
962   SUnit *OnlyAvailablePred = 0;
963   for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
964        E = SU->Preds.end(); I != E; ++I)
965     if (!I->first->isScheduled) {
966       // We found an available, but not scheduled, predecessor.  If it's the
967       // only one we have found, keep track of it... otherwise give up.
968       if (OnlyAvailablePred && OnlyAvailablePred != I->first)
969         return 0;
970       OnlyAvailablePred = I->first;
971     }
972       
973   return OnlyAvailablePred;
974 }
975
976 void LatencyPriorityQueue::push_impl(SUnit *SU) {
977   // Look at all of the successors of this node.  Count the number of nodes that
978   // this node is the sole unscheduled node for.
979   unsigned NumNodesBlocking = 0;
980   for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
981        E = SU->Succs.end(); I != E; ++I)
982     if (getSingleUnscheduledPred(I->first) == SU)
983       ++NumNodesBlocking;
984   NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
985   
986   Queue.push(SU);
987 }
988
989
990 // ScheduledNode - As nodes are scheduled, we look to see if there are any
991 // successor nodes that have a single unscheduled predecessor.  If so, that
992 // single predecessor has a higher priority, since scheduling it will make
993 // the node available.
994 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
995   for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
996        E = SU->Succs.end(); I != E; ++I)
997     AdjustPriorityOfUnscheduledPreds(I->first);
998 }
999
1000 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1001 /// scheduled.  If SU is not itself available, then there is at least one
1002 /// predecessor node that has not been scheduled yet.  If SU has exactly ONE
1003 /// unscheduled predecessor, we want to increase its priority: it getting
1004 /// scheduled will make this node available, so it is better than some other
1005 /// node of the same priority that will not make a node available.
1006 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1007   if (SU->isAvailable) return;  // All preds scheduled.
1008   
1009   SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1010   if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1011   
1012   // Okay, we found a single predecessor that is available, but not scheduled.
1013   // Since it is available, it must be in the priority queue.  First remove it.
1014   RemoveFromPriorityQueue(OnlyAvailablePred);
1015
1016   // Reinsert the node into the priority queue, which recomputes its
1017   // NumNodesSolelyBlocking value.
1018   push(OnlyAvailablePred);
1019 }
1020
1021
1022 //===----------------------------------------------------------------------===//
1023 //                         Public Constructor Functions
1024 //===----------------------------------------------------------------------===//
1025
1026 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1027                                                     MachineBasicBlock *BB) {
1028   return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true, 
1029                              new RegReductionPriorityQueue(),
1030                              new HazardRecognizer());
1031 }
1032
1033 /// createTDListDAGScheduler - This creates a top-down list scheduler with the
1034 /// specified hazard recognizer.
1035 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1036                                             MachineBasicBlock *BB,
1037                                             HazardRecognizer *HR) {
1038   return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
1039                              new LatencyPriorityQueue(),
1040                              HR);
1041 }