The list-td and list-tdrr schedulers don't yet support physreg
[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/LatencyPriorityQueue.h"
23 #include "llvm/CodeGen/ScheduleDAGSDNodes.h"
24 #include "llvm/CodeGen/SchedulerRegistry.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/ADT/PriorityQueue.h"
33 #include "llvm/ADT/Statistic.h"
34 #include <climits>
35 using namespace llvm;
36
37 STATISTIC(NumNoops , "Number of noops inserted");
38 STATISTIC(NumStalls, "Number of pipeline stalls");
39
40 static RegisterScheduler
41   tdListDAGScheduler("list-td", "Top-down list scheduler",
42                      createTDListDAGScheduler);
43    
44 namespace {
45 //===----------------------------------------------------------------------===//
46 /// ScheduleDAGList - The actual list scheduler implementation.  This supports
47 /// top-down scheduling.
48 ///
49 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAGSDNodes {
50 private:
51   /// AvailableQueue - The priority queue to use for the available SUnits.
52   ///
53   SchedulingPriorityQueue *AvailableQueue;
54   
55   /// PendingQueue - This contains all of the instructions whose operands have
56   /// been issued, but their results are not ready yet (due to the latency of
57   /// the operation).  Once the operands become available, the instruction is
58   /// added to the AvailableQueue.
59   std::vector<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     : ScheduleDAGSDNodes(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 *SU, const SDep &D);
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 the scheduling graph.
95   BuildSchedGraph();
96
97   AvailableQueue->initNodes(SUnits);
98   
99   ListScheduleTopDown();
100   
101   AvailableQueue->releaseState();
102 }
103
104 //===----------------------------------------------------------------------===//
105 //  Top-Down Scheduling
106 //===----------------------------------------------------------------------===//
107
108 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
109 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
110 void ScheduleDAGList::ReleaseSucc(SUnit *SU, const SDep &D) {
111   SUnit *SuccSU = D.getSUnit();
112   --SuccSU->NumPredsLeft;
113   
114 #ifndef NDEBUG
115   if (SuccSU->NumPredsLeft < 0) {
116     cerr << "*** Scheduling failed! ***\n";
117     SuccSU->dump(this);
118     cerr << " has been released too many times!\n";
119     assert(0);
120   }
121 #endif
122   
123   SuccSU->setDepthToAtLeast(SU->getDepth() + D.getLatency());
124   
125   if (SuccSU->NumPredsLeft == 0) {
126     PendingQueue.push_back(SuccSU);
127   }
128 }
129
130 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
131 /// count of its successors. If a successor pending count is zero, add it to
132 /// the Available queue.
133 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
134   DOUT << "*** Scheduling [" << CurCycle << "]: ";
135   DEBUG(SU->dump(this));
136   
137   Sequence.push_back(SU);
138   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
139   SU->setDepthToAtLeast(CurCycle);
140
141   // Top down: release successors.
142   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
143        I != E; ++I) {
144     assert(!I->isAssignedRegDep() &&
145            "The list-td scheduler doesn't yet support physreg dependencies!");
146
147     ReleaseSucc(SU, *I);
148   }
149
150   SU->isScheduled = true;
151   AvailableQueue->ScheduledNode(SU);
152 }
153
154 /// ListScheduleTopDown - The main loop of list scheduling for top-down
155 /// schedulers.
156 void ScheduleDAGList::ListScheduleTopDown() {
157   unsigned CurCycle = 0;
158
159   // All leaves to Available queue.
160   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
161     // It is available if it has no predecessors.
162     if (SUnits[i].Preds.empty()) {
163       AvailableQueue->push(&SUnits[i]);
164       SUnits[i].isAvailable = true;
165     }
166   }
167   
168   // While Available queue is not empty, grab the node with the highest
169   // priority. If it is not ready put it back.  Schedule the node.
170   std::vector<SUnit*> NotReady;
171   Sequence.reserve(SUnits.size());
172   while (!AvailableQueue->empty() || !PendingQueue.empty()) {
173     // Check to see if any of the pending instructions are ready to issue.  If
174     // so, add them to the available queue.
175     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
176       if (PendingQueue[i]->getDepth() == CurCycle) {
177         AvailableQueue->push(PendingQueue[i]);
178         PendingQueue[i]->isAvailable = true;
179         PendingQueue[i] = PendingQueue.back();
180         PendingQueue.pop_back();
181         --i; --e;
182       } else {
183         assert(PendingQueue[i]->getDepth() > CurCycle && "Negative latency?");
184       }
185     }
186     
187     // If there are no instructions available, don't try to issue anything, and
188     // don't advance the hazard recognizer.
189     if (AvailableQueue->empty()) {
190       ++CurCycle;
191       continue;
192     }
193
194     SUnit *FoundSUnit = 0;
195     SDNode *FoundNode = 0;
196     
197     bool HasNoopHazards = false;
198     while (!AvailableQueue->empty()) {
199       SUnit *CurSUnit = AvailableQueue->pop();
200       
201       // Get the node represented by this SUnit.
202       FoundNode = CurSUnit->getNode();
203       
204       // If this is a pseudo op, like copyfromreg, look to see if there is a
205       // real target node flagged to it.  If so, use the target node.
206       while (!FoundNode->isMachineOpcode()) {
207         SDNode *N = FoundNode->getFlaggedNode();
208         if (!N) break;
209         FoundNode = N;
210       }
211     
212       HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
213       if (HT == HazardRecognizer::NoHazard) {
214         FoundSUnit = CurSUnit;
215         break;
216       }
217     
218       // Remember if this is a noop hazard.
219       HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
220       
221       NotReady.push_back(CurSUnit);
222     }
223     
224     // Add the nodes that aren't ready back onto the available list.
225     if (!NotReady.empty()) {
226       AvailableQueue->push_all(NotReady);
227       NotReady.clear();
228     }
229
230     // If we found a node to schedule, do it now.
231     if (FoundSUnit) {
232       ScheduleNodeTopDown(FoundSUnit, CurCycle);
233       HazardRec->EmitInstruction(FoundNode);
234
235       // If this is a pseudo-op node, we don't want to increment the current
236       // cycle.
237       if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
238         ++CurCycle;        
239     } else if (!HasNoopHazards) {
240       // Otherwise, we have a pipeline stall, but no other problem, just advance
241       // the current cycle and try again.
242       DOUT << "*** Advancing cycle, no work to do\n";
243       HazardRec->AdvanceCycle();
244       ++NumStalls;
245       ++CurCycle;
246     } else {
247       // Otherwise, we have no instructions to issue and we have instructions
248       // that will fault if we don't do this right.  This is the case for
249       // processors without pipeline interlocks and other cases.
250       DOUT << "*** Emitting noop\n";
251       HazardRec->EmitNoop();
252       Sequence.push_back(0);   // NULL SUnit* -> noop
253       ++NumNoops;
254       ++CurCycle;
255     }
256   }
257
258 #ifndef NDEBUG
259   VerifySchedule(/*isBottomUp=*/false);
260 #endif
261 }
262
263 //===----------------------------------------------------------------------===//
264 //                         Public Constructor Functions
265 //===----------------------------------------------------------------------===//
266
267 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
268 /// new hazard recognizer. This scheduler takes ownership of the hazard
269 /// recognizer and deletes it when done.
270 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
271                                             SelectionDAG *DAG,
272                                             const TargetMachine *TM,
273                                             MachineBasicBlock *BB, bool Fast) {
274   return new ScheduleDAGList(DAG, BB, *TM,
275                              new LatencyPriorityQueue(),
276                              IS->CreateTargetHazardRecognizer());
277 }