blob: 845fbe7e0ef8cc7882cda8a0f60d8967a0fdaf5f [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.
44 std::set<SUnit*> Preds; // All real predecessors.
45 std::set<SUnit*> ChainPreds; // All chain predecessors.
46 std::set<SUnit*> Succs; // All real successors.
47 std::set<SUnit*> ChainSuccs; // All chain successors.
Chris Lattner12c6d892006-03-08 04:41:06 +000048 short NumPredsLeft; // # of preds not scheduled.
49 short NumSuccsLeft; // # of succs not scheduled.
50 short NumChainPredsLeft; // # of chain preds not scheduled.
51 short NumChainSuccsLeft; // # of chain succs not scheduled.
Chris Lattner12c6d892006-03-08 04:41:06 +000052 bool isTwoAddress : 1; // Is a two-address instruction.
53 bool isDefNUseOperand : 1; // Is a def&use operand.
Chris Lattner349e9dd2006-03-10 05:51:05 +000054 bool isAvailable : 1; // True once available.
55 bool isScheduled : 1; // True once scheduled.
Chris Lattner12c6d892006-03-08 04:41:06 +000056 unsigned short Latency; // Node latency.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000057 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
Chris Lattnerfd22d422006-03-08 05:18:27 +000058 unsigned NodeNum; // Entry # of node in the node vector.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000059
Chris Lattnerfd22d422006-03-08 05:18:27 +000060 SUnit(SDNode *node, unsigned nodenum)
Chris Lattneraf5e26c2006-03-08 04:37:58 +000061 : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
Evan Cheng4e3904f2006-03-02 21:38:29 +000062 NumChainPredsLeft(0), NumChainSuccsLeft(0),
Evan Cheng5e9a6952006-03-03 06:23:43 +000063 isTwoAddress(false), isDefNUseOperand(false),
Chris Lattner349e9dd2006-03-10 05:51:05 +000064 isAvailable(false), isScheduled(false),
Chris Lattnerfd22d422006-03-08 05:18:27 +000065 Latency(0), CycleBound(0), NodeNum(nodenum) {}
Chris Lattneraf5e26c2006-03-08 04:37:58 +000066
Chris Lattnerd4130372006-03-09 07:15:18 +000067 void dump(const SelectionDAG *G) const;
68 void dumpAll(const SelectionDAG *G) const;
Chris Lattneraf5e26c2006-03-08 04:37:58 +000069 };
70}
Evan Chengab495562006-01-25 09:14:32 +000071
Chris Lattnerd4130372006-03-09 07:15:18 +000072void SUnit::dump(const SelectionDAG *G) const {
Evan Chengc4c339c2006-01-26 00:30:29 +000073 std::cerr << "SU: ";
Evan Chengab495562006-01-25 09:14:32 +000074 Node->dump(G);
75 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +000076 if (FlaggedNodes.size() != 0) {
Evan Chengab495562006-01-25 09:14:32 +000077 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
Evan Chengc4c339c2006-01-26 00:30:29 +000078 std::cerr << " ";
Evan Chengab495562006-01-25 09:14:32 +000079 FlaggedNodes[i]->dump(G);
80 std::cerr << "\n";
81 }
82 }
Chris Lattnerd4130372006-03-09 07:15:18 +000083}
Evan Chengab495562006-01-25 09:14:32 +000084
Chris Lattnerd4130372006-03-09 07:15:18 +000085void SUnit::dumpAll(const SelectionDAG *G) const {
86 dump(G);
Evan Chengc4c339c2006-01-26 00:30:29 +000087
Chris Lattnerd4130372006-03-09 07:15:18 +000088 std::cerr << " # preds left : " << NumPredsLeft << "\n";
89 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
90 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
91 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
92 std::cerr << " Latency : " << Latency << "\n";
93
94 if (Preds.size() != 0) {
95 std::cerr << " Predecessors:\n";
96 for (std::set<SUnit*>::const_iterator I = Preds.begin(),
97 E = Preds.end(); I != E; ++I) {
98 std::cerr << " ";
99 (*I)->dump(G);
Evan Chengab495562006-01-25 09:14:32 +0000100 }
101 }
Chris Lattnerd4130372006-03-09 07:15:18 +0000102 if (ChainPreds.size() != 0) {
103 std::cerr << " Chained Preds:\n";
104 for (std::set<SUnit*>::const_iterator I = ChainPreds.begin(),
105 E = ChainPreds.end(); I != E; ++I) {
106 std::cerr << " ";
107 (*I)->dump(G);
108 }
109 }
110 if (Succs.size() != 0) {
111 std::cerr << " Successors:\n";
112 for (std::set<SUnit*>::const_iterator I = Succs.begin(),
113 E = Succs.end(); I != E; ++I) {
114 std::cerr << " ";
115 (*I)->dump(G);
116 }
117 }
118 if (ChainSuccs.size() != 0) {
119 std::cerr << " Chained succs:\n";
120 for (std::set<SUnit*>::const_iterator I = ChainSuccs.begin(),
121 E = ChainSuccs.end(); I != E; ++I) {
122 std::cerr << " ";
123 (*I)->dump(G);
124 }
125 }
126 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +0000127}
128
Chris Lattner9df64752006-03-09 06:35:14 +0000129//===----------------------------------------------------------------------===//
Chris Lattner9e95acc2006-03-09 06:37:29 +0000130/// SchedulingPriorityQueue - This interface is used to plug different
131/// priorities computation algorithms into the list scheduler. It implements the
132/// interface of a standard priority queue, where nodes are inserted in
133/// arbitrary order and returned in priority order. The computation of the
134/// priority and the representation of the queue are totally up to the
135/// implementation to decide.
136///
137namespace {
Chris Lattner9df64752006-03-09 06:35:14 +0000138class SchedulingPriorityQueue {
139public:
140 virtual ~SchedulingPriorityQueue() {}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000141
Chris Lattner9df64752006-03-09 06:35:14 +0000142 virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
143 virtual void releaseState() = 0;
Chris Lattnerfd22d422006-03-08 05:18:27 +0000144
Chris Lattner9df64752006-03-09 06:35:14 +0000145 virtual bool empty() const = 0;
146 virtual void push(SUnit *U) = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000147
148 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
Chris Lattner9df64752006-03-09 06:35:14 +0000149 virtual SUnit *pop() = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000150
151 /// ScheduledNode - As each node is scheduled, this method is invoked. This
152 /// allows the priority function to adjust the priority of node that have
153 /// already been emitted.
154 virtual void ScheduledNode(SUnit *Node) {}
Chris Lattner9df64752006-03-09 06:35:14 +0000155};
Chris Lattner9e95acc2006-03-09 06:37:29 +0000156}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000157
158
Chris Lattnere50c0922006-03-05 22:45:01 +0000159
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000160namespace {
Chris Lattner9e95acc2006-03-09 06:37:29 +0000161//===----------------------------------------------------------------------===//
162/// ScheduleDAGList - The actual list scheduler implementation. This supports
163/// both top-down and bottom-up scheduling.
164///
Evan Cheng31272342006-01-23 08:26:10 +0000165class ScheduleDAGList : public ScheduleDAG {
166private:
Evan Chengab495562006-01-25 09:14:32 +0000167 // SDNode to SUnit mapping (many to one).
168 std::map<SDNode*, SUnit*> SUnitMap;
Chris Lattner00b52ea2006-03-05 23:59:20 +0000169 // The schedule. Null SUnit*'s represent noop instructions.
Evan Chengab495562006-01-25 09:14:32 +0000170 std::vector<SUnit*> Sequence;
171 // Current scheduling cycle.
172 unsigned CurrCycle;
Chris Lattner42e20262006-03-08 04:54:34 +0000173
174 // The scheduling units.
175 std::vector<SUnit> SUnits;
Evan Cheng31272342006-01-23 08:26:10 +0000176
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000177 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
178 /// it is top-down.
179 bool isBottomUp;
180
Chris Lattner9df64752006-03-09 06:35:14 +0000181 /// PriorityQueue - The priority queue to use.
182 SchedulingPriorityQueue *PriorityQueue;
183
Chris Lattnere50c0922006-03-05 22:45:01 +0000184 /// HazardRec - The hazard recognizer to use.
Chris Lattner543832d2006-03-08 04:25:59 +0000185 HazardRecognizer *HazardRec;
Chris Lattnere50c0922006-03-05 22:45:01 +0000186
Evan Cheng31272342006-01-23 08:26:10 +0000187public:
188 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
Chris Lattnere50c0922006-03-05 22:45:01 +0000189 const TargetMachine &tm, bool isbottomup,
Chris Lattner9df64752006-03-09 06:35:14 +0000190 SchedulingPriorityQueue *priorityqueue,
Chris Lattner543832d2006-03-08 04:25:59 +0000191 HazardRecognizer *HR)
Chris Lattnera5b93b82006-03-10 07:42:02 +0000192 : ScheduleDAG(dag, bb, tm),
Chris Lattner9df64752006-03-09 06:35:14 +0000193 CurrCycle(0), isBottomUp(isbottomup),
194 PriorityQueue(priorityqueue), HazardRec(HR) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000195 }
Evan Chengab495562006-01-25 09:14:32 +0000196
197 ~ScheduleDAGList() {
Chris Lattner543832d2006-03-08 04:25:59 +0000198 delete HazardRec;
Chris Lattner9df64752006-03-09 06:35:14 +0000199 delete PriorityQueue;
Evan Chengab495562006-01-25 09:14:32 +0000200 }
Evan Cheng31272342006-01-23 08:26:10 +0000201
202 void Schedule();
Evan Cheng31272342006-01-23 08:26:10 +0000203
Chris Lattnerd4130372006-03-09 07:15:18 +0000204 void dumpSchedule() const;
Evan Chengab495562006-01-25 09:14:32 +0000205
206private:
Evan Chengc4c339c2006-01-26 00:30:29 +0000207 SUnit *NewSUnit(SDNode *N);
Chris Lattner399bee22006-03-09 06:48:37 +0000208 void ReleasePred(SUnit *PredSU, bool isChain = false);
209 void ReleaseSucc(SUnit *SuccSU, bool isChain = false);
210 void ScheduleNodeBottomUp(SUnit *SU);
211 void ScheduleNodeTopDown(SUnit *SU);
212 void ListScheduleTopDown();
213 void ListScheduleBottomUp();
Evan Chengab495562006-01-25 09:14:32 +0000214 void BuildSchedUnits();
215 void EmitSchedule();
216};
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000217} // end anonymous namespace
Evan Chengab495562006-01-25 09:14:32 +0000218
Chris Lattner47639db2006-03-06 00:22:00 +0000219HazardRecognizer::~HazardRecognizer() {}
220
Evan Chengc4c339c2006-01-26 00:30:29 +0000221
222/// NewSUnit - Creates a new SUnit and return a ptr to it.
223SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
Chris Lattnerfd22d422006-03-08 05:18:27 +0000224 SUnits.push_back(SUnit(N, SUnits.size()));
Chris Lattner42e20262006-03-08 04:54:34 +0000225 return &SUnits.back();
Evan Chengc4c339c2006-01-26 00:30:29 +0000226}
227
228/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
229/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattner399bee22006-03-09 06:48:37 +0000230void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain) {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000231 // FIXME: the distance between two nodes is not always == the predecessor's
232 // latency. For example, the reader can very well read the register written
233 // by the predecessor later than the issue cycle. It also depends on the
234 // interrupt model (drain vs. freeze).
Chris Lattner12c6d892006-03-08 04:41:06 +0000235 PredSU->CycleBound = std::max(PredSU->CycleBound,CurrCycle + PredSU->Latency);
Evan Cheng4e3904f2006-03-02 21:38:29 +0000236
Evan Chengc5c06582006-03-06 06:08:54 +0000237 if (!isChain)
Evan Cheng4e3904f2006-03-02 21:38:29 +0000238 PredSU->NumSuccsLeft--;
Evan Chengc5c06582006-03-06 06:08:54 +0000239 else
Evan Cheng4e3904f2006-03-02 21:38:29 +0000240 PredSU->NumChainSuccsLeft--;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000241
Evan Chengab495562006-01-25 09:14:32 +0000242#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000243 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
Evan Chengab495562006-01-25 09:14:32 +0000244 std::cerr << "*** List scheduling failed! ***\n";
245 PredSU->dump(&DAG);
246 std::cerr << " has been released too many times!\n";
247 assert(0);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000248 }
Evan Chengab495562006-01-25 09:14:32 +0000249#endif
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000250
251 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
252 // EntryToken has to go last! Special case it here.
Chris Lattner349e9dd2006-03-10 05:51:05 +0000253 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
254 PredSU->isAvailable = true;
Chris Lattner399bee22006-03-09 06:48:37 +0000255 PriorityQueue->push(PredSU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000256 }
Evan Chengab495562006-01-25 09:14:32 +0000257 }
Evan Chengab495562006-01-25 09:14:32 +0000258}
259
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000260/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
261/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattner399bee22006-03-09 06:48:37 +0000262void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000263 // FIXME: the distance between two nodes is not always == the predecessor's
264 // latency. For example, the reader can very well read the register written
265 // by the predecessor later than the issue cycle. It also depends on the
266 // interrupt model (drain vs. freeze).
Chris Lattner12c6d892006-03-08 04:41:06 +0000267 SuccSU->CycleBound = std::max(SuccSU->CycleBound,CurrCycle + SuccSU->Latency);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000268
Evan Chengc5c06582006-03-06 06:08:54 +0000269 if (!isChain)
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000270 SuccSU->NumPredsLeft--;
Evan Chengc5c06582006-03-06 06:08:54 +0000271 else
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000272 SuccSU->NumChainPredsLeft--;
273
274#ifndef NDEBUG
275 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
276 std::cerr << "*** List scheduling failed! ***\n";
277 SuccSU->dump(&DAG);
278 std::cerr << " has been released too many times!\n";
279 abort();
280 }
281#endif
282
Chris Lattner349e9dd2006-03-10 05:51:05 +0000283 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
284 SuccSU->isAvailable = true;
Chris Lattner399bee22006-03-09 06:48:37 +0000285 PriorityQueue->push(SuccSU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000286 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000287}
288
289/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
290/// count of its predecessors. If a predecessor pending count is zero, add it to
291/// the Available queue.
Chris Lattner399bee22006-03-09 06:48:37 +0000292void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU) {
Evan Cheng5e9a6952006-03-03 06:23:43 +0000293 DEBUG(std::cerr << "*** Scheduling: ");
Chris Lattnerd4130372006-03-09 07:15:18 +0000294 DEBUG(SU->dump(&DAG));
Evan Cheng5e9a6952006-03-03 06:23:43 +0000295
Evan Chengab495562006-01-25 09:14:32 +0000296 Sequence.push_back(SU);
Evan Chengab495562006-01-25 09:14:32 +0000297
298 // Bottom up: release predecessors
Evan Cheng4e3904f2006-03-02 21:38:29 +0000299 for (std::set<SUnit*>::iterator I1 = SU->Preds.begin(),
300 E1 = SU->Preds.end(); I1 != E1; ++I1) {
Chris Lattner399bee22006-03-09 06:48:37 +0000301 ReleasePred(*I1);
Evan Cheng4e3904f2006-03-02 21:38:29 +0000302 SU->NumPredsLeft--;
Evan Cheng4e3904f2006-03-02 21:38:29 +0000303 }
304 for (std::set<SUnit*>::iterator I2 = SU->ChainPreds.begin(),
305 E2 = SU->ChainPreds.end(); I2 != E2; ++I2)
Chris Lattner399bee22006-03-09 06:48:37 +0000306 ReleasePred(*I2, true);
Evan Chengab495562006-01-25 09:14:32 +0000307
308 CurrCycle++;
309}
310
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000311/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
312/// count of its successors. If a successor pending count is zero, add it to
313/// the Available queue.
Chris Lattner399bee22006-03-09 06:48:37 +0000314void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000315 DEBUG(std::cerr << "*** Scheduling: ");
Chris Lattnerd4130372006-03-09 07:15:18 +0000316 DEBUG(SU->dump(&DAG));
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000317
318 Sequence.push_back(SU);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000319
320 // Bottom up: release successors.
321 for (std::set<SUnit*>::iterator I1 = SU->Succs.begin(),
322 E1 = SU->Succs.end(); I1 != E1; ++I1) {
Chris Lattner399bee22006-03-09 06:48:37 +0000323 ReleaseSucc(*I1);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000324 SU->NumSuccsLeft--;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000325 }
326 for (std::set<SUnit*>::iterator I2 = SU->ChainSuccs.begin(),
327 E2 = SU->ChainSuccs.end(); I2 != E2; ++I2)
Chris Lattner399bee22006-03-09 06:48:37 +0000328 ReleaseSucc(*I2, true);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000329
330 CurrCycle++;
331}
332
Evan Chengab495562006-01-25 09:14:32 +0000333/// isReady - True if node's lower cycle bound is less or equal to the current
334/// scheduling cycle. Always true if all nodes have uniform latency 1.
335static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
336 return SU->CycleBound <= CurrCycle;
337}
338
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000339/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
340/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000341void ScheduleDAGList::ListScheduleBottomUp() {
Chris Lattner7a36d972006-03-05 20:21:55 +0000342 // Add root to Available queue.
Chris Lattner399bee22006-03-09 06:48:37 +0000343 PriorityQueue->push(SUnitMap[DAG.getRoot().Val]);
Evan Chengab495562006-01-25 09:14:32 +0000344
345 // While Available queue is not empty, grab the node with the highest
346 // priority. If it is not ready put it back. Schedule the node.
347 std::vector<SUnit*> NotReady;
Chris Lattner399bee22006-03-09 06:48:37 +0000348 while (!PriorityQueue->empty()) {
349 SUnit *CurrNode = PriorityQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000350
Evan Chengab495562006-01-25 09:14:32 +0000351 while (!isReady(CurrNode, CurrCycle)) {
352 NotReady.push_back(CurrNode);
Chris Lattner399bee22006-03-09 06:48:37 +0000353 CurrNode = PriorityQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000354 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000355
356 // Add the nodes that aren't ready back onto the available list.
Chris Lattner25e25562006-03-10 04:32:49 +0000357 PriorityQueue->push_all(NotReady);
358 NotReady.clear();
Evan Chengab495562006-01-25 09:14:32 +0000359
Chris Lattner399bee22006-03-09 06:48:37 +0000360 ScheduleNodeBottomUp(CurrNode);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000361 CurrNode->isScheduled = true;
362 PriorityQueue->ScheduledNode(CurrNode);
Evan Chengab495562006-01-25 09:14:32 +0000363 }
364
365 // Add entry node last
366 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
367 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Evan Chengab495562006-01-25 09:14:32 +0000368 Sequence.push_back(Entry);
369 }
370
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000371 // Reverse the order if it is bottom up.
372 std::reverse(Sequence.begin(), Sequence.end());
373
374
Evan Chengab495562006-01-25 09:14:32 +0000375#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000376 // Verify that all SUnits were scheduled.
Evan Chengc4c339c2006-01-26 00:30:29 +0000377 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000378 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
379 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
Evan Chengc4c339c2006-01-26 00:30:29 +0000380 if (!AnyNotSched)
381 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000382 SUnits[i].dump(&DAG);
Evan Chengc4c339c2006-01-26 00:30:29 +0000383 std::cerr << "has not been scheduled!\n";
384 AnyNotSched = true;
Evan Chengab495562006-01-25 09:14:32 +0000385 }
Evan Chengab495562006-01-25 09:14:32 +0000386 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000387 assert(!AnyNotSched);
Reid Spencer5edde662006-01-25 21:49:13 +0000388#endif
Evan Chengab495562006-01-25 09:14:32 +0000389}
390
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000391/// ListScheduleTopDown - The main loop of list scheduling for top-down
392/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000393void ScheduleDAGList::ListScheduleTopDown() {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000394 // Emit the entry node first.
395 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Chris Lattner399bee22006-03-09 06:48:37 +0000396 ScheduleNodeTopDown(Entry);
Chris Lattner543832d2006-03-08 04:25:59 +0000397 HazardRec->EmitInstruction(Entry->Node);
Chris Lattnere50c0922006-03-05 22:45:01 +0000398
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000399 // All leaves to Available queue.
Chris Lattner42e20262006-03-08 04:54:34 +0000400 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000401 // It is available if it has no predecessors.
Chris Lattner42e20262006-03-08 04:54:34 +0000402 if ((SUnits[i].Preds.size() + SUnits[i].ChainPreds.size()) == 0 &&
403 &SUnits[i] != Entry)
Chris Lattner399bee22006-03-09 06:48:37 +0000404 PriorityQueue->push(&SUnits[i]);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000405 }
406
407 // While Available queue is not empty, grab the node with the highest
408 // priority. If it is not ready put it back. Schedule the node.
409 std::vector<SUnit*> NotReady;
Chris Lattner399bee22006-03-09 06:48:37 +0000410 while (!PriorityQueue->empty()) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000411 SUnit *FoundNode = 0;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000412
Chris Lattnere50c0922006-03-05 22:45:01 +0000413 bool HasNoopHazards = false;
414 do {
Chris Lattner399bee22006-03-09 06:48:37 +0000415 SUnit *CurNode = PriorityQueue->pop();
Chris Lattner0c801bd2006-03-07 05:40:43 +0000416
417 // Get the node represented by this SUnit.
418 SDNode *N = CurNode->Node;
419 // If this is a pseudo op, like copyfromreg, look to see if there is a
420 // real target node flagged to it. If so, use the target node.
421 for (unsigned i = 0, e = CurNode->FlaggedNodes.size();
422 N->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
423 N = CurNode->FlaggedNodes[i];
424
Chris Lattner543832d2006-03-08 04:25:59 +0000425 HazardRecognizer::HazardType HT = HazardRec->getHazardType(N);
Chris Lattnere50c0922006-03-05 22:45:01 +0000426 if (HT == HazardRecognizer::NoHazard) {
Chris Lattner0c801bd2006-03-07 05:40:43 +0000427 FoundNode = CurNode;
Chris Lattnere50c0922006-03-05 22:45:01 +0000428 break;
429 }
430
431 // Remember if this is a noop hazard.
432 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
433
Chris Lattner0c801bd2006-03-07 05:40:43 +0000434 NotReady.push_back(CurNode);
Chris Lattner399bee22006-03-09 06:48:37 +0000435 } while (!PriorityQueue->empty());
Chris Lattnere50c0922006-03-05 22:45:01 +0000436
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000437 // Add the nodes that aren't ready back onto the available list.
Chris Lattner25e25562006-03-10 04:32:49 +0000438 PriorityQueue->push_all(NotReady);
439 NotReady.clear();
Chris Lattnere50c0922006-03-05 22:45:01 +0000440
441 // If we found a node to schedule, do it now.
442 if (FoundNode) {
Chris Lattner399bee22006-03-09 06:48:37 +0000443 ScheduleNodeTopDown(FoundNode);
Chris Lattner543832d2006-03-08 04:25:59 +0000444 HazardRec->EmitInstruction(FoundNode->Node);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000445 FoundNode->isScheduled = true;
446 PriorityQueue->ScheduledNode(FoundNode);
Chris Lattnere50c0922006-03-05 22:45:01 +0000447 } else if (!HasNoopHazards) {
448 // Otherwise, we have a pipeline stall, but no other problem, just advance
449 // the current cycle and try again.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000450 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000451 HazardRec->AdvanceCycle();
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000452 ++NumStalls;
Chris Lattnere50c0922006-03-05 22:45:01 +0000453 } else {
454 // Otherwise, we have no instructions to issue and we have instructions
455 // that will fault if we don't do this right. This is the case for
456 // processors without pipeline interlocks and other cases.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000457 DEBUG(std::cerr << "*** Emitting noop\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000458 HazardRec->EmitNoop();
Chris Lattner00b52ea2006-03-05 23:59:20 +0000459 Sequence.push_back(0); // NULL SUnit* -> noop
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000460 ++NumNoops;
Chris Lattnere50c0922006-03-05 22:45:01 +0000461 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000462 }
463
464#ifndef NDEBUG
465 // Verify that all SUnits were scheduled.
466 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000467 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
468 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000469 if (!AnyNotSched)
470 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000471 SUnits[i].dump(&DAG);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000472 std::cerr << "has not been scheduled!\n";
473 AnyNotSched = true;
474 }
475 }
476 assert(!AnyNotSched);
477#endif
478}
479
480
Evan Chengab495562006-01-25 09:14:32 +0000481void ScheduleDAGList::BuildSchedUnits() {
Chris Lattner42e20262006-03-08 04:54:34 +0000482 // Reserve entries in the vector for each of the SUnits we are creating. This
483 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
484 // invalidated.
Chris Lattner6f82fe82006-03-10 07:13:32 +0000485 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
Chris Lattner42e20262006-03-08 04:54:34 +0000486
Chris Lattnerd4130372006-03-09 07:15:18 +0000487 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
488
Chris Lattner6f82fe82006-03-10 07:13:32 +0000489 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
490 E = DAG.allnodes_end(); NI != E; ++NI) {
491 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
Evan Chengc4c339c2006-01-26 00:30:29 +0000492 continue;
Chris Lattner6f82fe82006-03-10 07:13:32 +0000493
494 // If this node has already been processed, stop now.
495 if (SUnitMap[NI]) continue;
496
497 SUnit *NodeSUnit = NewSUnit(NI);
Evan Chengab495562006-01-25 09:14:32 +0000498
Chris Lattner6f82fe82006-03-10 07:13:32 +0000499 // See if anything is flagged to this node, if so, add them to flagged
500 // nodes. Nodes can have at most one flag input and one flag output. Flags
501 // are required the be the last operand and result of a node.
502
503 // Scan up, adding flagged preds to FlaggedNodes.
504 SDNode *N = NI;
505 while (N->getNumOperands() &&
506 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
507 N = N->getOperand(N->getNumOperands()-1).Val;
508 NodeSUnit->FlaggedNodes.push_back(N);
509 SUnitMap[N] = NodeSUnit;
Evan Chengc4c339c2006-01-26 00:30:29 +0000510 }
Chris Lattner6f82fe82006-03-10 07:13:32 +0000511
512 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
513 // have a user of the flag operand.
514 N = NI;
515 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
516 SDOperand FlagVal(N, N->getNumValues()-1);
517
518 // There are either zero or one users of the Flag result.
519 bool HasFlagUse = false;
520 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
521 UI != E; ++UI)
522 if (FlagVal.isOperand(*UI)) {
523 HasFlagUse = true;
524 NodeSUnit->FlaggedNodes.push_back(N);
525 SUnitMap[N] = NodeSUnit;
526 N = *UI;
527 break;
528 }
529 if (!HasFlagUse) break;
530 }
531
532 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
533 // Update the SUnit
534 NodeSUnit->Node = N;
535 SUnitMap[N] = NodeSUnit;
536
Chris Lattnerd4130372006-03-09 07:15:18 +0000537 // Compute the latency for the node. We use the sum of the latencies for
538 // all nodes flagged together into this SUnit.
Chris Lattnerc6c9e652006-03-09 17:31:22 +0000539 if (InstrItins.isEmpty()) {
Chris Lattnerd4130372006-03-09 07:15:18 +0000540 // No latency information.
Chris Lattner6f82fe82006-03-10 07:13:32 +0000541 NodeSUnit->Latency = 1;
Chris Lattnerd4130372006-03-09 07:15:18 +0000542 } else {
Chris Lattner6f82fe82006-03-10 07:13:32 +0000543 NodeSUnit->Latency = 0;
Chris Lattnerd4130372006-03-09 07:15:18 +0000544 if (N->isTargetOpcode()) {
545 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
546 InstrStage *S = InstrItins.begin(SchedClass);
547 InstrStage *E = InstrItins.end(SchedClass);
548 for (; S != E; ++S)
Chris Lattner6f82fe82006-03-10 07:13:32 +0000549 NodeSUnit->Latency += S->Cycles;
Chris Lattnerd4130372006-03-09 07:15:18 +0000550 }
Chris Lattner6f82fe82006-03-10 07:13:32 +0000551 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
552 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
Chris Lattnerd4130372006-03-09 07:15:18 +0000553 if (FNode->isTargetOpcode()) {
554 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
555 InstrStage *S = InstrItins.begin(SchedClass);
556 InstrStage *E = InstrItins.end(SchedClass);
557 for (; S != E; ++S)
Chris Lattner6f82fe82006-03-10 07:13:32 +0000558 NodeSUnit->Latency += S->Cycles;
Chris Lattnerd4130372006-03-09 07:15:18 +0000559 }
560 }
561 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000562 }
Evan Chengab495562006-01-25 09:14:32 +0000563
Evan Chengc4c339c2006-01-26 00:30:29 +0000564 // Pass 2: add the preds, succs, etc.
Chris Lattner6f82fe82006-03-10 07:13:32 +0000565 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
566 SUnit *SU = &SUnits[su];
567 SDNode *MainNode = SU->Node;
Evan Cheng5e9a6952006-03-03 06:23:43 +0000568
Chris Lattner6f82fe82006-03-10 07:13:32 +0000569 if (MainNode->isTargetOpcode() &&
570 TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
Evan Cheng5e9a6952006-03-03 06:23:43 +0000571 SU->isTwoAddress = true;
Evan Chengc4c339c2006-01-26 00:30:29 +0000572
Chris Lattner6f82fe82006-03-10 07:13:32 +0000573 // Find all predecessors and successors of the group.
574 // Temporarily add N to make code simpler.
575 SU->FlaggedNodes.push_back(MainNode);
576
577 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
578 SDNode *N = SU->FlaggedNodes[n];
579
580 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
581 SDNode *OpN = N->getOperand(i).Val;
582 if (isPassiveNode(OpN)) continue; // Not scheduled.
583 SUnit *OpSU = SUnitMap[OpN];
584 assert(OpSU && "Node has no SUnit!");
585 if (OpSU == SU) continue; // In the same group.
586
587 MVT::ValueType OpVT = N->getOperand(i).getValueType();
588 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
589
590 if (OpVT == MVT::Other) {
591 if (SU->ChainPreds.insert(OpSU).second)
592 SU->NumChainPredsLeft++;
593 if (OpSU->ChainSuccs.insert(SU).second)
594 OpSU->NumChainSuccsLeft++;
595 } else {
596 if (SU->Preds.insert(OpSU).second)
597 SU->NumPredsLeft++;
598 if (OpSU->Succs.insert(SU).second)
599 OpSU->NumSuccsLeft++;
Evan Chengc4c339c2006-01-26 00:30:29 +0000600 }
601 }
Evan Chengab495562006-01-25 09:14:32 +0000602 }
Chris Lattnerd4130372006-03-09 07:15:18 +0000603
Chris Lattner6f82fe82006-03-10 07:13:32 +0000604 // Remove MainNode from FlaggedNodes again.
605 SU->FlaggedNodes.pop_back();
606
Chris Lattnerd4130372006-03-09 07:15:18 +0000607 DEBUG(SU->dumpAll(&DAG));
Evan Chengab495562006-01-25 09:14:32 +0000608 }
Evan Chengab495562006-01-25 09:14:32 +0000609}
610
611/// EmitSchedule - Emit the machine code in scheduled order.
612void ScheduleDAGList::EmitSchedule() {
Chris Lattnerb9d8fa02006-03-10 07:25:12 +0000613 std::map<SDNode*, unsigned> VRBaseMap;
Evan Chengab495562006-01-25 09:14:32 +0000614 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
Chris Lattner2d945ba2006-03-05 23:51:47 +0000615 if (SUnit *SU = Sequence[i]) {
Chris Lattnerdc2f1352006-03-10 07:28:36 +0000616 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
617 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
618 EmitNode(SU->Node, VRBaseMap);
Chris Lattner2d945ba2006-03-05 23:51:47 +0000619 } else {
620 // Null SUnit* is a noop.
621 EmitNoop();
Evan Chengab495562006-01-25 09:14:32 +0000622 }
Evan Chengab495562006-01-25 09:14:32 +0000623 }
624}
625
626/// dump - dump the schedule.
Chris Lattnerd4130372006-03-09 07:15:18 +0000627void ScheduleDAGList::dumpSchedule() const {
Evan Chengab495562006-01-25 09:14:32 +0000628 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
Chris Lattner2d945ba2006-03-05 23:51:47 +0000629 if (SUnit *SU = Sequence[i])
Chris Lattnerd4130372006-03-09 07:15:18 +0000630 SU->dump(&DAG);
Chris Lattner2d945ba2006-03-05 23:51:47 +0000631 else
632 std::cerr << "**** NOOP ****\n";
Evan Chengab495562006-01-25 09:14:32 +0000633 }
634}
635
636/// Schedule - Schedule the DAG using list scheduling.
637/// FIXME: Right now it only supports the burr (bottom up register reducing)
638/// heuristic.
Evan Cheng31272342006-01-23 08:26:10 +0000639void ScheduleDAGList::Schedule() {
Evan Chengab495562006-01-25 09:14:32 +0000640 DEBUG(std::cerr << "********** List Scheduling **********\n");
641
642 // Build scheduling units.
643 BuildSchedUnits();
Chris Lattnerfd22d422006-03-08 05:18:27 +0000644
Chris Lattner9df64752006-03-09 06:35:14 +0000645 PriorityQueue->initNodes(SUnits);
646
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000647 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
648 if (isBottomUp)
Chris Lattner399bee22006-03-09 06:48:37 +0000649 ListScheduleBottomUp();
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000650 else
Chris Lattner399bee22006-03-09 06:48:37 +0000651 ListScheduleTopDown();
Chris Lattner9df64752006-03-09 06:35:14 +0000652
653 PriorityQueue->releaseState();
654
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000655 DEBUG(std::cerr << "*** Final schedule ***\n");
Chris Lattnerd4130372006-03-09 07:15:18 +0000656 DEBUG(dumpSchedule());
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000657 DEBUG(std::cerr << "\n");
658
Evan Chengab495562006-01-25 09:14:32 +0000659 // Emit in scheduled order
660 EmitSchedule();
Evan Cheng31272342006-01-23 08:26:10 +0000661}
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000662
Chris Lattner9df64752006-03-09 06:35:14 +0000663//===----------------------------------------------------------------------===//
664// RegReductionPriorityQueue Implementation
665//===----------------------------------------------------------------------===//
666//
667// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
668// to reduce register pressure.
669//
670namespace {
671 class RegReductionPriorityQueue;
672
673 /// Sorting functions for the Available queue.
674 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
675 RegReductionPriorityQueue *SPQ;
676 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
677 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
678
679 bool operator()(const SUnit* left, const SUnit* right) const;
680 };
681} // end anonymous namespace
682
683namespace {
684 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
685 // SUnits - The SUnits for the current graph.
686 const std::vector<SUnit> *SUnits;
687
688 // SethiUllmanNumbers - The SethiUllman number for each node.
689 std::vector<int> SethiUllmanNumbers;
690
691 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
692 public:
693 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
694 }
695
696 void initNodes(const std::vector<SUnit> &sunits) {
697 SUnits = &sunits;
698 // Calculate node priorities.
699 CalculatePriorities();
700 }
701 void releaseState() {
702 SUnits = 0;
703 SethiUllmanNumbers.clear();
704 }
705
706 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
707 assert(NodeNum < SethiUllmanNumbers.size());
708 return SethiUllmanNumbers[NodeNum];
709 }
710
711 bool empty() const { return Queue.empty(); }
712
713 void push(SUnit *U) {
714 Queue.push(U);
715 }
Chris Lattner25e25562006-03-10 04:32:49 +0000716 void push_all(const std::vector<SUnit *> &Nodes) {
717 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
718 Queue.push(Nodes[i]);
719 }
720
Chris Lattner9df64752006-03-09 06:35:14 +0000721 SUnit *pop() {
722 SUnit *V = Queue.top();
723 Queue.pop();
724 return V;
725 }
726 private:
727 void CalculatePriorities();
728 int CalcNodePriority(const SUnit *SU);
729 };
730}
731
732bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
733 unsigned LeftNum = left->NodeNum;
734 unsigned RightNum = right->NodeNum;
735
736 int LBonus = (int)left ->isDefNUseOperand;
737 int RBonus = (int)right->isDefNUseOperand;
738
739 // Special tie breaker: if two nodes share a operand, the one that
740 // use it as a def&use operand is preferred.
741 if (left->isTwoAddress && !right->isTwoAddress) {
742 SDNode *DUNode = left->Node->getOperand(0).Val;
743 if (DUNode->isOperand(right->Node))
744 LBonus++;
745 }
746 if (!left->isTwoAddress && right->isTwoAddress) {
747 SDNode *DUNode = right->Node->getOperand(0).Val;
748 if (DUNode->isOperand(left->Node))
749 RBonus++;
750 }
751
752 // Priority1 is just the number of live range genned.
753 int LPriority1 = left ->NumPredsLeft - LBonus;
754 int RPriority1 = right->NumPredsLeft - RBonus;
755 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
756 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
757
758 if (LPriority1 > RPriority1)
759 return true;
760 else if (LPriority1 == RPriority1)
761 if (LPriority2 < RPriority2)
762 return true;
763 else if (LPriority2 == RPriority2)
764 if (left->CycleBound > right->CycleBound)
765 return true;
766
767 return false;
768}
769
770
771/// CalcNodePriority - Priority is the Sethi Ullman number.
772/// Smaller number is the higher priority.
773int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
774 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
775 if (SethiUllmanNumber != INT_MIN)
776 return SethiUllmanNumber;
777
778 if (SU->Preds.size() == 0) {
779 SethiUllmanNumber = 1;
780 } else {
781 int Extra = 0;
Jeff Cohen6ce97682006-03-10 03:57:45 +0000782 for (std::set<SUnit*>::const_iterator I = SU->Preds.begin(),
Chris Lattner9df64752006-03-09 06:35:14 +0000783 E = SU->Preds.end(); I != E; ++I) {
784 SUnit *PredSU = *I;
785 int PredSethiUllman = CalcNodePriority(PredSU);
786 if (PredSethiUllman > SethiUllmanNumber) {
787 SethiUllmanNumber = PredSethiUllman;
788 Extra = 0;
789 } else if (PredSethiUllman == SethiUllmanNumber)
790 Extra++;
791 }
792
793 if (SU->Node->getOpcode() != ISD::TokenFactor)
794 SethiUllmanNumber += Extra;
795 else
796 SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
797 }
798
799 return SethiUllmanNumber;
800}
801
802/// CalculatePriorities - Calculate priorities of all scheduling units.
803void RegReductionPriorityQueue::CalculatePriorities() {
804 SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
805
806 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
807 CalcNodePriority(&(*SUnits)[i]);
808}
809
Chris Lattner6398c132006-03-09 07:38:27 +0000810//===----------------------------------------------------------------------===//
811// LatencyPriorityQueue Implementation
812//===----------------------------------------------------------------------===//
813//
814// This is a SchedulingPriorityQueue that schedules using latency information to
815// reduce the length of the critical path through the basic block.
816//
817namespace {
818 class LatencyPriorityQueue;
819
820 /// Sorting functions for the Available queue.
821 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
822 LatencyPriorityQueue *PQ;
823 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
824 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
825
826 bool operator()(const SUnit* left, const SUnit* right) const;
827 };
828} // end anonymous namespace
829
830namespace {
831 class LatencyPriorityQueue : public SchedulingPriorityQueue {
832 // SUnits - The SUnits for the current graph.
833 const std::vector<SUnit> *SUnits;
834
835 // Latencies - The latency (max of latency from this node to the bb exit)
836 // for each node.
837 std::vector<int> Latencies;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000838
839 /// NumNodesSolelyBlocking - This vector contains, for every node in the
840 /// Queue, the number of nodes that the node is the sole unscheduled
841 /// predecessor for. This is used as a tie-breaker heuristic for better
842 /// mobility.
843 std::vector<unsigned> NumNodesSolelyBlocking;
844
Chris Lattner6398c132006-03-09 07:38:27 +0000845 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
846public:
847 LatencyPriorityQueue() : Queue(latency_sort(this)) {
848 }
849
850 void initNodes(const std::vector<SUnit> &sunits) {
851 SUnits = &sunits;
852 // Calculate node priorities.
853 CalculatePriorities();
854 }
855 void releaseState() {
856 SUnits = 0;
857 Latencies.clear();
858 }
859
860 unsigned getLatency(unsigned NodeNum) const {
861 assert(NodeNum < Latencies.size());
862 return Latencies[NodeNum];
863 }
864
Chris Lattner349e9dd2006-03-10 05:51:05 +0000865 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
866 assert(NodeNum < NumNodesSolelyBlocking.size());
867 return NumNodesSolelyBlocking[NodeNum];
868 }
869
Chris Lattner6398c132006-03-09 07:38:27 +0000870 bool empty() const { return Queue.empty(); }
871
Chris Lattner349e9dd2006-03-10 05:51:05 +0000872 virtual void push(SUnit *U) {
873 push_impl(U);
Chris Lattner6398c132006-03-09 07:38:27 +0000874 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000875 void push_impl(SUnit *U);
876
Chris Lattner25e25562006-03-10 04:32:49 +0000877 void push_all(const std::vector<SUnit *> &Nodes) {
878 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner349e9dd2006-03-10 05:51:05 +0000879 push_impl(Nodes[i]);
Chris Lattner25e25562006-03-10 04:32:49 +0000880 }
881
Chris Lattner6398c132006-03-09 07:38:27 +0000882 SUnit *pop() {
883 SUnit *V = Queue.top();
884 Queue.pop();
Chris Lattner6398c132006-03-09 07:38:27 +0000885 return V;
886 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000887
888 // ScheduledNode - As nodes are scheduled, we look to see if there are any
889 // successor nodes that have a single unscheduled predecessor. If so, that
890 // single predecessor has a higher priority, since scheduling it will make
891 // the node available.
892 void ScheduledNode(SUnit *Node);
893
Chris Lattner6398c132006-03-09 07:38:27 +0000894private:
895 void CalculatePriorities();
896 int CalcLatency(const SUnit &SU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000897 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
898
899 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
900 /// node from a priority queue. We should roll our own heap to make this
901 /// better or something.
902 void RemoveFromPriorityQueue(SUnit *SU) {
903 std::vector<SUnit*> Temp;
904
905 assert(!Queue.empty() && "Not in queue!");
906 while (Queue.top() != SU) {
907 Temp.push_back(Queue.top());
908 Queue.pop();
909 assert(!Queue.empty() && "Not in queue!");
910 }
911
912 // Remove the node from the PQ.
913 Queue.pop();
914
915 // Add all the other nodes back.
916 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
917 Queue.push(Temp[i]);
918 }
Chris Lattner6398c132006-03-09 07:38:27 +0000919 };
920}
921
922bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
923 unsigned LHSNum = LHS->NodeNum;
924 unsigned RHSNum = RHS->NodeNum;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000925
926 // The most important heuristic is scheduling the critical path.
927 unsigned LHSLatency = PQ->getLatency(LHSNum);
928 unsigned RHSLatency = PQ->getLatency(RHSNum);
929 if (LHSLatency < RHSLatency) return true;
930 if (LHSLatency > RHSLatency) return false;
Chris Lattner6398c132006-03-09 07:38:27 +0000931
Chris Lattner349e9dd2006-03-10 05:51:05 +0000932 // After that, if two nodes have identical latencies, look to see if one will
933 // unblock more other nodes than the other.
934 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
935 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
936 if (LHSBlocked < RHSBlocked) return true;
937 if (LHSBlocked > RHSBlocked) return false;
938
939 // Finally, just to provide a stable ordering, use the node number as a
940 // deciding factor.
941 return LHSNum < RHSNum;
Chris Lattner6398c132006-03-09 07:38:27 +0000942}
943
944
945/// CalcNodePriority - Calculate the maximal path from the node to the exit.
946///
947int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
948 int &Latency = Latencies[SU.NodeNum];
949 if (Latency != -1)
950 return Latency;
951
952 int MaxSuccLatency = 0;
Jeff Cohen6ce97682006-03-10 03:57:45 +0000953 for (std::set<SUnit*>::const_iterator I = SU.Succs.begin(),
Chris Lattner6398c132006-03-09 07:38:27 +0000954 E = SU.Succs.end(); I != E; ++I)
955 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(**I));
956
Jeff Cohen6ce97682006-03-10 03:57:45 +0000957 for (std::set<SUnit*>::const_iterator I = SU.ChainSuccs.begin(),
Chris Lattner6398c132006-03-09 07:38:27 +0000958 E = SU.ChainSuccs.end(); I != E; ++I)
959 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(**I));
960
961 return Latency = MaxSuccLatency + SU.Latency;
962}
963
964/// CalculatePriorities - Calculate priorities of all scheduling units.
965void LatencyPriorityQueue::CalculatePriorities() {
966 Latencies.assign(SUnits->size(), -1);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000967 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
Chris Lattner6398c132006-03-09 07:38:27 +0000968
969 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
970 CalcLatency((*SUnits)[i]);
971}
972
Chris Lattner349e9dd2006-03-10 05:51:05 +0000973/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
974/// of SU, return it, otherwise return null.
975static SUnit *getSingleUnscheduledPred(SUnit *SU) {
976 SUnit *OnlyAvailablePred = 0;
977 for (std::set<SUnit*>::const_iterator I = SU->Preds.begin(),
978 E = SU->Preds.end(); I != E; ++I)
979 if (!(*I)->isScheduled) {
980 // We found an available, but not scheduled, predecessor. If it's the
981 // only one we have found, keep track of it... otherwise give up.
982 if (OnlyAvailablePred && OnlyAvailablePred != *I)
983 return 0;
984 OnlyAvailablePred = *I;
985 }
986
987 for (std::set<SUnit*>::const_iterator I = SU->ChainSuccs.begin(),
988 E = SU->ChainSuccs.end(); I != E; ++I)
989 if (!(*I)->isScheduled) {
990 // We found an available, but not scheduled, predecessor. If it's the
991 // only one we have found, keep track of it... otherwise give up.
992 if (OnlyAvailablePred && OnlyAvailablePred != *I)
993 return 0;
994 OnlyAvailablePred = *I;
995 }
996
997 return OnlyAvailablePred;
998}
999
1000void LatencyPriorityQueue::push_impl(SUnit *SU) {
1001 // Look at all of the successors of this node. Count the number of nodes that
1002 // this node is the sole unscheduled node for.
1003 unsigned NumNodesBlocking = 0;
1004 for (std::set<SUnit*>::const_iterator I = SU->Succs.begin(),
1005 E = SU->Succs.end(); I != E; ++I)
1006 if (getSingleUnscheduledPred(*I) == SU)
1007 ++NumNodesBlocking;
1008
1009 for (std::set<SUnit*>::const_iterator I = SU->ChainSuccs.begin(),
1010 E = SU->ChainSuccs.end(); I != E; ++I)
1011 if (getSingleUnscheduledPred(*I) == SU)
1012 ++NumNodesBlocking;
1013
1014 Queue.push(SU);
1015}
1016
1017
1018// ScheduledNode - As nodes are scheduled, we look to see if there are any
1019// successor nodes that have a single unscheduled predecessor. If so, that
1020// single predecessor has a higher priority, since scheduling it will make
1021// the node available.
1022void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
1023 for (std::set<SUnit*>::const_iterator I = SU->Succs.begin(),
1024 E = SU->Succs.end(); I != E; ++I)
1025 AdjustPriorityOfUnscheduledPreds(*I);
1026
1027 for (std::set<SUnit*>::const_iterator I = SU->ChainSuccs.begin(),
1028 E = SU->ChainSuccs.end(); I != E; ++I)
1029 AdjustPriorityOfUnscheduledPreds(*I);
1030}
1031
1032/// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1033/// scheduled. If SU is not itself available, then there is at least one
1034/// predecessor node that has not been scheduled yet. If SU has exactly ONE
1035/// unscheduled predecessor, we want to increase its priority: it getting
1036/// scheduled will make this node available, so it is better than some other
1037/// node of the same priority that will not make a node available.
1038void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1039 if (SU->isAvailable) return; // All preds scheduled.
1040
1041 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1042 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1043
1044 // Okay, we found a single predecessor that is available, but not scheduled.
1045 // Since it is available, it must be in the priority queue. First remove it.
1046 RemoveFromPriorityQueue(OnlyAvailablePred);
1047
1048 // Reinsert the node into the priority queue, which recomputes its
1049 // NumNodesSolelyBlocking value.
1050 push(OnlyAvailablePred);
1051}
1052
Chris Lattner9df64752006-03-09 06:35:14 +00001053
1054//===----------------------------------------------------------------------===//
1055// Public Constructor Functions
1056//===----------------------------------------------------------------------===//
1057
Evan Chengab495562006-01-25 09:14:32 +00001058llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1059 MachineBasicBlock *BB) {
Chris Lattner543832d2006-03-08 04:25:59 +00001060 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
Chris Lattner9df64752006-03-09 06:35:14 +00001061 new RegReductionPriorityQueue(),
Chris Lattner543832d2006-03-08 04:25:59 +00001062 new HazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00001063}
1064
Chris Lattner47639db2006-03-06 00:22:00 +00001065/// createTDListDAGScheduler - This creates a top-down list scheduler with the
1066/// specified hazard recognizer.
1067ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1068 MachineBasicBlock *BB,
Chris Lattner543832d2006-03-08 04:25:59 +00001069 HazardRecognizer *HR) {
Chris Lattner9df64752006-03-09 06:35:14 +00001070 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
Chris Lattner6398c132006-03-09 07:38:27 +00001071 new LatencyPriorityQueue(),
Chris Lattner9df64752006-03-09 06:35:14 +00001072 HR);
Evan Cheng31272342006-01-23 08:26:10 +00001073}