blob: 3fd082439c3add29d47a2021d50fc3458c41c7ba [file] [log] [blame]
Evan Chengab495562006-01-25 09:14:32 +00001//===---- ScheduleDAGList.cpp - Implement a list scheduler for isel DAG ---===//
Evan Cheng31272342006-01-23 08:26:10 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner01aa7522006-03-06 17:58:04 +000010// This implements bottom-up and top-down list schedulers, using standard
11// algorithms. The basic approach uses a priority queue of available nodes to
12// schedule. One at a time, nodes are taken from the priority queue (thus in
13// priority 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.
Evan Cheng31272342006-01-23 08:26:10 +000018//
19//===----------------------------------------------------------------------===//
20
21#define DEBUG_TYPE "sched"
22#include "llvm/CodeGen/ScheduleDAG.h"
Evan Cheng31272342006-01-23 08:26:10 +000023#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetInstrInfo.h"
Evan Chengab495562006-01-25 09:14:32 +000025#include "llvm/Support/Debug.h"
Chris Lattnerfa5e1c92006-03-05 23:13:56 +000026#include "llvm/ADT/Statistic.h"
Evan Chengab495562006-01-25 09:14:32 +000027#include <climits>
28#include <iostream>
Evan Cheng31272342006-01-23 08:26:10 +000029#include <queue>
Evan Cheng4e3904f2006-03-02 21:38:29 +000030#include <set>
31#include <vector>
Chris Lattnerd4130372006-03-09 07:15:18 +000032#include "llvm/Support/CommandLine.h"
Evan Cheng31272342006-01-23 08:26:10 +000033using namespace llvm;
34
Evan Chengab495562006-01-25 09:14:32 +000035namespace {
Chris Lattnerfa5e1c92006-03-05 23:13:56 +000036 Statistic<> NumNoops ("scheduler", "Number of noops inserted");
37 Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
Evan Cheng31272342006-01-23 08:26:10 +000038
Chris Lattner12c6d892006-03-08 04:41:06 +000039 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
40 /// a group of nodes flagged together.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000041 struct SUnit {
42 SDNode *Node; // Representative node.
43 std::vector<SDNode*> FlaggedNodes; // All nodes flagged to Node.
Chris Lattner578d8fc2006-03-11 22:24:20 +000044
45 // Preds/Succs - The SUnits before/after us in the graph. The boolean value
46 // is true if the edge is a token chain edge, false if it is a value edge.
47 std::set<std::pair<SUnit*,bool> > Preds; // All sunit predecessors.
48 std::set<std::pair<SUnit*,bool> > Succs; // All sunit successors.
49
Chris Lattner12c6d892006-03-08 04:41:06 +000050 short NumPredsLeft; // # of preds not scheduled.
51 short NumSuccsLeft; // # of succs not scheduled.
52 short NumChainPredsLeft; // # of chain preds not scheduled.
53 short NumChainSuccsLeft; // # of chain succs not scheduled.
Chris Lattner12c6d892006-03-08 04:41:06 +000054 bool isTwoAddress : 1; // Is a two-address instruction.
55 bool isDefNUseOperand : 1; // Is a def&use operand.
Chris Lattner349e9dd2006-03-10 05:51:05 +000056 bool isAvailable : 1; // True once available.
57 bool isScheduled : 1; // True once scheduled.
Chris Lattner12c6d892006-03-08 04:41:06 +000058 unsigned short Latency; // Node latency.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000059 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
Chris Lattnerfd22d422006-03-08 05:18:27 +000060 unsigned NodeNum; // Entry # of node in the node vector.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000061
Chris Lattnerfd22d422006-03-08 05:18:27 +000062 SUnit(SDNode *node, unsigned nodenum)
Chris Lattneraf5e26c2006-03-08 04:37:58 +000063 : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
Evan Cheng4e3904f2006-03-02 21:38:29 +000064 NumChainPredsLeft(0), NumChainSuccsLeft(0),
Evan Cheng5e9a6952006-03-03 06:23:43 +000065 isTwoAddress(false), isDefNUseOperand(false),
Chris Lattner349e9dd2006-03-10 05:51:05 +000066 isAvailable(false), isScheduled(false),
Chris Lattnerfd22d422006-03-08 05:18:27 +000067 Latency(0), CycleBound(0), NodeNum(nodenum) {}
Chris Lattneraf5e26c2006-03-08 04:37:58 +000068
Chris Lattnerd4130372006-03-09 07:15:18 +000069 void dump(const SelectionDAG *G) const;
70 void dumpAll(const SelectionDAG *G) const;
Chris Lattneraf5e26c2006-03-08 04:37:58 +000071 };
72}
Evan Chengab495562006-01-25 09:14:32 +000073
Chris Lattnerd4130372006-03-09 07:15:18 +000074void SUnit::dump(const SelectionDAG *G) const {
Evan Chengc4c339c2006-01-26 00:30:29 +000075 std::cerr << "SU: ";
Evan Chengab495562006-01-25 09:14:32 +000076 Node->dump(G);
77 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +000078 if (FlaggedNodes.size() != 0) {
Evan Chengab495562006-01-25 09:14:32 +000079 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
Evan Chengc4c339c2006-01-26 00:30:29 +000080 std::cerr << " ";
Evan Chengab495562006-01-25 09:14:32 +000081 FlaggedNodes[i]->dump(G);
82 std::cerr << "\n";
83 }
84 }
Chris Lattnerd4130372006-03-09 07:15:18 +000085}
Evan Chengab495562006-01-25 09:14:32 +000086
Chris Lattnerd4130372006-03-09 07:15:18 +000087void SUnit::dumpAll(const SelectionDAG *G) const {
88 dump(G);
Evan Chengc4c339c2006-01-26 00:30:29 +000089
Chris Lattnerd4130372006-03-09 07:15:18 +000090 std::cerr << " # preds left : " << NumPredsLeft << "\n";
91 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
92 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
93 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
94 std::cerr << " Latency : " << Latency << "\n";
95
96 if (Preds.size() != 0) {
97 std::cerr << " Predecessors:\n";
Chris Lattner578d8fc2006-03-11 22:24:20 +000098 for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
Chris Lattnerd4130372006-03-09 07:15:18 +000099 E = Preds.end(); I != E; ++I) {
Chris Lattner578d8fc2006-03-11 22:24:20 +0000100 if (I->second)
101 std::cerr << " ch ";
102 else
103 std::cerr << " val ";
104 I->first->dump(G);
Chris Lattnerd4130372006-03-09 07:15:18 +0000105 }
106 }
107 if (Succs.size() != 0) {
108 std::cerr << " Successors:\n";
Chris Lattner578d8fc2006-03-11 22:24:20 +0000109 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
Chris Lattnerd4130372006-03-09 07:15:18 +0000110 E = Succs.end(); I != E; ++I) {
Chris Lattner578d8fc2006-03-11 22:24:20 +0000111 if (I->second)
112 std::cerr << " ch ";
113 else
114 std::cerr << " val ";
115 I->first->dump(G);
Chris Lattnerd4130372006-03-09 07:15:18 +0000116 }
117 }
118 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +0000119}
120
Chris Lattner9df64752006-03-09 06:35:14 +0000121//===----------------------------------------------------------------------===//
Chris Lattner9e95acc2006-03-09 06:37:29 +0000122/// SchedulingPriorityQueue - This interface is used to plug different
123/// priorities computation algorithms into the list scheduler. It implements the
124/// interface of a standard priority queue, where nodes are inserted in
125/// arbitrary order and returned in priority order. The computation of the
126/// priority and the representation of the queue are totally up to the
127/// implementation to decide.
128///
129namespace {
Chris Lattner9df64752006-03-09 06:35:14 +0000130class SchedulingPriorityQueue {
131public:
132 virtual ~SchedulingPriorityQueue() {}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000133
Chris Lattner9df64752006-03-09 06:35:14 +0000134 virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
135 virtual void releaseState() = 0;
Chris Lattnerfd22d422006-03-08 05:18:27 +0000136
Chris Lattner9df64752006-03-09 06:35:14 +0000137 virtual bool empty() const = 0;
138 virtual void push(SUnit *U) = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000139
140 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
Chris Lattner9df64752006-03-09 06:35:14 +0000141 virtual SUnit *pop() = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000142
143 /// ScheduledNode - As each node is scheduled, this method is invoked. This
144 /// allows the priority function to adjust the priority of node that have
145 /// already been emitted.
146 virtual void ScheduledNode(SUnit *Node) {}
Chris Lattner9df64752006-03-09 06:35:14 +0000147};
Chris Lattner9e95acc2006-03-09 06:37:29 +0000148}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000149
150
Chris Lattnere50c0922006-03-05 22:45:01 +0000151
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000152namespace {
Chris Lattner9e95acc2006-03-09 06:37:29 +0000153//===----------------------------------------------------------------------===//
154/// ScheduleDAGList - The actual list scheduler implementation. This supports
155/// both top-down and bottom-up scheduling.
156///
Evan Cheng31272342006-01-23 08:26:10 +0000157class ScheduleDAGList : public ScheduleDAG {
158private:
Evan Chengab495562006-01-25 09:14:32 +0000159 // SDNode to SUnit mapping (many to one).
160 std::map<SDNode*, SUnit*> SUnitMap;
Chris Lattner00b52ea2006-03-05 23:59:20 +0000161 // The schedule. Null SUnit*'s represent noop instructions.
Evan Chengab495562006-01-25 09:14:32 +0000162 std::vector<SUnit*> Sequence;
163 // Current scheduling cycle.
164 unsigned CurrCycle;
Chris Lattner42e20262006-03-08 04:54:34 +0000165
166 // The scheduling units.
167 std::vector<SUnit> SUnits;
Evan Cheng31272342006-01-23 08:26:10 +0000168
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000169 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
170 /// it is top-down.
171 bool isBottomUp;
172
Chris Lattner9df64752006-03-09 06:35:14 +0000173 /// PriorityQueue - The priority queue to use.
174 SchedulingPriorityQueue *PriorityQueue;
175
Chris Lattnere50c0922006-03-05 22:45:01 +0000176 /// HazardRec - The hazard recognizer to use.
Chris Lattner543832d2006-03-08 04:25:59 +0000177 HazardRecognizer *HazardRec;
Chris Lattnere50c0922006-03-05 22:45:01 +0000178
Evan Cheng31272342006-01-23 08:26:10 +0000179public:
180 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
Chris Lattnere50c0922006-03-05 22:45:01 +0000181 const TargetMachine &tm, bool isbottomup,
Chris Lattner9df64752006-03-09 06:35:14 +0000182 SchedulingPriorityQueue *priorityqueue,
Chris Lattner543832d2006-03-08 04:25:59 +0000183 HazardRecognizer *HR)
Chris Lattnera5b93b82006-03-10 07:42:02 +0000184 : ScheduleDAG(dag, bb, tm),
Chris Lattner9df64752006-03-09 06:35:14 +0000185 CurrCycle(0), isBottomUp(isbottomup),
186 PriorityQueue(priorityqueue), HazardRec(HR) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000187 }
Evan Chengab495562006-01-25 09:14:32 +0000188
189 ~ScheduleDAGList() {
Chris Lattner543832d2006-03-08 04:25:59 +0000190 delete HazardRec;
Chris Lattner9df64752006-03-09 06:35:14 +0000191 delete PriorityQueue;
Evan Chengab495562006-01-25 09:14:32 +0000192 }
Evan Cheng31272342006-01-23 08:26:10 +0000193
194 void Schedule();
Evan Cheng31272342006-01-23 08:26:10 +0000195
Chris Lattnerd4130372006-03-09 07:15:18 +0000196 void dumpSchedule() const;
Evan Chengab495562006-01-25 09:14:32 +0000197
198private:
Evan Chengc4c339c2006-01-26 00:30:29 +0000199 SUnit *NewSUnit(SDNode *N);
Chris Lattner578d8fc2006-03-11 22:24:20 +0000200 void ReleasePred(SUnit *PredSU, bool isChain);
201 void ReleaseSucc(SUnit *SuccSU, bool isChain);
Chris Lattner399bee22006-03-09 06:48:37 +0000202 void ScheduleNodeBottomUp(SUnit *SU);
203 void ScheduleNodeTopDown(SUnit *SU);
204 void ListScheduleTopDown();
205 void ListScheduleBottomUp();
Evan Chengab495562006-01-25 09:14:32 +0000206 void BuildSchedUnits();
207 void EmitSchedule();
208};
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000209} // end anonymous namespace
Evan Chengab495562006-01-25 09:14:32 +0000210
Chris Lattner47639db2006-03-06 00:22:00 +0000211HazardRecognizer::~HazardRecognizer() {}
212
Evan Chengc4c339c2006-01-26 00:30:29 +0000213
214/// NewSUnit - Creates a new SUnit and return a ptr to it.
215SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
Chris Lattnerfd22d422006-03-08 05:18:27 +0000216 SUnits.push_back(SUnit(N, SUnits.size()));
Chris Lattner42e20262006-03-08 04:54:34 +0000217 return &SUnits.back();
Evan Chengc4c339c2006-01-26 00:30:29 +0000218}
219
220/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
221/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattner399bee22006-03-09 06:48:37 +0000222void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain) {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000223 // FIXME: the distance between two nodes is not always == the predecessor's
224 // latency. For example, the reader can very well read the register written
225 // by the predecessor later than the issue cycle. It also depends on the
226 // interrupt model (drain vs. freeze).
Chris Lattner12c6d892006-03-08 04:41:06 +0000227 PredSU->CycleBound = std::max(PredSU->CycleBound,CurrCycle + PredSU->Latency);
Evan Cheng4e3904f2006-03-02 21:38:29 +0000228
Evan Chengc5c06582006-03-06 06:08:54 +0000229 if (!isChain)
Evan Cheng4e3904f2006-03-02 21:38:29 +0000230 PredSU->NumSuccsLeft--;
Evan Chengc5c06582006-03-06 06:08:54 +0000231 else
Evan Cheng4e3904f2006-03-02 21:38:29 +0000232 PredSU->NumChainSuccsLeft--;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000233
Evan Chengab495562006-01-25 09:14:32 +0000234#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000235 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
Evan Chengab495562006-01-25 09:14:32 +0000236 std::cerr << "*** List scheduling failed! ***\n";
237 PredSU->dump(&DAG);
238 std::cerr << " has been released too many times!\n";
239 assert(0);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000240 }
Evan Chengab495562006-01-25 09:14:32 +0000241#endif
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000242
243 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
244 // EntryToken has to go last! Special case it here.
Chris Lattner349e9dd2006-03-10 05:51:05 +0000245 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
246 PredSU->isAvailable = true;
Chris Lattner399bee22006-03-09 06:48:37 +0000247 PriorityQueue->push(PredSU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000248 }
Evan Chengab495562006-01-25 09:14:32 +0000249 }
Evan Chengab495562006-01-25 09:14:32 +0000250}
251
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000252/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
253/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattner399bee22006-03-09 06:48:37 +0000254void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000255 // FIXME: the distance between two nodes is not always == the predecessor's
256 // latency. For example, the reader can very well read the register written
257 // by the predecessor later than the issue cycle. It also depends on the
258 // interrupt model (drain vs. freeze).
Chris Lattner12c6d892006-03-08 04:41:06 +0000259 SuccSU->CycleBound = std::max(SuccSU->CycleBound,CurrCycle + SuccSU->Latency);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000260
Evan Chengc5c06582006-03-06 06:08:54 +0000261 if (!isChain)
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000262 SuccSU->NumPredsLeft--;
Evan Chengc5c06582006-03-06 06:08:54 +0000263 else
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000264 SuccSU->NumChainPredsLeft--;
265
266#ifndef NDEBUG
267 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
268 std::cerr << "*** List scheduling failed! ***\n";
269 SuccSU->dump(&DAG);
270 std::cerr << " has been released too many times!\n";
271 abort();
272 }
273#endif
274
Chris Lattner349e9dd2006-03-10 05:51:05 +0000275 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
276 SuccSU->isAvailable = true;
Chris Lattner399bee22006-03-09 06:48:37 +0000277 PriorityQueue->push(SuccSU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000278 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000279}
280
281/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
282/// count of its predecessors. If a predecessor pending count is zero, add it to
283/// the Available queue.
Chris Lattner399bee22006-03-09 06:48:37 +0000284void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU) {
Evan Cheng5e9a6952006-03-03 06:23:43 +0000285 DEBUG(std::cerr << "*** Scheduling: ");
Chris Lattnerd4130372006-03-09 07:15:18 +0000286 DEBUG(SU->dump(&DAG));
Evan Cheng5e9a6952006-03-03 06:23:43 +0000287
Evan Chengab495562006-01-25 09:14:32 +0000288 Sequence.push_back(SU);
Evan Chengab495562006-01-25 09:14:32 +0000289
290 // Bottom up: release predecessors
Chris Lattner578d8fc2006-03-11 22:24:20 +0000291 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
292 E = SU->Preds.end(); I != E; ++I) {
293 ReleasePred(I->first, I->second);
294 if (!I->second)
295 SU->NumPredsLeft--;
Evan Cheng4e3904f2006-03-02 21:38:29 +0000296 }
Evan Chengab495562006-01-25 09:14:32 +0000297 CurrCycle++;
298}
299
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000300/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
301/// count of its successors. If a successor pending count is zero, add it to
302/// the Available queue.
Chris Lattner399bee22006-03-09 06:48:37 +0000303void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000304 DEBUG(std::cerr << "*** Scheduling: ");
Chris Lattnerd4130372006-03-09 07:15:18 +0000305 DEBUG(SU->dump(&DAG));
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000306
307 Sequence.push_back(SU);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000308
309 // Bottom up: release successors.
Chris Lattner578d8fc2006-03-11 22:24:20 +0000310 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
311 E = SU->Succs.end(); I != E; ++I) {
312 ReleaseSucc(I->first, I->second);
313 if (!I->second)
314 SU->NumSuccsLeft--;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000315 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000316 CurrCycle++;
317}
318
Evan Chengab495562006-01-25 09:14:32 +0000319/// isReady - True if node's lower cycle bound is less or equal to the current
320/// scheduling cycle. Always true if all nodes have uniform latency 1.
321static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
322 return SU->CycleBound <= CurrCycle;
323}
324
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000325/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
326/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000327void ScheduleDAGList::ListScheduleBottomUp() {
Chris Lattner7a36d972006-03-05 20:21:55 +0000328 // Add root to Available queue.
Chris Lattner399bee22006-03-09 06:48:37 +0000329 PriorityQueue->push(SUnitMap[DAG.getRoot().Val]);
Evan Chengab495562006-01-25 09:14:32 +0000330
331 // While Available queue is not empty, grab the node with the highest
332 // priority. If it is not ready put it back. Schedule the node.
333 std::vector<SUnit*> NotReady;
Chris Lattner399bee22006-03-09 06:48:37 +0000334 while (!PriorityQueue->empty()) {
335 SUnit *CurrNode = PriorityQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000336
Evan Chengab495562006-01-25 09:14:32 +0000337 while (!isReady(CurrNode, CurrCycle)) {
338 NotReady.push_back(CurrNode);
Chris Lattner399bee22006-03-09 06:48:37 +0000339 CurrNode = PriorityQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000340 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000341
342 // Add the nodes that aren't ready back onto the available list.
Chris Lattner25e25562006-03-10 04:32:49 +0000343 PriorityQueue->push_all(NotReady);
344 NotReady.clear();
Evan Chengab495562006-01-25 09:14:32 +0000345
Chris Lattner399bee22006-03-09 06:48:37 +0000346 ScheduleNodeBottomUp(CurrNode);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000347 CurrNode->isScheduled = true;
348 PriorityQueue->ScheduledNode(CurrNode);
Evan Chengab495562006-01-25 09:14:32 +0000349 }
350
351 // Add entry node last
352 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
353 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Evan Chengab495562006-01-25 09:14:32 +0000354 Sequence.push_back(Entry);
355 }
356
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000357 // Reverse the order if it is bottom up.
358 std::reverse(Sequence.begin(), Sequence.end());
359
360
Evan Chengab495562006-01-25 09:14:32 +0000361#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000362 // Verify that all SUnits were scheduled.
Evan Chengc4c339c2006-01-26 00:30:29 +0000363 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000364 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
365 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
Evan Chengc4c339c2006-01-26 00:30:29 +0000366 if (!AnyNotSched)
367 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000368 SUnits[i].dump(&DAG);
Evan Chengc4c339c2006-01-26 00:30:29 +0000369 std::cerr << "has not been scheduled!\n";
370 AnyNotSched = true;
Evan Chengab495562006-01-25 09:14:32 +0000371 }
Evan Chengab495562006-01-25 09:14:32 +0000372 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000373 assert(!AnyNotSched);
Reid Spencer5edde662006-01-25 21:49:13 +0000374#endif
Evan Chengab495562006-01-25 09:14:32 +0000375}
376
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000377/// ListScheduleTopDown - The main loop of list scheduling for top-down
378/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000379void ScheduleDAGList::ListScheduleTopDown() {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000380 // Emit the entry node first.
381 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Chris Lattner399bee22006-03-09 06:48:37 +0000382 ScheduleNodeTopDown(Entry);
Chris Lattner543832d2006-03-08 04:25:59 +0000383 HazardRec->EmitInstruction(Entry->Node);
Chris Lattnere50c0922006-03-05 22:45:01 +0000384
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000385 // All leaves to Available queue.
Chris Lattner42e20262006-03-08 04:54:34 +0000386 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000387 // It is available if it has no predecessors.
Chris Lattner578d8fc2006-03-11 22:24:20 +0000388 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry)
Chris Lattner399bee22006-03-09 06:48:37 +0000389 PriorityQueue->push(&SUnits[i]);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000390 }
391
392 // While Available queue is not empty, grab the node with the highest
393 // priority. If it is not ready put it back. Schedule the node.
394 std::vector<SUnit*> NotReady;
Chris Lattner399bee22006-03-09 06:48:37 +0000395 while (!PriorityQueue->empty()) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000396 SUnit *FoundNode = 0;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000397
Chris Lattnere50c0922006-03-05 22:45:01 +0000398 bool HasNoopHazards = false;
399 do {
Chris Lattner399bee22006-03-09 06:48:37 +0000400 SUnit *CurNode = PriorityQueue->pop();
Chris Lattner0c801bd2006-03-07 05:40:43 +0000401
402 // Get the node represented by this SUnit.
403 SDNode *N = CurNode->Node;
404 // If this is a pseudo op, like copyfromreg, look to see if there is a
405 // real target node flagged to it. If so, use the target node.
406 for (unsigned i = 0, e = CurNode->FlaggedNodes.size();
407 N->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
408 N = CurNode->FlaggedNodes[i];
409
Chris Lattner543832d2006-03-08 04:25:59 +0000410 HazardRecognizer::HazardType HT = HazardRec->getHazardType(N);
Chris Lattnere50c0922006-03-05 22:45:01 +0000411 if (HT == HazardRecognizer::NoHazard) {
Chris Lattner0c801bd2006-03-07 05:40:43 +0000412 FoundNode = CurNode;
Chris Lattnere50c0922006-03-05 22:45:01 +0000413 break;
414 }
415
416 // Remember if this is a noop hazard.
417 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
418
Chris Lattner0c801bd2006-03-07 05:40:43 +0000419 NotReady.push_back(CurNode);
Chris Lattner399bee22006-03-09 06:48:37 +0000420 } while (!PriorityQueue->empty());
Chris Lattnere50c0922006-03-05 22:45:01 +0000421
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000422 // Add the nodes that aren't ready back onto the available list.
Chris Lattner25e25562006-03-10 04:32:49 +0000423 PriorityQueue->push_all(NotReady);
424 NotReady.clear();
Chris Lattnere50c0922006-03-05 22:45:01 +0000425
426 // If we found a node to schedule, do it now.
427 if (FoundNode) {
Chris Lattner399bee22006-03-09 06:48:37 +0000428 ScheduleNodeTopDown(FoundNode);
Chris Lattner543832d2006-03-08 04:25:59 +0000429 HazardRec->EmitInstruction(FoundNode->Node);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000430 FoundNode->isScheduled = true;
431 PriorityQueue->ScheduledNode(FoundNode);
Chris Lattnere50c0922006-03-05 22:45:01 +0000432 } else if (!HasNoopHazards) {
433 // Otherwise, we have a pipeline stall, but no other problem, just advance
434 // the current cycle and try again.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000435 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000436 HazardRec->AdvanceCycle();
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000437 ++NumStalls;
Chris Lattnere50c0922006-03-05 22:45:01 +0000438 } else {
439 // Otherwise, we have no instructions to issue and we have instructions
440 // that will fault if we don't do this right. This is the case for
441 // processors without pipeline interlocks and other cases.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000442 DEBUG(std::cerr << "*** Emitting noop\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000443 HazardRec->EmitNoop();
Chris Lattner00b52ea2006-03-05 23:59:20 +0000444 Sequence.push_back(0); // NULL SUnit* -> noop
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000445 ++NumNoops;
Chris Lattnere50c0922006-03-05 22:45:01 +0000446 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000447 }
448
449#ifndef NDEBUG
450 // Verify that all SUnits were scheduled.
451 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000452 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
453 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000454 if (!AnyNotSched)
455 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000456 SUnits[i].dump(&DAG);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000457 std::cerr << "has not been scheduled!\n";
458 AnyNotSched = true;
459 }
460 }
461 assert(!AnyNotSched);
462#endif
463}
464
465
Evan Chengab495562006-01-25 09:14:32 +0000466void ScheduleDAGList::BuildSchedUnits() {
Chris Lattner42e20262006-03-08 04:54:34 +0000467 // Reserve entries in the vector for each of the SUnits we are creating. This
468 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
469 // invalidated.
Chris Lattner6f82fe82006-03-10 07:13:32 +0000470 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
Chris Lattner42e20262006-03-08 04:54:34 +0000471
Chris Lattnerd4130372006-03-09 07:15:18 +0000472 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
473
Chris Lattner6f82fe82006-03-10 07:13:32 +0000474 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
475 E = DAG.allnodes_end(); NI != E; ++NI) {
476 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
Evan Chengc4c339c2006-01-26 00:30:29 +0000477 continue;
Chris Lattner6f82fe82006-03-10 07:13:32 +0000478
479 // If this node has already been processed, stop now.
480 if (SUnitMap[NI]) continue;
481
482 SUnit *NodeSUnit = NewSUnit(NI);
Evan Chengab495562006-01-25 09:14:32 +0000483
Chris Lattner6f82fe82006-03-10 07:13:32 +0000484 // See if anything is flagged to this node, if so, add them to flagged
485 // nodes. Nodes can have at most one flag input and one flag output. Flags
486 // are required the be the last operand and result of a node.
487
488 // Scan up, adding flagged preds to FlaggedNodes.
489 SDNode *N = NI;
490 while (N->getNumOperands() &&
491 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
492 N = N->getOperand(N->getNumOperands()-1).Val;
493 NodeSUnit->FlaggedNodes.push_back(N);
494 SUnitMap[N] = NodeSUnit;
Evan Chengc4c339c2006-01-26 00:30:29 +0000495 }
Chris Lattner6f82fe82006-03-10 07:13:32 +0000496
497 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
498 // have a user of the flag operand.
499 N = NI;
500 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
501 SDOperand FlagVal(N, N->getNumValues()-1);
502
503 // There are either zero or one users of the Flag result.
504 bool HasFlagUse = false;
505 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
506 UI != E; ++UI)
507 if (FlagVal.isOperand(*UI)) {
508 HasFlagUse = true;
509 NodeSUnit->FlaggedNodes.push_back(N);
510 SUnitMap[N] = NodeSUnit;
511 N = *UI;
512 break;
513 }
514 if (!HasFlagUse) break;
515 }
516
517 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
518 // Update the SUnit
519 NodeSUnit->Node = N;
520 SUnitMap[N] = NodeSUnit;
521
Chris Lattnerd4130372006-03-09 07:15:18 +0000522 // Compute the latency for the node. We use the sum of the latencies for
523 // all nodes flagged together into this SUnit.
Chris Lattnerc6c9e652006-03-09 17:31:22 +0000524 if (InstrItins.isEmpty()) {
Chris Lattnerd4130372006-03-09 07:15:18 +0000525 // No latency information.
Chris Lattner6f82fe82006-03-10 07:13:32 +0000526 NodeSUnit->Latency = 1;
Chris Lattnerd4130372006-03-09 07:15:18 +0000527 } else {
Chris Lattner6f82fe82006-03-10 07:13:32 +0000528 NodeSUnit->Latency = 0;
Chris Lattnerd4130372006-03-09 07:15:18 +0000529 if (N->isTargetOpcode()) {
530 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
531 InstrStage *S = InstrItins.begin(SchedClass);
532 InstrStage *E = InstrItins.end(SchedClass);
533 for (; S != E; ++S)
Chris Lattner6f82fe82006-03-10 07:13:32 +0000534 NodeSUnit->Latency += S->Cycles;
Chris Lattnerd4130372006-03-09 07:15:18 +0000535 }
Chris Lattner6f82fe82006-03-10 07:13:32 +0000536 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
537 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
Chris Lattnerd4130372006-03-09 07:15:18 +0000538 if (FNode->isTargetOpcode()) {
539 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
540 InstrStage *S = InstrItins.begin(SchedClass);
541 InstrStage *E = InstrItins.end(SchedClass);
542 for (; S != E; ++S)
Chris Lattner6f82fe82006-03-10 07:13:32 +0000543 NodeSUnit->Latency += S->Cycles;
Chris Lattnerd4130372006-03-09 07:15:18 +0000544 }
545 }
546 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000547 }
Evan Chengab495562006-01-25 09:14:32 +0000548
Evan Chengc4c339c2006-01-26 00:30:29 +0000549 // Pass 2: add the preds, succs, etc.
Chris Lattner6f82fe82006-03-10 07:13:32 +0000550 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
551 SUnit *SU = &SUnits[su];
552 SDNode *MainNode = SU->Node;
Evan Cheng5e9a6952006-03-03 06:23:43 +0000553
Chris Lattner6f82fe82006-03-10 07:13:32 +0000554 if (MainNode->isTargetOpcode() &&
555 TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
Evan Cheng5e9a6952006-03-03 06:23:43 +0000556 SU->isTwoAddress = true;
Evan Chengc4c339c2006-01-26 00:30:29 +0000557
Chris Lattner6f82fe82006-03-10 07:13:32 +0000558 // Find all predecessors and successors of the group.
559 // Temporarily add N to make code simpler.
560 SU->FlaggedNodes.push_back(MainNode);
561
562 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
563 SDNode *N = SU->FlaggedNodes[n];
564
565 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
566 SDNode *OpN = N->getOperand(i).Val;
567 if (isPassiveNode(OpN)) continue; // Not scheduled.
568 SUnit *OpSU = SUnitMap[OpN];
569 assert(OpSU && "Node has no SUnit!");
570 if (OpSU == SU) continue; // In the same group.
571
572 MVT::ValueType OpVT = N->getOperand(i).getValueType();
573 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
Chris Lattner578d8fc2006-03-11 22:24:20 +0000574 bool isChain = OpVT == MVT::Other;
575
576 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
577 if (!isChain) {
Chris Lattner6f82fe82006-03-10 07:13:32 +0000578 SU->NumPredsLeft++;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000579 } else {
580 SU->NumChainPredsLeft++;
581 }
582 }
583 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
584 if (!isChain) {
Chris Lattner6f82fe82006-03-10 07:13:32 +0000585 OpSU->NumSuccsLeft++;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000586 } else {
587 OpSU->NumChainSuccsLeft++;
588 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000589 }
590 }
Evan Chengab495562006-01-25 09:14:32 +0000591 }
Chris Lattnerd4130372006-03-09 07:15:18 +0000592
Chris Lattner6f82fe82006-03-10 07:13:32 +0000593 // Remove MainNode from FlaggedNodes again.
594 SU->FlaggedNodes.pop_back();
Evan Chengab495562006-01-25 09:14:32 +0000595 }
Chris Lattner578d8fc2006-03-11 22:24:20 +0000596 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
597 SUnits[su].dumpAll(&DAG));
Evan Chengab495562006-01-25 09:14:32 +0000598}
599
600/// EmitSchedule - Emit the machine code in scheduled order.
601void ScheduleDAGList::EmitSchedule() {
Chris Lattnerb9d8fa02006-03-10 07:25:12 +0000602 std::map<SDNode*, unsigned> VRBaseMap;
Evan Chengab495562006-01-25 09:14:32 +0000603 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
Chris Lattner2d945ba2006-03-05 23:51:47 +0000604 if (SUnit *SU = Sequence[i]) {
Chris Lattnerdc2f1352006-03-10 07:28:36 +0000605 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
606 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
607 EmitNode(SU->Node, VRBaseMap);
Chris Lattner2d945ba2006-03-05 23:51:47 +0000608 } else {
609 // Null SUnit* is a noop.
610 EmitNoop();
Evan Chengab495562006-01-25 09:14:32 +0000611 }
Evan Chengab495562006-01-25 09:14:32 +0000612 }
613}
614
615/// dump - dump the schedule.
Chris Lattnerd4130372006-03-09 07:15:18 +0000616void ScheduleDAGList::dumpSchedule() const {
Evan Chengab495562006-01-25 09:14:32 +0000617 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
Chris Lattner2d945ba2006-03-05 23:51:47 +0000618 if (SUnit *SU = Sequence[i])
Chris Lattnerd4130372006-03-09 07:15:18 +0000619 SU->dump(&DAG);
Chris Lattner2d945ba2006-03-05 23:51:47 +0000620 else
621 std::cerr << "**** NOOP ****\n";
Evan Chengab495562006-01-25 09:14:32 +0000622 }
623}
624
625/// Schedule - Schedule the DAG using list scheduling.
626/// FIXME: Right now it only supports the burr (bottom up register reducing)
627/// heuristic.
Evan Cheng31272342006-01-23 08:26:10 +0000628void ScheduleDAGList::Schedule() {
Evan Chengab495562006-01-25 09:14:32 +0000629 DEBUG(std::cerr << "********** List Scheduling **********\n");
630
631 // Build scheduling units.
632 BuildSchedUnits();
Chris Lattnerfd22d422006-03-08 05:18:27 +0000633
Chris Lattner9df64752006-03-09 06:35:14 +0000634 PriorityQueue->initNodes(SUnits);
635
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000636 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
637 if (isBottomUp)
Chris Lattner399bee22006-03-09 06:48:37 +0000638 ListScheduleBottomUp();
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000639 else
Chris Lattner399bee22006-03-09 06:48:37 +0000640 ListScheduleTopDown();
Chris Lattner9df64752006-03-09 06:35:14 +0000641
642 PriorityQueue->releaseState();
643
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000644 DEBUG(std::cerr << "*** Final schedule ***\n");
Chris Lattnerd4130372006-03-09 07:15:18 +0000645 DEBUG(dumpSchedule());
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000646 DEBUG(std::cerr << "\n");
647
Evan Chengab495562006-01-25 09:14:32 +0000648 // Emit in scheduled order
649 EmitSchedule();
Evan Cheng31272342006-01-23 08:26:10 +0000650}
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000651
Chris Lattner9df64752006-03-09 06:35:14 +0000652//===----------------------------------------------------------------------===//
653// RegReductionPriorityQueue Implementation
654//===----------------------------------------------------------------------===//
655//
656// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
657// to reduce register pressure.
658//
659namespace {
660 class RegReductionPriorityQueue;
661
662 /// Sorting functions for the Available queue.
663 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
664 RegReductionPriorityQueue *SPQ;
665 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
666 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
667
668 bool operator()(const SUnit* left, const SUnit* right) const;
669 };
670} // end anonymous namespace
671
672namespace {
673 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
674 // SUnits - The SUnits for the current graph.
675 const std::vector<SUnit> *SUnits;
676
677 // SethiUllmanNumbers - The SethiUllman number for each node.
678 std::vector<int> SethiUllmanNumbers;
679
680 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
681 public:
682 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
683 }
684
685 void initNodes(const std::vector<SUnit> &sunits) {
686 SUnits = &sunits;
687 // Calculate node priorities.
688 CalculatePriorities();
689 }
690 void releaseState() {
691 SUnits = 0;
692 SethiUllmanNumbers.clear();
693 }
694
695 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
696 assert(NodeNum < SethiUllmanNumbers.size());
697 return SethiUllmanNumbers[NodeNum];
698 }
699
700 bool empty() const { return Queue.empty(); }
701
702 void push(SUnit *U) {
703 Queue.push(U);
704 }
Chris Lattner25e25562006-03-10 04:32:49 +0000705 void push_all(const std::vector<SUnit *> &Nodes) {
706 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
707 Queue.push(Nodes[i]);
708 }
709
Chris Lattner9df64752006-03-09 06:35:14 +0000710 SUnit *pop() {
711 SUnit *V = Queue.top();
712 Queue.pop();
713 return V;
714 }
715 private:
716 void CalculatePriorities();
717 int CalcNodePriority(const SUnit *SU);
718 };
719}
720
721bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
722 unsigned LeftNum = left->NodeNum;
723 unsigned RightNum = right->NodeNum;
724
725 int LBonus = (int)left ->isDefNUseOperand;
726 int RBonus = (int)right->isDefNUseOperand;
727
728 // Special tie breaker: if two nodes share a operand, the one that
729 // use it as a def&use operand is preferred.
730 if (left->isTwoAddress && !right->isTwoAddress) {
731 SDNode *DUNode = left->Node->getOperand(0).Val;
732 if (DUNode->isOperand(right->Node))
733 LBonus++;
734 }
735 if (!left->isTwoAddress && right->isTwoAddress) {
736 SDNode *DUNode = right->Node->getOperand(0).Val;
737 if (DUNode->isOperand(left->Node))
738 RBonus++;
739 }
740
741 // Priority1 is just the number of live range genned.
742 int LPriority1 = left ->NumPredsLeft - LBonus;
743 int RPriority1 = right->NumPredsLeft - RBonus;
744 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
745 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
746
747 if (LPriority1 > RPriority1)
748 return true;
749 else if (LPriority1 == RPriority1)
750 if (LPriority2 < RPriority2)
751 return true;
752 else if (LPriority2 == RPriority2)
753 if (left->CycleBound > right->CycleBound)
754 return true;
755
756 return false;
757}
758
759
760/// CalcNodePriority - Priority is the Sethi Ullman number.
761/// Smaller number is the higher priority.
762int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
763 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
764 if (SethiUllmanNumber != INT_MIN)
765 return SethiUllmanNumber;
766
767 if (SU->Preds.size() == 0) {
768 SethiUllmanNumber = 1;
769 } else {
770 int Extra = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000771 for (std::set<std::pair<SUnit*, bool> >::const_iterator
772 I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
773 if (I->second) continue; // ignore chain preds.
774 SUnit *PredSU = I->first;
Chris Lattner9df64752006-03-09 06:35:14 +0000775 int PredSethiUllman = CalcNodePriority(PredSU);
776 if (PredSethiUllman > SethiUllmanNumber) {
777 SethiUllmanNumber = PredSethiUllman;
778 Extra = 0;
779 } else if (PredSethiUllman == SethiUllmanNumber)
780 Extra++;
781 }
782
783 if (SU->Node->getOpcode() != ISD::TokenFactor)
784 SethiUllmanNumber += Extra;
785 else
786 SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
787 }
788
789 return SethiUllmanNumber;
790}
791
792/// CalculatePriorities - Calculate priorities of all scheduling units.
793void RegReductionPriorityQueue::CalculatePriorities() {
794 SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
795
796 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
797 CalcNodePriority(&(*SUnits)[i]);
798}
799
Chris Lattner6398c132006-03-09 07:38:27 +0000800//===----------------------------------------------------------------------===//
801// LatencyPriorityQueue Implementation
802//===----------------------------------------------------------------------===//
803//
804// This is a SchedulingPriorityQueue that schedules using latency information to
805// reduce the length of the critical path through the basic block.
806//
807namespace {
808 class LatencyPriorityQueue;
809
810 /// Sorting functions for the Available queue.
811 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
812 LatencyPriorityQueue *PQ;
813 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
814 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
815
816 bool operator()(const SUnit* left, const SUnit* right) const;
817 };
818} // end anonymous namespace
819
820namespace {
821 class LatencyPriorityQueue : public SchedulingPriorityQueue {
822 // SUnits - The SUnits for the current graph.
823 const std::vector<SUnit> *SUnits;
824
825 // Latencies - The latency (max of latency from this node to the bb exit)
826 // for each node.
827 std::vector<int> Latencies;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000828
829 /// NumNodesSolelyBlocking - This vector contains, for every node in the
830 /// Queue, the number of nodes that the node is the sole unscheduled
831 /// predecessor for. This is used as a tie-breaker heuristic for better
832 /// mobility.
833 std::vector<unsigned> NumNodesSolelyBlocking;
834
Chris Lattner6398c132006-03-09 07:38:27 +0000835 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
836public:
837 LatencyPriorityQueue() : Queue(latency_sort(this)) {
838 }
839
840 void initNodes(const std::vector<SUnit> &sunits) {
841 SUnits = &sunits;
842 // Calculate node priorities.
843 CalculatePriorities();
844 }
845 void releaseState() {
846 SUnits = 0;
847 Latencies.clear();
848 }
849
850 unsigned getLatency(unsigned NodeNum) const {
851 assert(NodeNum < Latencies.size());
852 return Latencies[NodeNum];
853 }
854
Chris Lattner349e9dd2006-03-10 05:51:05 +0000855 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
856 assert(NodeNum < NumNodesSolelyBlocking.size());
857 return NumNodesSolelyBlocking[NodeNum];
858 }
859
Chris Lattner6398c132006-03-09 07:38:27 +0000860 bool empty() const { return Queue.empty(); }
861
Chris Lattner349e9dd2006-03-10 05:51:05 +0000862 virtual void push(SUnit *U) {
863 push_impl(U);
Chris Lattner6398c132006-03-09 07:38:27 +0000864 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000865 void push_impl(SUnit *U);
866
Chris Lattner25e25562006-03-10 04:32:49 +0000867 void push_all(const std::vector<SUnit *> &Nodes) {
868 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner349e9dd2006-03-10 05:51:05 +0000869 push_impl(Nodes[i]);
Chris Lattner25e25562006-03-10 04:32:49 +0000870 }
871
Chris Lattner6398c132006-03-09 07:38:27 +0000872 SUnit *pop() {
873 SUnit *V = Queue.top();
874 Queue.pop();
Chris Lattner6398c132006-03-09 07:38:27 +0000875 return V;
876 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000877
878 // ScheduledNode - As nodes are scheduled, we look to see if there are any
879 // successor nodes that have a single unscheduled predecessor. If so, that
880 // single predecessor has a higher priority, since scheduling it will make
881 // the node available.
882 void ScheduledNode(SUnit *Node);
883
Chris Lattner6398c132006-03-09 07:38:27 +0000884private:
885 void CalculatePriorities();
886 int CalcLatency(const SUnit &SU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000887 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
888
889 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
890 /// node from a priority queue. We should roll our own heap to make this
891 /// better or something.
892 void RemoveFromPriorityQueue(SUnit *SU) {
893 std::vector<SUnit*> Temp;
894
895 assert(!Queue.empty() && "Not in queue!");
896 while (Queue.top() != SU) {
897 Temp.push_back(Queue.top());
898 Queue.pop();
899 assert(!Queue.empty() && "Not in queue!");
900 }
901
902 // Remove the node from the PQ.
903 Queue.pop();
904
905 // Add all the other nodes back.
906 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
907 Queue.push(Temp[i]);
908 }
Chris Lattner6398c132006-03-09 07:38:27 +0000909 };
910}
911
912bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
913 unsigned LHSNum = LHS->NodeNum;
914 unsigned RHSNum = RHS->NodeNum;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000915
916 // The most important heuristic is scheduling the critical path.
917 unsigned LHSLatency = PQ->getLatency(LHSNum);
918 unsigned RHSLatency = PQ->getLatency(RHSNum);
919 if (LHSLatency < RHSLatency) return true;
920 if (LHSLatency > RHSLatency) return false;
Chris Lattner6398c132006-03-09 07:38:27 +0000921
Chris Lattner349e9dd2006-03-10 05:51:05 +0000922 // After that, if two nodes have identical latencies, look to see if one will
923 // unblock more other nodes than the other.
924 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
925 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
926 if (LHSBlocked < RHSBlocked) return true;
927 if (LHSBlocked > RHSBlocked) return false;
928
929 // Finally, just to provide a stable ordering, use the node number as a
930 // deciding factor.
931 return LHSNum < RHSNum;
Chris Lattner6398c132006-03-09 07:38:27 +0000932}
933
934
935/// CalcNodePriority - Calculate the maximal path from the node to the exit.
936///
937int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
938 int &Latency = Latencies[SU.NodeNum];
939 if (Latency != -1)
940 return Latency;
941
942 int MaxSuccLatency = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000943 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
Chris Lattner6398c132006-03-09 07:38:27 +0000944 E = SU.Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +0000945 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
Chris Lattner6398c132006-03-09 07:38:27 +0000946
947 return Latency = MaxSuccLatency + SU.Latency;
948}
949
950/// CalculatePriorities - Calculate priorities of all scheduling units.
951void LatencyPriorityQueue::CalculatePriorities() {
952 Latencies.assign(SUnits->size(), -1);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000953 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
Chris Lattner6398c132006-03-09 07:38:27 +0000954
955 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
956 CalcLatency((*SUnits)[i]);
957}
958
Chris Lattner349e9dd2006-03-10 05:51:05 +0000959/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
960/// of SU, return it, otherwise return null.
961static SUnit *getSingleUnscheduledPred(SUnit *SU) {
962 SUnit *OnlyAvailablePred = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000963 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +0000964 E = SU->Preds.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +0000965 if (!I->first->isScheduled) {
Chris Lattner349e9dd2006-03-10 05:51:05 +0000966 // We found an available, but not scheduled, predecessor. If it's the
967 // only one we have found, keep track of it... otherwise give up.
Chris Lattner578d8fc2006-03-11 22:24:20 +0000968 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
Chris Lattner349e9dd2006-03-10 05:51:05 +0000969 return 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000970 OnlyAvailablePred = I->first;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000971 }
972
973 return OnlyAvailablePred;
974}
975
976void LatencyPriorityQueue::push_impl(SUnit *SU) {
977 // Look at all of the successors of this node. Count the number of nodes that
978 // this node is the sole unscheduled node for.
979 unsigned NumNodesBlocking = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000980 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +0000981 E = SU->Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +0000982 if (getSingleUnscheduledPred(I->first) == SU)
Chris Lattner349e9dd2006-03-10 05:51:05 +0000983 ++NumNodesBlocking;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000984 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000985
986 Queue.push(SU);
987}
988
989
990// ScheduledNode - As nodes are scheduled, we look to see if there are any
991// successor nodes that have a single unscheduled predecessor. If so, that
992// single predecessor has a higher priority, since scheduling it will make
993// the node available.
994void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
Chris Lattner578d8fc2006-03-11 22:24:20 +0000995 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +0000996 E = SU->Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +0000997 AdjustPriorityOfUnscheduledPreds(I->first);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000998}
999
1000/// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1001/// scheduled. If SU is not itself available, then there is at least one
1002/// predecessor node that has not been scheduled yet. If SU has exactly ONE
1003/// unscheduled predecessor, we want to increase its priority: it getting
1004/// scheduled will make this node available, so it is better than some other
1005/// node of the same priority that will not make a node available.
1006void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1007 if (SU->isAvailable) return; // All preds scheduled.
1008
1009 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1010 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1011
1012 // Okay, we found a single predecessor that is available, but not scheduled.
1013 // Since it is available, it must be in the priority queue. First remove it.
1014 RemoveFromPriorityQueue(OnlyAvailablePred);
1015
1016 // Reinsert the node into the priority queue, which recomputes its
1017 // NumNodesSolelyBlocking value.
1018 push(OnlyAvailablePred);
1019}
1020
Chris Lattner9df64752006-03-09 06:35:14 +00001021
1022//===----------------------------------------------------------------------===//
1023// Public Constructor Functions
1024//===----------------------------------------------------------------------===//
1025
Evan Chengab495562006-01-25 09:14:32 +00001026llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1027 MachineBasicBlock *BB) {
Chris Lattner543832d2006-03-08 04:25:59 +00001028 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
Chris Lattner9df64752006-03-09 06:35:14 +00001029 new RegReductionPriorityQueue(),
Chris Lattner543832d2006-03-08 04:25:59 +00001030 new HazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00001031}
1032
Chris Lattner47639db2006-03-06 00:22:00 +00001033/// createTDListDAGScheduler - This creates a top-down list scheduler with the
1034/// specified hazard recognizer.
1035ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1036 MachineBasicBlock *BB,
Chris Lattner543832d2006-03-08 04:25:59 +00001037 HazardRecognizer *HR) {
Chris Lattner9df64752006-03-09 06:35:14 +00001038 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
Chris Lattner6398c132006-03-09 07:38:27 +00001039 new LatencyPriorityQueue(),
Chris Lattner9df64752006-03-09 06:35:14 +00001040 HR);
Evan Cheng31272342006-01-23 08:26:10 +00001041}