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