Use the new PriorityQueue in ScheduleDAGList too, which also
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements a top-down list scheduler, using standard algorithms.
11 // The basic approach uses a priority queue of available nodes to schedule.
12 // One at a time, nodes are taken from the priority queue (thus in priority
13 // 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 "pre-RA-sched"
22 #include "llvm/CodeGen/ScheduleDAG.h"
23 #include "llvm/CodeGen/SchedulerRegistry.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/ADT/PriorityQueue.h"
32 #include "llvm/ADT/Statistic.h"
33 #include <climits>
34 using namespace llvm;
35
36 STATISTIC(NumNoops , "Number of noops inserted");
37 STATISTIC(NumStalls, "Number of pipeline stalls");
38
39 static RegisterScheduler
40   tdListDAGScheduler("list-td", "  Top-down list scheduler",
41                      createTDListDAGScheduler);
42    
43 namespace {
44 //===----------------------------------------------------------------------===//
45 /// ScheduleDAGList - The actual list scheduler implementation.  This supports
46 /// top-down scheduling.
47 ///
48 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAG {
49 private:
50   /// AvailableQueue - The priority queue to use for the available SUnits.
51   ///
52   SchedulingPriorityQueue *AvailableQueue;
53   
54   /// PendingQueue - This contains all of the instructions whose operands have
55   /// been issued, but their results are not ready yet (due to the latency of
56   /// the operation).  Once the operands becomes available, the instruction is
57   /// added to the AvailableQueue.  This keeps track of each SUnit and the
58   /// number of cycles left to execute before the operation is available.
59   std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
60
61   /// HazardRec - The hazard recognizer to use.
62   HazardRecognizer *HazardRec;
63
64 public:
65   ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
66                   const TargetMachine &tm,
67                   SchedulingPriorityQueue *availqueue,
68                   HazardRecognizer *HR)
69     : ScheduleDAG(dag, bb, tm),
70       AvailableQueue(availqueue), HazardRec(HR) {
71     }
72
73   ~ScheduleDAGList() {
74     delete HazardRec;
75     delete AvailableQueue;
76   }
77
78   void Schedule();
79
80 private:
81   void ReleaseSucc(SUnit *SuccSU, bool isChain);
82   void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
83   void ListScheduleTopDown();
84 };
85 }  // end anonymous namespace
86
87 HazardRecognizer::~HazardRecognizer() {}
88
89
90 /// Schedule - Schedule the DAG using list scheduling.
91 void ScheduleDAGList::Schedule() {
92   DOUT << "********** List Scheduling **********\n";
93   
94   // Build scheduling units.
95   BuildSchedUnits();
96
97   AvailableQueue->initNodes(SUnits);
98   
99   ListScheduleTopDown();
100   
101   AvailableQueue->releaseState();
102   
103   DOUT << "*** Final schedule ***\n";
104   DEBUG(dumpSchedule());
105   DOUT << "\n";
106   
107   // Emit in scheduled order
108   EmitSchedule();
109 }
110
111 //===----------------------------------------------------------------------===//
112 //  Top-Down Scheduling
113 //===----------------------------------------------------------------------===//
114
115 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
116 /// the PendingQueue if the count reaches zero.
117 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
118   SuccSU->NumPredsLeft--;
119   
120   assert(SuccSU->NumPredsLeft >= 0 &&
121          "List scheduling internal error");
122   
123   if (SuccSU->NumPredsLeft == 0) {
124     // Compute how many cycles it will be before this actually becomes
125     // available.  This is the max of the start time of all predecessors plus
126     // their latencies.
127     unsigned AvailableCycle = 0;
128     for (SUnit::pred_iterator I = SuccSU->Preds.begin(),
129          E = SuccSU->Preds.end(); I != E; ++I) {
130       // If this is a token edge, we don't need to wait for the latency of the
131       // preceeding instruction (e.g. a long-latency load) unless there is also
132       // some other data dependence.
133       SUnit &Pred = *I->Dep;
134       unsigned PredDoneCycle = Pred.Cycle;
135       if (!I->isCtrl)
136         PredDoneCycle += Pred.Latency;
137       else if (Pred.Latency)
138         PredDoneCycle += 1;
139
140       AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
141     }
142     
143     PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
144   }
145 }
146
147 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
148 /// count of its successors. If a successor pending count is zero, add it to
149 /// the Available queue.
150 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
151   DOUT << "*** Scheduling [" << CurCycle << "]: ";
152   DEBUG(SU->dump(&DAG));
153   
154   Sequence.push_back(SU);
155   SU->Cycle = CurCycle;
156   
157   // Bottom up: release successors.
158   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
159        I != E; ++I)
160     ReleaseSucc(I->Dep, I->isCtrl);
161 }
162
163 /// ListScheduleTopDown - The main loop of list scheduling for top-down
164 /// schedulers.
165 void ScheduleDAGList::ListScheduleTopDown() {
166   unsigned CurCycle = 0;
167
168   // All leaves to Available queue.
169   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
170     // It is available if it has no predecessors.
171     if (SUnits[i].Preds.empty()) {
172       AvailableQueue->push(&SUnits[i]);
173       SUnits[i].isAvailable = SUnits[i].isPending = true;
174     }
175   }
176   
177   // While Available queue is not empty, grab the node with the highest
178   // priority. If it is not ready put it back.  Schedule the node.
179   std::vector<SUnit*> NotReady;
180   Sequence.reserve(SUnits.size());
181   while (!AvailableQueue->empty() || !PendingQueue.empty()) {
182     // Check to see if any of the pending instructions are ready to issue.  If
183     // so, add them to the available queue.
184     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
185       if (PendingQueue[i].first == CurCycle) {
186         AvailableQueue->push(PendingQueue[i].second);
187         PendingQueue[i].second->isAvailable = true;
188         PendingQueue[i] = PendingQueue.back();
189         PendingQueue.pop_back();
190         --i; --e;
191       } else {
192         assert(PendingQueue[i].first > CurCycle && "Negative latency?");
193       }
194     }
195     
196     // If there are no instructions available, don't try to issue anything, and
197     // don't advance the hazard recognizer.
198     if (AvailableQueue->empty()) {
199       ++CurCycle;
200       continue;
201     }
202
203     SUnit *FoundSUnit = 0;
204     SDNode *FoundNode = 0;
205     
206     bool HasNoopHazards = false;
207     while (!AvailableQueue->empty()) {
208       SUnit *CurSUnit = AvailableQueue->pop();
209       
210       // Get the node represented by this SUnit.
211       FoundNode = CurSUnit->Node;
212       
213       // If this is a pseudo op, like copyfromreg, look to see if there is a
214       // real target node flagged to it.  If so, use the target node.
215       for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size(); 
216            FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
217         FoundNode = CurSUnit->FlaggedNodes[i];
218       
219       HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
220       if (HT == HazardRecognizer::NoHazard) {
221         FoundSUnit = CurSUnit;
222         break;
223       }
224       
225       // Remember if this is a noop hazard.
226       HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
227       
228       NotReady.push_back(CurSUnit);
229     }
230     
231     // Add the nodes that aren't ready back onto the available list.
232     if (!NotReady.empty()) {
233       AvailableQueue->push_all(NotReady);
234       NotReady.clear();
235     }
236
237     // If we found a node to schedule, do it now.
238     if (FoundSUnit) {
239       ScheduleNodeTopDown(FoundSUnit, CurCycle);
240       HazardRec->EmitInstruction(FoundNode);
241       FoundSUnit->isScheduled = true;
242       AvailableQueue->ScheduledNode(FoundSUnit);
243
244       // If this is a pseudo-op node, we don't want to increment the current
245       // cycle.
246       if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
247         ++CurCycle;        
248     } else if (!HasNoopHazards) {
249       // Otherwise, we have a pipeline stall, but no other problem, just advance
250       // the current cycle and try again.
251       DOUT << "*** Advancing cycle, no work to do\n";
252       HazardRec->AdvanceCycle();
253       ++NumStalls;
254       ++CurCycle;
255     } else {
256       // Otherwise, we have no instructions to issue and we have instructions
257       // that will fault if we don't do this right.  This is the case for
258       // processors without pipeline interlocks and other cases.
259       DOUT << "*** Emitting noop\n";
260       HazardRec->EmitNoop();
261       Sequence.push_back(0);   // NULL SUnit* -> noop
262       ++NumNoops;
263       ++CurCycle;
264     }
265   }
266
267 #ifndef NDEBUG
268   // Verify that all SUnits were scheduled.
269   bool AnyNotSched = false;
270   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
271     if (SUnits[i].NumPredsLeft != 0) {
272       if (!AnyNotSched)
273         cerr << "*** List scheduling failed! ***\n";
274       SUnits[i].dump(&DAG);
275       cerr << "has not been scheduled!\n";
276       AnyNotSched = true;
277     }
278   }
279   assert(!AnyNotSched);
280 #endif
281 }
282
283 //===----------------------------------------------------------------------===//
284 //                    LatencyPriorityQueue Implementation
285 //===----------------------------------------------------------------------===//
286 //
287 // This is a SchedulingPriorityQueue that schedules using latency information to
288 // reduce the length of the critical path through the basic block.
289 // 
290 namespace {
291   class LatencyPriorityQueue;
292   
293   /// Sorting functions for the Available queue.
294   struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
295     LatencyPriorityQueue *PQ;
296     latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
297     latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
298     
299     bool operator()(const SUnit* left, const SUnit* right) const;
300   };
301 }  // end anonymous namespace
302
303 namespace {
304   class LatencyPriorityQueue : public SchedulingPriorityQueue {
305     // SUnits - The SUnits for the current graph.
306     std::vector<SUnit> *SUnits;
307     
308     // Latencies - The latency (max of latency from this node to the bb exit)
309     // for each node.
310     std::vector<int> Latencies;
311
312     /// NumNodesSolelyBlocking - This vector contains, for every node in the
313     /// Queue, the number of nodes that the node is the sole unscheduled
314     /// predecessor for.  This is used as a tie-breaker heuristic for better
315     /// mobility.
316     std::vector<unsigned> NumNodesSolelyBlocking;
317
318     PriorityQueue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
319 public:
320     LatencyPriorityQueue() : Queue(latency_sort(this)) {
321     }
322     
323     void initNodes(std::vector<SUnit> &sunits) {
324       SUnits = &sunits;
325       // Calculate node priorities.
326       CalculatePriorities();
327     }
328
329     void addNode(const SUnit *SU) {
330       Latencies.resize(SUnits->size(), -1);
331       NumNodesSolelyBlocking.resize(SUnits->size(), 0);
332       CalcLatency(*SU);
333     }
334
335     void updateNode(const SUnit *SU) {
336       Latencies[SU->NodeNum] = -1;
337       CalcLatency(*SU);
338     }
339
340     void releaseState() {
341       SUnits = 0;
342       Latencies.clear();
343     }
344     
345     unsigned getLatency(unsigned NodeNum) const {
346       assert(NodeNum < Latencies.size());
347       return Latencies[NodeNum];
348     }
349     
350     unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
351       assert(NodeNum < NumNodesSolelyBlocking.size());
352       return NumNodesSolelyBlocking[NodeNum];
353     }
354     
355     unsigned size() const { return Queue.size(); }
356
357     bool empty() const { return Queue.empty(); }
358     
359     virtual void push(SUnit *U) {
360       push_impl(U);
361     }
362     void push_impl(SUnit *U);
363     
364     void push_all(const std::vector<SUnit *> &Nodes) {
365       for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
366         push_impl(Nodes[i]);
367     }
368     
369     SUnit *pop() {
370       if (empty()) return NULL;
371       SUnit *V = Queue.top();
372       Queue.pop();
373       return V;
374     }
375
376     void remove(SUnit *SU) {
377       assert(!Queue.empty() && "Not in queue!");
378       Queue.erase_one(SU);
379     }
380
381     // ScheduledNode - As nodes are scheduled, we look to see if there are any
382     // successor nodes that have a single unscheduled predecessor.  If so, that
383     // single predecessor has a higher priority, since scheduling it will make
384     // the node available.
385     void ScheduledNode(SUnit *Node);
386
387 private:
388     void CalculatePriorities();
389     int CalcLatency(const SUnit &SU);
390     void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
391     SUnit *getSingleUnscheduledPred(SUnit *SU);
392   };
393 }
394
395 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
396   unsigned LHSNum = LHS->NodeNum;
397   unsigned RHSNum = RHS->NodeNum;
398
399   // The most important heuristic is scheduling the critical path.
400   unsigned LHSLatency = PQ->getLatency(LHSNum);
401   unsigned RHSLatency = PQ->getLatency(RHSNum);
402   if (LHSLatency < RHSLatency) return true;
403   if (LHSLatency > RHSLatency) return false;
404   
405   // After that, if two nodes have identical latencies, look to see if one will
406   // unblock more other nodes than the other.
407   unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
408   unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
409   if (LHSBlocked < RHSBlocked) return true;
410   if (LHSBlocked > RHSBlocked) return false;
411   
412   // Finally, just to provide a stable ordering, use the node number as a
413   // deciding factor.
414   return LHSNum < RHSNum;
415 }
416
417
418 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
419 ///
420 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
421   int &Latency = Latencies[SU.NodeNum];
422   if (Latency != -1)
423     return Latency;
424
425   std::vector<const SUnit*> WorkList;
426   WorkList.push_back(&SU);
427   while (!WorkList.empty()) {
428     const SUnit *Cur = WorkList.back();
429     bool AllDone = true;
430     int MaxSuccLatency = 0;
431     for (SUnit::const_succ_iterator I = Cur->Succs.begin(),E = Cur->Succs.end();
432          I != E; ++I) {
433       int SuccLatency = Latencies[I->Dep->NodeNum];
434       if (SuccLatency == -1) {
435         AllDone = false;
436         WorkList.push_back(I->Dep);
437       } else {
438         MaxSuccLatency = std::max(MaxSuccLatency, SuccLatency);
439       }
440     }
441     if (AllDone) {
442       Latencies[Cur->NodeNum] = MaxSuccLatency + Cur->Latency;
443       WorkList.pop_back();
444     }
445   }
446
447   return Latency;
448 }
449
450 /// CalculatePriorities - Calculate priorities of all scheduling units.
451 void LatencyPriorityQueue::CalculatePriorities() {
452   Latencies.assign(SUnits->size(), -1);
453   NumNodesSolelyBlocking.assign(SUnits->size(), 0);
454
455   // For each node, calculate the maximal path from the node to the exit.
456   std::vector<std::pair<const SUnit*, unsigned> > WorkList;
457   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
458     const SUnit *SU = &(*SUnits)[i];
459     if (SU->Succs.empty())
460       WorkList.push_back(std::make_pair(SU, 0U));
461   }
462
463   while (!WorkList.empty()) {
464     const SUnit *SU = WorkList.back().first;
465     unsigned SuccLat = WorkList.back().second;
466     WorkList.pop_back();
467     int &Latency = Latencies[SU->NodeNum];
468     if (Latency == -1 || (SU->Latency + SuccLat) > (unsigned)Latency) {
469       Latency = SU->Latency + SuccLat;
470       for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
471            I != E; ++I)
472         WorkList.push_back(std::make_pair(I->Dep, Latency));
473     }
474   }
475 }
476
477 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
478 /// of SU, return it, otherwise return null.
479 SUnit *LatencyPriorityQueue::getSingleUnscheduledPred(SUnit *SU) {
480   SUnit *OnlyAvailablePred = 0;
481   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
482        I != E; ++I) {
483     SUnit &Pred = *I->Dep;
484     if (!Pred.isScheduled) {
485       // We found an available, but not scheduled, predecessor.  If it's the
486       // only one we have found, keep track of it... otherwise give up.
487       if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
488         return 0;
489       OnlyAvailablePred = &Pred;
490     }
491   }
492       
493   return OnlyAvailablePred;
494 }
495
496 void LatencyPriorityQueue::push_impl(SUnit *SU) {
497   // Look at all of the successors of this node.  Count the number of nodes that
498   // this node is the sole unscheduled node for.
499   unsigned NumNodesBlocking = 0;
500   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
501        I != E; ++I)
502     if (getSingleUnscheduledPred(I->Dep) == SU)
503       ++NumNodesBlocking;
504   NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
505   
506   Queue.push(SU);
507 }
508
509
510 // ScheduledNode - As nodes are scheduled, we look to see if there are any
511 // successor nodes that have a single unscheduled predecessor.  If so, that
512 // single predecessor has a higher priority, since scheduling it will make
513 // the node available.
514 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
515   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
516        I != E; ++I)
517     AdjustPriorityOfUnscheduledPreds(I->Dep);
518 }
519
520 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
521 /// scheduled.  If SU is not itself available, then there is at least one
522 /// predecessor node that has not been scheduled yet.  If SU has exactly ONE
523 /// unscheduled predecessor, we want to increase its priority: it getting
524 /// scheduled will make this node available, so it is better than some other
525 /// node of the same priority that will not make a node available.
526 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
527   if (SU->isPending) return;  // All preds scheduled.
528   
529   SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
530   if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
531   
532   // Okay, we found a single predecessor that is available, but not scheduled.
533   // Since it is available, it must be in the priority queue.  First remove it.
534   remove(OnlyAvailablePred);
535
536   // Reinsert the node into the priority queue, which recomputes its
537   // NumNodesSolelyBlocking value.
538   push(OnlyAvailablePred);
539 }
540
541
542 //===----------------------------------------------------------------------===//
543 //                         Public Constructor Functions
544 //===----------------------------------------------------------------------===//
545
546 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
547 /// new hazard recognizer. This scheduler takes ownership of the hazard
548 /// recognizer and deletes it when done.
549 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
550                                             SelectionDAG *DAG,
551                                             MachineBasicBlock *BB) {
552   return new ScheduleDAGList(*DAG, BB, DAG->getTarget(),
553                              new LatencyPriorityQueue(),
554                              IS->CreateTargetHazardRecognizer());
555 }