1 //===---- ScheduleDAGList.cpp - Implement a list scheduler for isel DAG ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
19 //===----------------------------------------------------------------------===//
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/Statistic.h"
36 STATISTIC(NumNoops , "Number of noops inserted");
37 STATISTIC(NumStalls, "Number of pipeline stalls");
39 static RegisterScheduler
40 tdListDAGScheduler("list-td", " Top-down list scheduler",
41 createTDListDAGScheduler);
44 //===----------------------------------------------------------------------===//
45 /// ScheduleDAGList - The actual list scheduler implementation. This supports
46 /// top-down scheduling.
48 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAG {
50 /// AvailableQueue - The priority queue to use for the available SUnits.
52 SchedulingPriorityQueue *AvailableQueue;
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;
61 /// HazardRec - The hazard recognizer to use.
62 HazardRecognizer *HazardRec;
65 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
66 const TargetMachine &tm,
67 SchedulingPriorityQueue *availqueue,
69 : ScheduleDAG(dag, bb, tm),
70 AvailableQueue(availqueue), HazardRec(HR) {
75 delete AvailableQueue;
81 void ReleaseSucc(SUnit *SuccSU, bool isChain);
82 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
83 void ListScheduleTopDown();
85 } // end anonymous namespace
87 HazardRecognizer::~HazardRecognizer() {}
90 /// Schedule - Schedule the DAG using list scheduling.
91 void ScheduleDAGList::Schedule() {
92 DOUT << "********** List Scheduling **********\n";
94 // Build scheduling units.
97 AvailableQueue->initNodes(SUnitMap, SUnits);
99 ListScheduleTopDown();
101 AvailableQueue->releaseState();
103 DOUT << "*** Final schedule ***\n";
104 DEBUG(dumpSchedule());
107 // Emit in scheduled order
111 //===----------------------------------------------------------------------===//
112 // Top-Down Scheduling
113 //===----------------------------------------------------------------------===//
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--;
120 assert(SuccSU->NumPredsLeft >= 0 &&
121 "List scheduling internal error");
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
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;
136 PredDoneCycle += Pred.Latency;
137 else if (Pred.Latency)
140 AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
143 PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
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));
154 Sequence.push_back(SU);
155 SU->Cycle = CurCycle;
157 // Bottom up: release successors.
158 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
160 ReleaseSucc(I->Dep, I->isCtrl);
163 /// ListScheduleTopDown - The main loop of list scheduling for top-down
165 void ScheduleDAGList::ListScheduleTopDown() {
166 unsigned CurCycle = 0;
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;
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 while (!AvailableQueue->empty() || !PendingQueue.empty()) {
181 // Check to see if any of the pending instructions are ready to issue. If
182 // so, add them to the available queue.
183 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
184 if (PendingQueue[i].first == CurCycle) {
185 AvailableQueue->push(PendingQueue[i].second);
186 PendingQueue[i].second->isAvailable = true;
187 PendingQueue[i] = PendingQueue.back();
188 PendingQueue.pop_back();
191 assert(PendingQueue[i].first > CurCycle && "Negative latency?");
195 // If there are no instructions available, don't try to issue anything, and
196 // don't advance the hazard recognizer.
197 if (AvailableQueue->empty()) {
202 SUnit *FoundSUnit = 0;
203 SDNode *FoundNode = 0;
205 bool HasNoopHazards = false;
206 while (!AvailableQueue->empty()) {
207 SUnit *CurSUnit = AvailableQueue->pop();
209 // Get the node represented by this SUnit.
210 FoundNode = CurSUnit->Node;
212 // If this is a pseudo op, like copyfromreg, look to see if there is a
213 // real target node flagged to it. If so, use the target node.
214 for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size();
215 FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
216 FoundNode = CurSUnit->FlaggedNodes[i];
218 HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
219 if (HT == HazardRecognizer::NoHazard) {
220 FoundSUnit = CurSUnit;
224 // Remember if this is a noop hazard.
225 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
227 NotReady.push_back(CurSUnit);
230 // Add the nodes that aren't ready back onto the available list.
231 if (!NotReady.empty()) {
232 AvailableQueue->push_all(NotReady);
236 // If we found a node to schedule, do it now.
238 ScheduleNodeTopDown(FoundSUnit, CurCycle);
239 HazardRec->EmitInstruction(FoundNode);
240 FoundSUnit->isScheduled = true;
241 AvailableQueue->ScheduledNode(FoundSUnit);
243 // If this is a pseudo-op node, we don't want to increment the current
245 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
247 } else if (!HasNoopHazards) {
248 // Otherwise, we have a pipeline stall, but no other problem, just advance
249 // the current cycle and try again.
250 DOUT << "*** Advancing cycle, no work to do\n";
251 HazardRec->AdvanceCycle();
255 // Otherwise, we have no instructions to issue and we have instructions
256 // that will fault if we don't do this right. This is the case for
257 // processors without pipeline interlocks and other cases.
258 DOUT << "*** Emitting noop\n";
259 HazardRec->EmitNoop();
260 Sequence.push_back(0); // NULL SUnit* -> noop
267 // Verify that all SUnits were scheduled.
268 bool AnyNotSched = false;
269 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
270 if (SUnits[i].NumPredsLeft != 0) {
272 cerr << "*** List scheduling failed! ***\n";
273 SUnits[i].dump(&DAG);
274 cerr << "has not been scheduled!\n";
278 assert(!AnyNotSched);
282 //===----------------------------------------------------------------------===//
283 // LatencyPriorityQueue Implementation
284 //===----------------------------------------------------------------------===//
286 // This is a SchedulingPriorityQueue that schedules using latency information to
287 // reduce the length of the critical path through the basic block.
290 class LatencyPriorityQueue;
292 /// Sorting functions for the Available queue.
293 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
294 LatencyPriorityQueue *PQ;
295 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
296 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
298 bool operator()(const SUnit* left, const SUnit* right) const;
300 } // end anonymous namespace
303 class LatencyPriorityQueue : public SchedulingPriorityQueue {
304 // SUnits - The SUnits for the current graph.
305 std::vector<SUnit> *SUnits;
307 // Latencies - The latency (max of latency from this node to the bb exit)
309 std::vector<int> Latencies;
311 /// NumNodesSolelyBlocking - This vector contains, for every node in the
312 /// Queue, the number of nodes that the node is the sole unscheduled
313 /// predecessor for. This is used as a tie-breaker heuristic for better
315 std::vector<unsigned> NumNodesSolelyBlocking;
317 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
319 LatencyPriorityQueue() : Queue(latency_sort(this)) {
322 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
323 std::vector<SUnit> &sunits) {
325 // Calculate node priorities.
326 CalculatePriorities();
329 void addNode(const SUnit *SU) {
330 Latencies.resize(SUnits->size(), -1);
331 NumNodesSolelyBlocking.resize(SUnits->size(), 0);
335 void updateNode(const SUnit *SU) {
336 Latencies[SU->NodeNum] = -1;
340 void releaseState() {
345 unsigned getLatency(unsigned NodeNum) const {
346 assert(NodeNum < Latencies.size());
347 return Latencies[NodeNum];
350 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
351 assert(NodeNum < NumNodesSolelyBlocking.size());
352 return NumNodesSolelyBlocking[NodeNum];
355 unsigned size() const { return Queue.size(); }
357 bool empty() const { return Queue.empty(); }
359 virtual void push(SUnit *U) {
362 void push_impl(SUnit *U);
364 void push_all(const std::vector<SUnit *> &Nodes) {
365 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
370 if (empty()) return NULL;
371 SUnit *V = Queue.top();
376 /// remove - This is a really inefficient way to remove a node from a
377 /// priority queue. We should roll our own heap to make this better or
379 void remove(SUnit *SU) {
380 std::vector<SUnit*> Temp;
382 assert(!Queue.empty() && "Not in queue!");
383 while (Queue.top() != SU) {
384 Temp.push_back(Queue.top());
386 assert(!Queue.empty() && "Not in queue!");
389 // Remove the node from the PQ.
392 // Add all the other nodes back.
393 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
397 // ScheduledNode - As nodes are scheduled, we look to see if there are any
398 // successor nodes that have a single unscheduled predecessor. If so, that
399 // single predecessor has a higher priority, since scheduling it will make
400 // the node available.
401 void ScheduledNode(SUnit *Node);
404 void CalculatePriorities();
405 int CalcLatency(const SUnit &SU);
406 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
407 SUnit *getSingleUnscheduledPred(SUnit *SU);
411 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
412 unsigned LHSNum = LHS->NodeNum;
413 unsigned RHSNum = RHS->NodeNum;
415 // The most important heuristic is scheduling the critical path.
416 unsigned LHSLatency = PQ->getLatency(LHSNum);
417 unsigned RHSLatency = PQ->getLatency(RHSNum);
418 if (LHSLatency < RHSLatency) return true;
419 if (LHSLatency > RHSLatency) return false;
421 // After that, if two nodes have identical latencies, look to see if one will
422 // unblock more other nodes than the other.
423 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
424 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
425 if (LHSBlocked < RHSBlocked) return true;
426 if (LHSBlocked > RHSBlocked) return false;
428 // Finally, just to provide a stable ordering, use the node number as a
430 return LHSNum < RHSNum;
434 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
436 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
437 int &Latency = Latencies[SU.NodeNum];
441 std::vector<const SUnit*> WorkList;
442 WorkList.push_back(&SU);
443 while (!WorkList.empty()) {
444 const SUnit *Cur = WorkList.back();
446 int MaxSuccLatency = 0;
447 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),E = Cur->Succs.end();
449 int SuccLatency = Latencies[I->Dep->NodeNum];
450 if (SuccLatency == -1) {
452 WorkList.push_back(I->Dep);
454 MaxSuccLatency = std::max(MaxSuccLatency, SuccLatency);
458 Latencies[Cur->NodeNum] = MaxSuccLatency + Cur->Latency;
466 /// CalculatePriorities - Calculate priorities of all scheduling units.
467 void LatencyPriorityQueue::CalculatePriorities() {
468 Latencies.assign(SUnits->size(), -1);
469 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
471 // For each node, calculate the maximal path from the node to the exit.
472 std::vector<std::pair<const SUnit*, unsigned> > WorkList;
473 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
474 const SUnit *SU = &(*SUnits)[i];
475 if (SU->Succs.empty())
476 WorkList.push_back(std::make_pair(SU, 0U));
479 while (!WorkList.empty()) {
480 const SUnit *SU = WorkList.back().first;
481 unsigned SuccLat = WorkList.back().second;
483 int &Latency = Latencies[SU->NodeNum];
484 if (Latency == -1 || (SU->Latency + SuccLat) > (unsigned)Latency) {
485 Latency = SU->Latency + SuccLat;
486 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
488 WorkList.push_back(std::make_pair(I->Dep, Latency));
493 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
494 /// of SU, return it, otherwise return null.
495 SUnit *LatencyPriorityQueue::getSingleUnscheduledPred(SUnit *SU) {
496 SUnit *OnlyAvailablePred = 0;
497 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
499 SUnit &Pred = *I->Dep;
500 if (!Pred.isScheduled) {
501 // We found an available, but not scheduled, predecessor. If it's the
502 // only one we have found, keep track of it... otherwise give up.
503 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
505 OnlyAvailablePred = &Pred;
509 return OnlyAvailablePred;
512 void LatencyPriorityQueue::push_impl(SUnit *SU) {
513 // Look at all of the successors of this node. Count the number of nodes that
514 // this node is the sole unscheduled node for.
515 unsigned NumNodesBlocking = 0;
516 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
518 if (getSingleUnscheduledPred(I->Dep) == SU)
520 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
526 // ScheduledNode - As nodes are scheduled, we look to see if there are any
527 // successor nodes that have a single unscheduled predecessor. If so, that
528 // single predecessor has a higher priority, since scheduling it will make
529 // the node available.
530 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
531 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
533 AdjustPriorityOfUnscheduledPreds(I->Dep);
536 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
537 /// scheduled. If SU is not itself available, then there is at least one
538 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
539 /// unscheduled predecessor, we want to increase its priority: it getting
540 /// scheduled will make this node available, so it is better than some other
541 /// node of the same priority that will not make a node available.
542 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
543 if (SU->isPending) return; // All preds scheduled.
545 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
546 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
548 // Okay, we found a single predecessor that is available, but not scheduled.
549 // Since it is available, it must be in the priority queue. First remove it.
550 remove(OnlyAvailablePred);
552 // Reinsert the node into the priority queue, which recomputes its
553 // NumNodesSolelyBlocking value.
554 push(OnlyAvailablePred);
558 //===----------------------------------------------------------------------===//
559 // Public Constructor Functions
560 //===----------------------------------------------------------------------===//
562 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
563 /// new hazard recognizer. This scheduler takes ownership of the hazard
564 /// recognizer and deletes it when done.
565 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
567 MachineBasicBlock *BB) {
568 return new ScheduleDAGList(*DAG, BB, DAG->getTarget(),
569 new LatencyPriorityQueue(),
570 IS->CreateTargetHazardRecognizer());