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