1 //===---- ScheduleDAGList.cpp - Implement a list scheduler for isel DAG ---===//
3 // The LLVM Compiler Infrastructure
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.
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/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.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/Statistic.h"
37 STATISTIC(NumNoops , "Number of noops inserted");
38 STATISTIC(NumStalls, "Number of pipeline stalls");
40 static RegisterScheduler
41 tdListDAGScheduler("list-td", " Top-down list scheduler",
42 createTDListDAGScheduler);
45 //===----------------------------------------------------------------------===//
46 /// ScheduleDAGList - The actual list scheduler implementation. This supports
47 /// top-down scheduling.
49 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAG {
51 /// AvailableQueue - The priority queue to use for the available SUnits.
53 SchedulingPriorityQueue *AvailableQueue;
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 becomes available, the instruction is
58 /// added to the AvailableQueue. This keeps track of each SUnit and the
59 /// number of cycles left to execute before the operation is available.
60 std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
62 /// HazardRec - The hazard recognizer to use.
63 HazardRecognizer *HazardRec;
66 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
67 const TargetMachine &tm,
68 SchedulingPriorityQueue *availqueue,
70 : ScheduleDAG(dag, bb, tm),
71 AvailableQueue(availqueue), HazardRec(HR) {
76 delete AvailableQueue;
82 void ReleaseSucc(SUnit *SuccSU, bool isChain);
83 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
84 void ListScheduleTopDown();
86 } // end anonymous namespace
88 HazardRecognizer::~HazardRecognizer() {}
91 /// Schedule - Schedule the DAG using list scheduling.
92 void ScheduleDAGList::Schedule() {
93 DOUT << "********** List Scheduling **********\n";
95 // Build scheduling units.
98 AvailableQueue->initNodes(SUnitMap, SUnits);
100 ListScheduleTopDown();
102 AvailableQueue->releaseState();
104 DOUT << "*** Final schedule ***\n";
105 DEBUG(dumpSchedule());
108 // Emit in scheduled order
112 //===----------------------------------------------------------------------===//
113 // Top-Down Scheduling
114 //===----------------------------------------------------------------------===//
116 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
117 /// the PendingQueue if the count reaches zero.
118 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
119 SuccSU->NumPredsLeft--;
121 assert(SuccSU->NumPredsLeft >= 0 &&
122 "List scheduling internal error");
124 if (SuccSU->NumPredsLeft == 0) {
125 // Compute how many cycles it will be before this actually becomes
126 // available. This is the max of the start time of all predecessors plus
128 unsigned AvailableCycle = 0;
129 for (SUnit::pred_iterator I = SuccSU->Preds.begin(),
130 E = SuccSU->Preds.end(); I != E; ++I) {
131 // If this is a token edge, we don't need to wait for the latency of the
132 // preceeding instruction (e.g. a long-latency load) unless there is also
133 // some other data dependence.
134 SUnit &Pred = *I->Dep;
135 unsigned PredDoneCycle = Pred.Cycle;
137 PredDoneCycle += Pred.Latency;
138 else if (Pred.Latency)
141 AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
144 PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
148 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
149 /// count of its successors. If a successor pending count is zero, add it to
150 /// the Available queue.
151 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
152 DOUT << "*** Scheduling [" << CurCycle << "]: ";
153 DEBUG(SU->dump(&DAG));
155 Sequence.push_back(SU);
156 SU->Cycle = CurCycle;
158 // Bottom up: release successors.
159 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
161 ReleaseSucc(I->Dep, I->isCtrl);
164 /// ListScheduleTopDown - The main loop of list scheduling for top-down
166 void ScheduleDAGList::ListScheduleTopDown() {
167 unsigned CurCycle = 0;
168 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
170 // All leaves to Available queue.
171 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
172 // It is available if it has no predecessors.
173 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
174 AvailableQueue->push(&SUnits[i]);
175 SUnits[i].isAvailable = SUnits[i].isPending = true;
179 // Emit the entry node first.
180 ScheduleNodeTopDown(Entry, CurCycle);
181 HazardRec->EmitInstruction(Entry->Node);
183 // While Available queue is not empty, grab the node with the highest
184 // priority. If it is not ready put it back. Schedule the node.
185 std::vector<SUnit*> NotReady;
186 while (!AvailableQueue->empty() || !PendingQueue.empty()) {
187 // Check to see if any of the pending instructions are ready to issue. If
188 // so, add them to the available queue.
189 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
190 if (PendingQueue[i].first == CurCycle) {
191 AvailableQueue->push(PendingQueue[i].second);
192 PendingQueue[i].second->isAvailable = true;
193 PendingQueue[i] = PendingQueue.back();
194 PendingQueue.pop_back();
197 assert(PendingQueue[i].first > CurCycle && "Negative latency?");
201 // If there are no instructions available, don't try to issue anything, and
202 // don't advance the hazard recognizer.
203 if (AvailableQueue->empty()) {
208 SUnit *FoundSUnit = 0;
209 SDNode *FoundNode = 0;
211 bool HasNoopHazards = false;
212 while (!AvailableQueue->empty()) {
213 SUnit *CurSUnit = AvailableQueue->pop();
215 // Get the node represented by this SUnit.
216 FoundNode = CurSUnit->Node;
218 // If this is a pseudo op, like copyfromreg, look to see if there is a
219 // real target node flagged to it. If so, use the target node.
220 for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size();
221 FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
222 FoundNode = CurSUnit->FlaggedNodes[i];
224 HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
225 if (HT == HazardRecognizer::NoHazard) {
226 FoundSUnit = CurSUnit;
230 // Remember if this is a noop hazard.
231 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
233 NotReady.push_back(CurSUnit);
236 // Add the nodes that aren't ready back onto the available list.
237 if (!NotReady.empty()) {
238 AvailableQueue->push_all(NotReady);
242 // If we found a node to schedule, do it now.
244 ScheduleNodeTopDown(FoundSUnit, CurCycle);
245 HazardRec->EmitInstruction(FoundNode);
246 FoundSUnit->isScheduled = true;
247 AvailableQueue->ScheduledNode(FoundSUnit);
249 // If this is a pseudo-op node, we don't want to increment the current
251 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
253 } else if (!HasNoopHazards) {
254 // Otherwise, we have a pipeline stall, but no other problem, just advance
255 // the current cycle and try again.
256 DOUT << "*** Advancing cycle, no work to do\n";
257 HazardRec->AdvanceCycle();
261 // Otherwise, we have no instructions to issue and we have instructions
262 // that will fault if we don't do this right. This is the case for
263 // processors without pipeline interlocks and other cases.
264 DOUT << "*** Emitting noop\n";
265 HazardRec->EmitNoop();
266 Sequence.push_back(0); // NULL SUnit* -> noop
273 // Verify that all SUnits were scheduled.
274 bool AnyNotSched = false;
275 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
276 if (SUnits[i].NumPredsLeft != 0) {
278 cerr << "*** List scheduling failed! ***\n";
279 SUnits[i].dump(&DAG);
280 cerr << "has not been scheduled!\n";
284 assert(!AnyNotSched);
288 //===----------------------------------------------------------------------===//
289 // LatencyPriorityQueue Implementation
290 //===----------------------------------------------------------------------===//
292 // This is a SchedulingPriorityQueue that schedules using latency information to
293 // reduce the length of the critical path through the basic block.
296 class LatencyPriorityQueue;
298 /// Sorting functions for the Available queue.
299 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
300 LatencyPriorityQueue *PQ;
301 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
302 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
304 bool operator()(const SUnit* left, const SUnit* right) const;
306 } // end anonymous namespace
309 class LatencyPriorityQueue : public SchedulingPriorityQueue {
310 // SUnits - The SUnits for the current graph.
311 std::vector<SUnit> *SUnits;
313 // Latencies - The latency (max of latency from this node to the bb exit)
315 std::vector<int> Latencies;
317 /// NumNodesSolelyBlocking - This vector contains, for every node in the
318 /// Queue, the number of nodes that the node is the sole unscheduled
319 /// predecessor for. This is used as a tie-breaker heuristic for better
321 std::vector<unsigned> NumNodesSolelyBlocking;
323 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
325 LatencyPriorityQueue() : Queue(latency_sort(this)) {
328 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
329 std::vector<SUnit> &sunits) {
331 // Calculate node priorities.
332 CalculatePriorities();
335 void addNode(const SUnit *SU) {
336 Latencies.resize(SUnits->size(), -1);
337 NumNodesSolelyBlocking.resize(SUnits->size(), 0);
341 void updateNode(const SUnit *SU) {
342 Latencies[SU->NodeNum] = -1;
346 void releaseState() {
351 unsigned getLatency(unsigned NodeNum) const {
352 assert(NodeNum < Latencies.size());
353 return Latencies[NodeNum];
356 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
357 assert(NodeNum < NumNodesSolelyBlocking.size());
358 return NumNodesSolelyBlocking[NodeNum];
361 unsigned size() const { return Queue.size(); }
363 bool empty() const { return Queue.empty(); }
365 virtual void push(SUnit *U) {
368 void push_impl(SUnit *U);
370 void push_all(const std::vector<SUnit *> &Nodes) {
371 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
376 if (empty()) return NULL;
377 SUnit *V = Queue.top();
382 /// remove - This is a really inefficient way to remove a node from a
383 /// priority queue. We should roll our own heap to make this better or
385 void remove(SUnit *SU) {
386 std::vector<SUnit*> Temp;
388 assert(!Queue.empty() && "Not in queue!");
389 while (Queue.top() != SU) {
390 Temp.push_back(Queue.top());
392 assert(!Queue.empty() && "Not in queue!");
395 // Remove the node from the PQ.
398 // Add all the other nodes back.
399 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
403 // ScheduledNode - As nodes are scheduled, we look to see if there are any
404 // successor nodes that have a single unscheduled predecessor. If so, that
405 // single predecessor has a higher priority, since scheduling it will make
406 // the node available.
407 void ScheduledNode(SUnit *Node);
410 void CalculatePriorities();
411 int CalcLatency(const SUnit &SU);
412 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
413 SUnit *getSingleUnscheduledPred(SUnit *SU);
417 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
418 unsigned LHSNum = LHS->NodeNum;
419 unsigned RHSNum = RHS->NodeNum;
421 // The most important heuristic is scheduling the critical path.
422 unsigned LHSLatency = PQ->getLatency(LHSNum);
423 unsigned RHSLatency = PQ->getLatency(RHSNum);
424 if (LHSLatency < RHSLatency) return true;
425 if (LHSLatency > RHSLatency) return false;
427 // After that, if two nodes have identical latencies, look to see if one will
428 // unblock more other nodes than the other.
429 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
430 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
431 if (LHSBlocked < RHSBlocked) return true;
432 if (LHSBlocked > RHSBlocked) return false;
434 // Finally, just to provide a stable ordering, use the node number as a
436 return LHSNum < RHSNum;
440 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
442 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
443 int &Latency = Latencies[SU.NodeNum];
447 std::vector<const SUnit*> WorkList;
448 WorkList.push_back(&SU);
449 while (!WorkList.empty()) {
450 const SUnit *Cur = WorkList.back();
452 int MaxSuccLatency = 0;
453 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),E = Cur->Succs.end();
455 int SuccLatency = Latencies[I->Dep->NodeNum];
456 if (SuccLatency == -1) {
458 WorkList.push_back(I->Dep);
460 MaxSuccLatency = std::max(MaxSuccLatency, SuccLatency);
464 Latencies[Cur->NodeNum] = MaxSuccLatency + Cur->Latency;
472 /// CalculatePriorities - Calculate priorities of all scheduling units.
473 void LatencyPriorityQueue::CalculatePriorities() {
474 Latencies.assign(SUnits->size(), -1);
475 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
477 // For each node, calculate the maximal path from the node to the exit.
478 std::vector<std::pair<const SUnit*, unsigned> > WorkList;
479 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
480 const SUnit *SU = &(*SUnits)[i];
481 if (SU->Succs.size() == 0)
482 WorkList.push_back(std::make_pair(SU, 0U));
485 while (!WorkList.empty()) {
486 const SUnit *SU = WorkList.back().first;
487 unsigned SuccLat = WorkList.back().second;
489 int &Latency = Latencies[SU->NodeNum];
490 if (Latency == -1 || (SU->Latency + SuccLat) > (unsigned)Latency) {
491 Latency = SU->Latency + SuccLat;
492 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
494 WorkList.push_back(std::make_pair(I->Dep, Latency));
499 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
500 /// of SU, return it, otherwise return null.
501 SUnit *LatencyPriorityQueue::getSingleUnscheduledPred(SUnit *SU) {
502 SUnit *OnlyAvailablePred = 0;
503 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
505 SUnit &Pred = *I->Dep;
506 if (!Pred.isScheduled) {
507 // We found an available, but not scheduled, predecessor. If it's the
508 // only one we have found, keep track of it... otherwise give up.
509 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
511 OnlyAvailablePred = &Pred;
515 return OnlyAvailablePred;
518 void LatencyPriorityQueue::push_impl(SUnit *SU) {
519 // Look at all of the successors of this node. Count the number of nodes that
520 // this node is the sole unscheduled node for.
521 unsigned NumNodesBlocking = 0;
522 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
524 if (getSingleUnscheduledPred(I->Dep) == SU)
526 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
532 // ScheduledNode - As nodes are scheduled, we look to see if there are any
533 // successor nodes that have a single unscheduled predecessor. If so, that
534 // single predecessor has a higher priority, since scheduling it will make
535 // the node available.
536 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
537 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
539 AdjustPriorityOfUnscheduledPreds(I->Dep);
542 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
543 /// scheduled. If SU is not itself available, then there is at least one
544 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
545 /// unscheduled predecessor, we want to increase its priority: it getting
546 /// scheduled will make this node available, so it is better than some other
547 /// node of the same priority that will not make a node available.
548 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
549 if (SU->isPending) return; // All preds scheduled.
551 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
552 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
554 // Okay, we found a single predecessor that is available, but not scheduled.
555 // Since it is available, it must be in the priority queue. First remove it.
556 remove(OnlyAvailablePred);
558 // Reinsert the node into the priority queue, which recomputes its
559 // NumNodesSolelyBlocking value.
560 push(OnlyAvailablePred);
564 //===----------------------------------------------------------------------===//
565 // Public Constructor Functions
566 //===----------------------------------------------------------------------===//
568 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
569 /// new hazard recognizer. This scheduler takes ownership of the hazard
570 /// recognizer and deletes it when done.
571 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
573 MachineBasicBlock *BB) {
574 return new ScheduleDAGList(*DAG, BB, DAG->getTarget(),
575 new LatencyPriorityQueue(),
576 IS->CreateTargetHazardRecognizer());