Move a few containers out of ScheduleDAGInstrs::BuildSchedGraph
[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/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 ScheduleDAGSDNodes {
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 become available, the instruction is
57   /// added to the AvailableQueue.
58   std::vector<SUnit*> PendingQueue;
59
60   /// HazardRec - The hazard recognizer to use.
61   HazardRecognizer *HazardRec;
62
63 public:
64   ScheduleDAGList(MachineFunction &mf,
65                   SchedulingPriorityQueue *availqueue,
66                   HazardRecognizer *HR)
67     : ScheduleDAGSDNodes(mf),
68       AvailableQueue(availqueue), HazardRec(HR) {
69     }
70
71   ~ScheduleDAGList() {
72     delete HazardRec;
73     delete AvailableQueue;
74   }
75
76   void Schedule();
77
78 private:
79   void ReleaseSucc(SUnit *SU, const SDep &D);
80   void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
81   void ListScheduleTopDown();
82 };
83 }  // end anonymous namespace
84
85 HazardRecognizer::~HazardRecognizer() {}
86
87
88 /// Schedule - Schedule the DAG using list scheduling.
89 void ScheduleDAGList::Schedule() {
90   DOUT << "********** List Scheduling **********\n";
91   
92   // Build the scheduling graph.
93   BuildSchedGraph();
94
95   AvailableQueue->initNodes(SUnits);
96   
97   ListScheduleTopDown();
98   
99   AvailableQueue->releaseState();
100 }
101
102 //===----------------------------------------------------------------------===//
103 //  Top-Down Scheduling
104 //===----------------------------------------------------------------------===//
105
106 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
107 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
108 void ScheduleDAGList::ReleaseSucc(SUnit *SU, const SDep &D) {
109   SUnit *SuccSU = D.getSUnit();
110   --SuccSU->NumPredsLeft;
111   
112 #ifndef NDEBUG
113   if (SuccSU->NumPredsLeft < 0) {
114     cerr << "*** Scheduling failed! ***\n";
115     SuccSU->dump(this);
116     cerr << " has been released too many times!\n";
117     assert(0);
118   }
119 #endif
120   
121   SuccSU->setDepthToAtLeast(SU->getDepth() + D.getLatency());
122   
123   if (SuccSU->NumPredsLeft == 0) {
124     PendingQueue.push_back(SuccSU);
125   }
126 }
127
128 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
129 /// count of its successors. If a successor pending count is zero, add it to
130 /// the Available queue.
131 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
132   DOUT << "*** Scheduling [" << CurCycle << "]: ";
133   DEBUG(SU->dump(this));
134   
135   Sequence.push_back(SU);
136   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
137   SU->setDepthToAtLeast(CurCycle);
138
139   // Top down: release successors.
140   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
141        I != E; ++I) {
142     assert(!I->isAssignedRegDep() &&
143            "The list-td scheduler doesn't yet support physreg dependencies!");
144
145     ReleaseSucc(SU, *I);
146   }
147
148   SU->isScheduled = true;
149   AvailableQueue->ScheduledNode(SU);
150 }
151
152 /// ListScheduleTopDown - The main loop of list scheduling for top-down
153 /// schedulers.
154 void ScheduleDAGList::ListScheduleTopDown() {
155   unsigned CurCycle = 0;
156
157   // All leaves to Available queue.
158   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
159     // It is available if it has no predecessors.
160     if (SUnits[i].Preds.empty()) {
161       AvailableQueue->push(&SUnits[i]);
162       SUnits[i].isAvailable = true;
163     }
164   }
165   
166   // While Available queue is not empty, grab the node with the highest
167   // priority. If it is not ready put it back.  Schedule the node.
168   std::vector<SUnit*> NotReady;
169   Sequence.reserve(SUnits.size());
170   while (!AvailableQueue->empty() || !PendingQueue.empty()) {
171     // Check to see if any of the pending instructions are ready to issue.  If
172     // so, add them to the available queue.
173     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
174       if (PendingQueue[i]->getDepth() == CurCycle) {
175         AvailableQueue->push(PendingQueue[i]);
176         PendingQueue[i]->isAvailable = true;
177         PendingQueue[i] = PendingQueue.back();
178         PendingQueue.pop_back();
179         --i; --e;
180       } else {
181         assert(PendingQueue[i]->getDepth() > CurCycle && "Negative latency?");
182       }
183     }
184     
185     // If there are no instructions available, don't try to issue anything, and
186     // don't advance the hazard recognizer.
187     if (AvailableQueue->empty()) {
188       ++CurCycle;
189       continue;
190     }
191
192     SUnit *FoundSUnit = 0;
193     SDNode *FoundNode = 0;
194     
195     bool HasNoopHazards = false;
196     while (!AvailableQueue->empty()) {
197       SUnit *CurSUnit = AvailableQueue->pop();
198       
199       // Get the node represented by this SUnit.
200       FoundNode = CurSUnit->getNode();
201       
202       // If this is a pseudo op, like copyfromreg, look to see if there is a
203       // real target node flagged to it.  If so, use the target node.
204       while (!FoundNode->isMachineOpcode()) {
205         SDNode *N = FoundNode->getFlaggedNode();
206         if (!N) break;
207         FoundNode = N;
208       }
209     
210       HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
211       if (HT == HazardRecognizer::NoHazard) {
212         FoundSUnit = CurSUnit;
213         break;
214       }
215     
216       // Remember if this is a noop hazard.
217       HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
218       
219       NotReady.push_back(CurSUnit);
220     }
221     
222     // Add the nodes that aren't ready back onto the available list.
223     if (!NotReady.empty()) {
224       AvailableQueue->push_all(NotReady);
225       NotReady.clear();
226     }
227
228     // If we found a node to schedule, do it now.
229     if (FoundSUnit) {
230       ScheduleNodeTopDown(FoundSUnit, CurCycle);
231       HazardRec->EmitInstruction(FoundNode);
232
233       // If this is a pseudo-op node, we don't want to increment the current
234       // cycle.
235       if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
236         ++CurCycle;        
237     } else if (!HasNoopHazards) {
238       // Otherwise, we have a pipeline stall, but no other problem, just advance
239       // the current cycle and try again.
240       DOUT << "*** Advancing cycle, no work to do\n";
241       HazardRec->AdvanceCycle();
242       ++NumStalls;
243       ++CurCycle;
244     } else {
245       // Otherwise, we have no instructions to issue and we have instructions
246       // that will fault if we don't do this right.  This is the case for
247       // processors without pipeline interlocks and other cases.
248       DOUT << "*** Emitting noop\n";
249       HazardRec->EmitNoop();
250       Sequence.push_back(0);   // NULL SUnit* -> noop
251       ++NumNoops;
252       ++CurCycle;
253     }
254   }
255
256 #ifndef NDEBUG
257   VerifySchedule(/*isBottomUp=*/false);
258 #endif
259 }
260
261 //===----------------------------------------------------------------------===//
262 //                         Public Constructor Functions
263 //===----------------------------------------------------------------------===//
264
265 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
266 /// new hazard recognizer. This scheduler takes ownership of the hazard
267 /// recognizer and deletes it when done.
268 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
269                                             bool Fast) {
270   return new ScheduleDAGList(*IS->MF,
271                              new LatencyPriorityQueue(),
272                              IS->CreateTargetHazardRecognizer());
273 }