blob: f3d97fe18c5521353417be159eaee37ed3c1387d [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 Lattner572003c2006-03-12 00:38:57 +000056 bool isPending : 1; // True once pending.
Chris Lattner349e9dd2006-03-10 05:51:05 +000057 bool isAvailable : 1; // True once available.
58 bool isScheduled : 1; // True once scheduled.
Chris Lattner12c6d892006-03-08 04:41:06 +000059 unsigned short Latency; // Node latency.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000060 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
Chris Lattner356183d2006-03-11 22:44:37 +000061 unsigned Cycle; // Once scheduled, the cycle of the op.
Chris Lattnerfd22d422006-03-08 05:18:27 +000062 unsigned NodeNum; // Entry # of node in the node vector.
Chris Lattneraf5e26c2006-03-08 04:37:58 +000063
Chris Lattnerfd22d422006-03-08 05:18:27 +000064 SUnit(SDNode *node, unsigned nodenum)
Chris Lattneraf5e26c2006-03-08 04:37:58 +000065 : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
Evan Cheng4e3904f2006-03-02 21:38:29 +000066 NumChainPredsLeft(0), NumChainSuccsLeft(0),
Evan Cheng5e9a6952006-03-03 06:23:43 +000067 isTwoAddress(false), isDefNUseOperand(false),
Chris Lattner572003c2006-03-12 00:38:57 +000068 isPending(false), isAvailable(false), isScheduled(false),
Chris Lattner356183d2006-03-11 22:44:37 +000069 Latency(0), CycleBound(0), Cycle(0), NodeNum(nodenum) {}
Chris Lattneraf5e26c2006-03-08 04:37:58 +000070
Chris Lattnerd4130372006-03-09 07:15:18 +000071 void dump(const SelectionDAG *G) const;
72 void dumpAll(const SelectionDAG *G) const;
Chris Lattneraf5e26c2006-03-08 04:37:58 +000073 };
74}
Evan Chengab495562006-01-25 09:14:32 +000075
Chris Lattnerd4130372006-03-09 07:15:18 +000076void SUnit::dump(const SelectionDAG *G) const {
Evan Chengc4c339c2006-01-26 00:30:29 +000077 std::cerr << "SU: ";
Evan Chengab495562006-01-25 09:14:32 +000078 Node->dump(G);
79 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +000080 if (FlaggedNodes.size() != 0) {
Evan Chengab495562006-01-25 09:14:32 +000081 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
Evan Chengc4c339c2006-01-26 00:30:29 +000082 std::cerr << " ";
Evan Chengab495562006-01-25 09:14:32 +000083 FlaggedNodes[i]->dump(G);
84 std::cerr << "\n";
85 }
86 }
Chris Lattnerd4130372006-03-09 07:15:18 +000087}
Evan Chengab495562006-01-25 09:14:32 +000088
Chris Lattnerd4130372006-03-09 07:15:18 +000089void SUnit::dumpAll(const SelectionDAG *G) const {
90 dump(G);
Evan Chengc4c339c2006-01-26 00:30:29 +000091
Chris Lattnerd4130372006-03-09 07:15:18 +000092 std::cerr << " # preds left : " << NumPredsLeft << "\n";
93 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
94 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
95 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
96 std::cerr << " Latency : " << Latency << "\n";
97
98 if (Preds.size() != 0) {
99 std::cerr << " Predecessors:\n";
Chris Lattner578d8fc2006-03-11 22:24:20 +0000100 for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
Chris Lattnerd4130372006-03-09 07:15:18 +0000101 E = Preds.end(); I != E; ++I) {
Chris Lattner578d8fc2006-03-11 22:24:20 +0000102 if (I->second)
103 std::cerr << " ch ";
104 else
105 std::cerr << " val ";
106 I->first->dump(G);
Chris Lattnerd4130372006-03-09 07:15:18 +0000107 }
108 }
109 if (Succs.size() != 0) {
110 std::cerr << " Successors:\n";
Chris Lattner578d8fc2006-03-11 22:24:20 +0000111 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
Chris Lattnerd4130372006-03-09 07:15:18 +0000112 E = Succs.end(); I != E; ++I) {
Chris Lattner578d8fc2006-03-11 22:24:20 +0000113 if (I->second)
114 std::cerr << " ch ";
115 else
116 std::cerr << " val ";
117 I->first->dump(G);
Chris Lattnerd4130372006-03-09 07:15:18 +0000118 }
119 }
120 std::cerr << "\n";
Evan Chengab495562006-01-25 09:14:32 +0000121}
122
Chris Lattner9df64752006-03-09 06:35:14 +0000123//===----------------------------------------------------------------------===//
Chris Lattner9e95acc2006-03-09 06:37:29 +0000124/// SchedulingPriorityQueue - This interface is used to plug different
125/// priorities computation algorithms into the list scheduler. It implements the
126/// interface of a standard priority queue, where nodes are inserted in
127/// arbitrary order and returned in priority order. The computation of the
128/// priority and the representation of the queue are totally up to the
129/// implementation to decide.
130///
131namespace {
Chris Lattner9df64752006-03-09 06:35:14 +0000132class SchedulingPriorityQueue {
133public:
134 virtual ~SchedulingPriorityQueue() {}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000135
Chris Lattner9df64752006-03-09 06:35:14 +0000136 virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
137 virtual void releaseState() = 0;
Chris Lattnerfd22d422006-03-08 05:18:27 +0000138
Chris Lattner9df64752006-03-09 06:35:14 +0000139 virtual bool empty() const = 0;
140 virtual void push(SUnit *U) = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000141
142 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
Chris Lattner9df64752006-03-09 06:35:14 +0000143 virtual SUnit *pop() = 0;
Chris Lattner25e25562006-03-10 04:32:49 +0000144
145 /// ScheduledNode - As each node is scheduled, this method is invoked. This
146 /// allows the priority function to adjust the priority of node that have
147 /// already been emitted.
148 virtual void ScheduledNode(SUnit *Node) {}
Chris Lattner9df64752006-03-09 06:35:14 +0000149};
Chris Lattner9e95acc2006-03-09 06:37:29 +0000150}
Chris Lattnerfd22d422006-03-08 05:18:27 +0000151
152
Chris Lattnere50c0922006-03-05 22:45:01 +0000153
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000154namespace {
Chris Lattner9e95acc2006-03-09 06:37:29 +0000155//===----------------------------------------------------------------------===//
156/// ScheduleDAGList - The actual list scheduler implementation. This supports
157/// both top-down and bottom-up scheduling.
158///
Evan Cheng31272342006-01-23 08:26:10 +0000159class ScheduleDAGList : public ScheduleDAG {
160private:
Evan Chengab495562006-01-25 09:14:32 +0000161 // SDNode to SUnit mapping (many to one).
162 std::map<SDNode*, SUnit*> SUnitMap;
Chris Lattner00b52ea2006-03-05 23:59:20 +0000163 // The schedule. Null SUnit*'s represent noop instructions.
Evan Chengab495562006-01-25 09:14:32 +0000164 std::vector<SUnit*> Sequence;
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 Lattner356183d2006-03-11 22:44:37 +0000173 /// AvailableQueue - The priority queue to use for the available SUnits.
174 ///
175 SchedulingPriorityQueue *AvailableQueue;
Chris Lattner9df64752006-03-09 06:35:14 +0000176
Chris Lattner572003c2006-03-12 00:38:57 +0000177 /// PendingQueue - This contains all of the instructions whose operands have
178 /// been issued, but their results are not ready yet (due to the latency of
179 /// the operation). Once the operands becomes available, the instruction is
180 /// added to the AvailableQueue. This keeps track of each SUnit and the
181 /// number of cycles left to execute before the operation is available.
182 std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
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 Lattner356183d2006-03-11 22:44:37 +0000190 SchedulingPriorityQueue *availqueue,
Chris Lattner543832d2006-03-08 04:25:59 +0000191 HazardRecognizer *HR)
Chris Lattner063086b2006-03-11 22:34:41 +0000192 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
Chris Lattner356183d2006-03-11 22:44:37 +0000193 AvailableQueue(availqueue), HazardRec(HR) {
Chris Lattnere50c0922006-03-05 22:45:01 +0000194 }
Evan Chengab495562006-01-25 09:14:32 +0000195
196 ~ScheduleDAGList() {
Chris Lattner543832d2006-03-08 04:25:59 +0000197 delete HazardRec;
Chris Lattner356183d2006-03-11 22:44:37 +0000198 delete AvailableQueue;
Evan Chengab495562006-01-25 09:14:32 +0000199 }
Evan Cheng31272342006-01-23 08:26:10 +0000200
201 void Schedule();
Evan Cheng31272342006-01-23 08:26:10 +0000202
Chris Lattnerd4130372006-03-09 07:15:18 +0000203 void dumpSchedule() const;
Evan Chengab495562006-01-25 09:14:32 +0000204
205private:
Evan Chengc4c339c2006-01-26 00:30:29 +0000206 SUnit *NewSUnit(SDNode *N);
Chris Lattner063086b2006-03-11 22:34:41 +0000207 void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
Chris Lattner572003c2006-03-12 00:38:57 +0000208 void ReleaseSucc(SUnit *SuccSU, bool isChain);
Chris Lattner063086b2006-03-11 22:34:41 +0000209 void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
210 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
Chris Lattner399bee22006-03-09 06:48:37 +0000211 void ListScheduleTopDown();
212 void ListScheduleBottomUp();
Evan Chengab495562006-01-25 09:14:32 +0000213 void BuildSchedUnits();
214 void EmitSchedule();
215};
Chris Lattneraf5e26c2006-03-08 04:37:58 +0000216} // end anonymous namespace
Evan Chengab495562006-01-25 09:14:32 +0000217
Chris Lattner47639db2006-03-06 00:22:00 +0000218HazardRecognizer::~HazardRecognizer() {}
219
Evan Chengc4c339c2006-01-26 00:30:29 +0000220
221/// NewSUnit - Creates a new SUnit and return a ptr to it.
222SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
Chris Lattnerfd22d422006-03-08 05:18:27 +0000223 SUnits.push_back(SUnit(N, SUnits.size()));
Chris Lattner42e20262006-03-08 04:54:34 +0000224 return &SUnits.back();
Evan Chengc4c339c2006-01-26 00:30:29 +0000225}
226
Chris Lattner9995a0c2006-03-11 22:28:35 +0000227/// BuildSchedUnits - Build SUnits from the selection dag that we are input.
228/// This SUnit graph is similar to the SelectionDAG, but represents flagged
229/// together nodes with a single SUnit.
230void ScheduleDAGList::BuildSchedUnits() {
231 // Reserve entries in the vector for each of the SUnits we are creating. This
232 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
233 // invalidated.
234 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
235
236 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
237
238 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
239 E = DAG.allnodes_end(); NI != E; ++NI) {
240 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
241 continue;
242
243 // If this node has already been processed, stop now.
244 if (SUnitMap[NI]) continue;
245
246 SUnit *NodeSUnit = NewSUnit(NI);
247
248 // See if anything is flagged to this node, if so, add them to flagged
249 // nodes. Nodes can have at most one flag input and one flag output. Flags
250 // are required the be the last operand and result of a node.
251
252 // Scan up, adding flagged preds to FlaggedNodes.
253 SDNode *N = NI;
254 while (N->getNumOperands() &&
255 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
256 N = N->getOperand(N->getNumOperands()-1).Val;
257 NodeSUnit->FlaggedNodes.push_back(N);
258 SUnitMap[N] = NodeSUnit;
259 }
260
261 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
262 // have a user of the flag operand.
263 N = NI;
264 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
265 SDOperand FlagVal(N, N->getNumValues()-1);
266
267 // There are either zero or one users of the Flag result.
268 bool HasFlagUse = false;
269 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
270 UI != E; ++UI)
271 if (FlagVal.isOperand(*UI)) {
272 HasFlagUse = true;
273 NodeSUnit->FlaggedNodes.push_back(N);
274 SUnitMap[N] = NodeSUnit;
275 N = *UI;
276 break;
277 }
278 if (!HasFlagUse) break;
279 }
280
281 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
282 // Update the SUnit
283 NodeSUnit->Node = N;
284 SUnitMap[N] = NodeSUnit;
285
286 // Compute the latency for the node. We use the sum of the latencies for
287 // all nodes flagged together into this SUnit.
288 if (InstrItins.isEmpty()) {
289 // No latency information.
290 NodeSUnit->Latency = 1;
291 } else {
292 NodeSUnit->Latency = 0;
293 if (N->isTargetOpcode()) {
294 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
295 InstrStage *S = InstrItins.begin(SchedClass);
296 InstrStage *E = InstrItins.end(SchedClass);
297 for (; S != E; ++S)
298 NodeSUnit->Latency += S->Cycles;
299 }
300 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
301 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
302 if (FNode->isTargetOpcode()) {
303 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
304 InstrStage *S = InstrItins.begin(SchedClass);
305 InstrStage *E = InstrItins.end(SchedClass);
306 for (; S != E; ++S)
307 NodeSUnit->Latency += S->Cycles;
308 }
309 }
310 }
311 }
312
313 // Pass 2: add the preds, succs, etc.
314 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
315 SUnit *SU = &SUnits[su];
316 SDNode *MainNode = SU->Node;
317
318 if (MainNode->isTargetOpcode() &&
319 TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
320 SU->isTwoAddress = true;
321
322 // Find all predecessors and successors of the group.
323 // Temporarily add N to make code simpler.
324 SU->FlaggedNodes.push_back(MainNode);
325
326 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
327 SDNode *N = SU->FlaggedNodes[n];
328
329 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
330 SDNode *OpN = N->getOperand(i).Val;
331 if (isPassiveNode(OpN)) continue; // Not scheduled.
332 SUnit *OpSU = SUnitMap[OpN];
333 assert(OpSU && "Node has no SUnit!");
334 if (OpSU == SU) continue; // In the same group.
335
336 MVT::ValueType OpVT = N->getOperand(i).getValueType();
337 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
338 bool isChain = OpVT == MVT::Other;
339
340 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
341 if (!isChain) {
342 SU->NumPredsLeft++;
343 } else {
344 SU->NumChainPredsLeft++;
345 }
346 }
347 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
348 if (!isChain) {
349 OpSU->NumSuccsLeft++;
350 } else {
351 OpSU->NumChainSuccsLeft++;
352 }
353 }
354 }
355 }
356
357 // Remove MainNode from FlaggedNodes again.
358 SU->FlaggedNodes.pop_back();
359 }
360 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
361 SUnits[su].dumpAll(&DAG));
362}
363
364/// EmitSchedule - Emit the machine code in scheduled order.
365void ScheduleDAGList::EmitSchedule() {
366 std::map<SDNode*, unsigned> VRBaseMap;
367 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
368 if (SUnit *SU = Sequence[i]) {
369 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
370 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
371 EmitNode(SU->Node, VRBaseMap);
372 } else {
373 // Null SUnit* is a noop.
374 EmitNoop();
375 }
376 }
377}
378
379/// dump - dump the schedule.
380void ScheduleDAGList::dumpSchedule() const {
381 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
382 if (SUnit *SU = Sequence[i])
383 SU->dump(&DAG);
384 else
385 std::cerr << "**** NOOP ****\n";
386 }
387}
388
389/// Schedule - Schedule the DAG using list scheduling.
Chris Lattner9995a0c2006-03-11 22:28:35 +0000390void ScheduleDAGList::Schedule() {
391 DEBUG(std::cerr << "********** List Scheduling **********\n");
392
393 // Build scheduling units.
394 BuildSchedUnits();
395
Chris Lattner356183d2006-03-11 22:44:37 +0000396 AvailableQueue->initNodes(SUnits);
Chris Lattner9995a0c2006-03-11 22:28:35 +0000397
398 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
399 if (isBottomUp)
400 ListScheduleBottomUp();
401 else
402 ListScheduleTopDown();
403
Chris Lattner356183d2006-03-11 22:44:37 +0000404 AvailableQueue->releaseState();
Chris Lattner9995a0c2006-03-11 22:28:35 +0000405
406 DEBUG(std::cerr << "*** Final schedule ***\n");
407 DEBUG(dumpSchedule());
408 DEBUG(std::cerr << "\n");
409
410 // Emit in scheduled order
411 EmitSchedule();
412}
413
414//===----------------------------------------------------------------------===//
415// Bottom-Up Scheduling
416//===----------------------------------------------------------------------===//
417
Evan Chengc4c339c2006-01-26 00:30:29 +0000418/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
419/// the Available queue is the count reaches zero. Also update its cycle bound.
Chris Lattner063086b2006-03-11 22:34:41 +0000420void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain,
Chris Lattner356183d2006-03-11 22:44:37 +0000421 unsigned CurCycle) {
Evan Cheng4e3904f2006-03-02 21:38:29 +0000422 // FIXME: the distance between two nodes is not always == the predecessor's
423 // latency. For example, the reader can very well read the register written
424 // by the predecessor later than the issue cycle. It also depends on the
425 // interrupt model (drain vs. freeze).
Chris Lattner356183d2006-03-11 22:44:37 +0000426 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
Evan Cheng4e3904f2006-03-02 21:38:29 +0000427
Evan Chengc5c06582006-03-06 06:08:54 +0000428 if (!isChain)
Evan Cheng4e3904f2006-03-02 21:38:29 +0000429 PredSU->NumSuccsLeft--;
Evan Chengc5c06582006-03-06 06:08:54 +0000430 else
Evan Cheng4e3904f2006-03-02 21:38:29 +0000431 PredSU->NumChainSuccsLeft--;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000432
Evan Chengab495562006-01-25 09:14:32 +0000433#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000434 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
Evan Chengab495562006-01-25 09:14:32 +0000435 std::cerr << "*** List scheduling failed! ***\n";
436 PredSU->dump(&DAG);
437 std::cerr << " has been released too many times!\n";
438 assert(0);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000439 }
Evan Chengab495562006-01-25 09:14:32 +0000440#endif
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000441
442 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
443 // EntryToken has to go last! Special case it here.
Chris Lattner349e9dd2006-03-10 05:51:05 +0000444 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
445 PredSU->isAvailable = true;
Chris Lattner356183d2006-03-11 22:44:37 +0000446 AvailableQueue->push(PredSU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000447 }
Evan Chengab495562006-01-25 09:14:32 +0000448 }
Evan Chengab495562006-01-25 09:14:32 +0000449}
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000450/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
451/// count of its predecessors. If a predecessor pending count is zero, add it to
452/// the Available queue.
Chris Lattner356183d2006-03-11 22:44:37 +0000453void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
Chris Lattner572003c2006-03-12 00:38:57 +0000454 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
Chris Lattnerd4130372006-03-09 07:15:18 +0000455 DEBUG(SU->dump(&DAG));
Chris Lattner356183d2006-03-11 22:44:37 +0000456 SU->Cycle = CurCycle;
Evan Cheng5e9a6952006-03-03 06:23:43 +0000457
Evan Chengab495562006-01-25 09:14:32 +0000458 Sequence.push_back(SU);
Evan Chengab495562006-01-25 09:14:32 +0000459
460 // Bottom up: release predecessors
Chris Lattner578d8fc2006-03-11 22:24:20 +0000461 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
462 E = SU->Preds.end(); I != E; ++I) {
Chris Lattner356183d2006-03-11 22:44:37 +0000463 ReleasePred(I->first, I->second, CurCycle);
464 // FIXME: This is something used by the priority function that it should
465 // calculate directly.
Chris Lattner578d8fc2006-03-11 22:24:20 +0000466 if (!I->second)
467 SU->NumPredsLeft--;
Evan Cheng4e3904f2006-03-02 21:38:29 +0000468 }
Evan Chengab495562006-01-25 09:14:32 +0000469}
470
471/// isReady - True if node's lower cycle bound is less or equal to the current
472/// scheduling cycle. Always true if all nodes have uniform latency 1.
473static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
474 return SU->CycleBound <= CurrCycle;
475}
476
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000477/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
478/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000479void ScheduleDAGList::ListScheduleBottomUp() {
Chris Lattner063086b2006-03-11 22:34:41 +0000480 unsigned CurrCycle = 0;
Chris Lattner7a36d972006-03-05 20:21:55 +0000481 // Add root to Available queue.
Chris Lattner356183d2006-03-11 22:44:37 +0000482 AvailableQueue->push(SUnitMap[DAG.getRoot().Val]);
Evan Chengab495562006-01-25 09:14:32 +0000483
484 // While Available queue is not empty, grab the node with the highest
485 // priority. If it is not ready put it back. Schedule the node.
486 std::vector<SUnit*> NotReady;
Chris Lattner356183d2006-03-11 22:44:37 +0000487 while (!AvailableQueue->empty()) {
488 SUnit *CurrNode = AvailableQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000489
Evan Chengab495562006-01-25 09:14:32 +0000490 while (!isReady(CurrNode, CurrCycle)) {
491 NotReady.push_back(CurrNode);
Chris Lattner356183d2006-03-11 22:44:37 +0000492 CurrNode = AvailableQueue->pop();
Evan Chengab495562006-01-25 09:14:32 +0000493 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000494
495 // Add the nodes that aren't ready back onto the available list.
Chris Lattner356183d2006-03-11 22:44:37 +0000496 AvailableQueue->push_all(NotReady);
Chris Lattner25e25562006-03-10 04:32:49 +0000497 NotReady.clear();
Evan Chengab495562006-01-25 09:14:32 +0000498
Chris Lattner063086b2006-03-11 22:34:41 +0000499 ScheduleNodeBottomUp(CurrNode, CurrCycle);
500 CurrCycle++;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000501 CurrNode->isScheduled = true;
Chris Lattner356183d2006-03-11 22:44:37 +0000502 AvailableQueue->ScheduledNode(CurrNode);
Evan Chengab495562006-01-25 09:14:32 +0000503 }
504
505 // Add entry node last
506 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
507 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Evan Chengab495562006-01-25 09:14:32 +0000508 Sequence.push_back(Entry);
509 }
510
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000511 // Reverse the order if it is bottom up.
512 std::reverse(Sequence.begin(), Sequence.end());
513
514
Evan Chengab495562006-01-25 09:14:32 +0000515#ifndef NDEBUG
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000516 // Verify that all SUnits were scheduled.
Evan Chengc4c339c2006-01-26 00:30:29 +0000517 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000518 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
519 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
Evan Chengc4c339c2006-01-26 00:30:29 +0000520 if (!AnyNotSched)
521 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000522 SUnits[i].dump(&DAG);
Evan Chengc4c339c2006-01-26 00:30:29 +0000523 std::cerr << "has not been scheduled!\n";
524 AnyNotSched = true;
Evan Chengab495562006-01-25 09:14:32 +0000525 }
Evan Chengab495562006-01-25 09:14:32 +0000526 }
Evan Chengc4c339c2006-01-26 00:30:29 +0000527 assert(!AnyNotSched);
Reid Spencer5edde662006-01-25 21:49:13 +0000528#endif
Evan Chengab495562006-01-25 09:14:32 +0000529}
530
Chris Lattner9995a0c2006-03-11 22:28:35 +0000531//===----------------------------------------------------------------------===//
532// Top-Down Scheduling
533//===----------------------------------------------------------------------===//
534
535/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Chris Lattner572003c2006-03-12 00:38:57 +0000536/// the PendingQueue if the count reaches zero.
537void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
Chris Lattner9995a0c2006-03-11 22:28:35 +0000538 if (!isChain)
539 SuccSU->NumPredsLeft--;
540 else
541 SuccSU->NumChainPredsLeft--;
542
Chris Lattner572003c2006-03-12 00:38:57 +0000543 assert(SuccSU->NumPredsLeft >= 0 && SuccSU->NumChainPredsLeft >= 0 &&
544 "List scheduling internal error");
Chris Lattner9995a0c2006-03-11 22:28:35 +0000545
546 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
Chris Lattner572003c2006-03-12 00:38:57 +0000547 // Compute how many cycles it will be before this actually becomes
548 // available. This is the max of the start time of all predecessors plus
549 // their latencies.
550 unsigned AvailableCycle = 0;
551 for (std::set<std::pair<SUnit*, bool> >::iterator I = SuccSU->Preds.begin(),
552 E = SuccSU->Preds.end(); I != E; ++I) {
Chris Lattner86a9b602006-03-12 03:52:09 +0000553 // If this is a token edge, we don't need to wait for the full latency of
554 // the preceeding instruction (e.g. a long-latency load) unless there is
555 // also some other data dependence.
556 unsigned PredDoneCycle = I->first->Cycle;
557 if (!I->second)
558 PredDoneCycle += I->first->Latency;
559 else
560 PredDoneCycle += 1;
561
562 AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
Chris Lattner572003c2006-03-12 00:38:57 +0000563 }
564
565 PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
566 SuccSU->isPending = true;
Chris Lattner9995a0c2006-03-11 22:28:35 +0000567 }
568}
569
570/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
571/// count of its successors. If a successor pending count is zero, add it to
572/// the Available queue.
Chris Lattner356183d2006-03-11 22:44:37 +0000573void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
Chris Lattner572003c2006-03-12 00:38:57 +0000574 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
Chris Lattner9995a0c2006-03-11 22:28:35 +0000575 DEBUG(SU->dump(&DAG));
576
577 Sequence.push_back(SU);
Chris Lattner356183d2006-03-11 22:44:37 +0000578 SU->Cycle = CurCycle;
Chris Lattner9995a0c2006-03-11 22:28:35 +0000579
580 // Bottom up: release successors.
581 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
Chris Lattner356183d2006-03-11 22:44:37 +0000582 E = SU->Succs.end(); I != E; ++I)
Chris Lattner572003c2006-03-12 00:38:57 +0000583 ReleaseSucc(I->first, I->second);
Chris Lattner9995a0c2006-03-11 22:28:35 +0000584}
585
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000586/// ListScheduleTopDown - The main loop of list scheduling for top-down
587/// schedulers.
Chris Lattner399bee22006-03-09 06:48:37 +0000588void ScheduleDAGList::ListScheduleTopDown() {
Chris Lattner572003c2006-03-12 00:38:57 +0000589 unsigned CurCycle = 0;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000590 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
Chris Lattner572003c2006-03-12 00:38:57 +0000591
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000592 // All leaves to Available queue.
Chris Lattner42e20262006-03-08 04:54:34 +0000593 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000594 // It is available if it has no predecessors.
Chris Lattner572003c2006-03-12 00:38:57 +0000595 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
Chris Lattner356183d2006-03-11 22:44:37 +0000596 AvailableQueue->push(&SUnits[i]);
Chris Lattner572003c2006-03-12 00:38:57 +0000597 SUnits[i].isAvailable = SUnits[i].isPending = true;
598 }
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000599 }
600
Chris Lattner572003c2006-03-12 00:38:57 +0000601 // Emit the entry node first.
602 ScheduleNodeTopDown(Entry, CurCycle);
603 HazardRec->EmitInstruction(Entry->Node);
604
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000605 // While Available queue is not empty, grab the node with the highest
606 // priority. If it is not ready put it back. Schedule the node.
607 std::vector<SUnit*> NotReady;
Chris Lattner572003c2006-03-12 00:38:57 +0000608 while (!AvailableQueue->empty() || !PendingQueue.empty()) {
609 // Check to see if any of the pending instructions are ready to issue. If
610 // so, add them to the available queue.
611 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i)
612 if (PendingQueue[i].first == CurCycle) {
613 AvailableQueue->push(PendingQueue[i].second);
614 PendingQueue[i].second->isAvailable = true;
615 PendingQueue[i] = PendingQueue.back();
616 PendingQueue.pop_back();
617 --i; --e;
618 } else {
619 assert(PendingQueue[i].first > CurCycle && "Negative latency?");
620 }
621
Chris Lattnere50c0922006-03-05 22:45:01 +0000622 SUnit *FoundNode = 0;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000623
Chris Lattnere50c0922006-03-05 22:45:01 +0000624 bool HasNoopHazards = false;
Chris Lattner572003c2006-03-12 00:38:57 +0000625 while (!AvailableQueue->empty()) {
Chris Lattner356183d2006-03-11 22:44:37 +0000626 SUnit *CurNode = AvailableQueue->pop();
Chris Lattner0c801bd2006-03-07 05:40:43 +0000627
628 // Get the node represented by this SUnit.
629 SDNode *N = CurNode->Node;
630 // If this is a pseudo op, like copyfromreg, look to see if there is a
631 // real target node flagged to it. If so, use the target node.
632 for (unsigned i = 0, e = CurNode->FlaggedNodes.size();
633 N->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
634 N = CurNode->FlaggedNodes[i];
635
Chris Lattner543832d2006-03-08 04:25:59 +0000636 HazardRecognizer::HazardType HT = HazardRec->getHazardType(N);
Chris Lattnere50c0922006-03-05 22:45:01 +0000637 if (HT == HazardRecognizer::NoHazard) {
Chris Lattner0c801bd2006-03-07 05:40:43 +0000638 FoundNode = CurNode;
Chris Lattnere50c0922006-03-05 22:45:01 +0000639 break;
640 }
641
642 // Remember if this is a noop hazard.
643 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
644
Chris Lattner0c801bd2006-03-07 05:40:43 +0000645 NotReady.push_back(CurNode);
Chris Lattner572003c2006-03-12 00:38:57 +0000646 }
Chris Lattnere50c0922006-03-05 22:45:01 +0000647
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000648 // Add the nodes that aren't ready back onto the available list.
Chris Lattner356183d2006-03-11 22:44:37 +0000649 AvailableQueue->push_all(NotReady);
Chris Lattner25e25562006-03-10 04:32:49 +0000650 NotReady.clear();
Chris Lattnere50c0922006-03-05 22:45:01 +0000651
652 // If we found a node to schedule, do it now.
653 if (FoundNode) {
Chris Lattner572003c2006-03-12 00:38:57 +0000654 ScheduleNodeTopDown(FoundNode, CurCycle);
Chris Lattner543832d2006-03-08 04:25:59 +0000655 HazardRec->EmitInstruction(FoundNode->Node);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000656 FoundNode->isScheduled = true;
Chris Lattner356183d2006-03-11 22:44:37 +0000657 AvailableQueue->ScheduledNode(FoundNode);
Chris Lattner572003c2006-03-12 00:38:57 +0000658
659 // If this is a pseudo-op node, we don't want to increment the current
660 // cycle.
661 if (FoundNode->Latency == 0)
662 continue; // Don't increment for pseudo-ops!
Chris Lattnere50c0922006-03-05 22:45:01 +0000663 } else if (!HasNoopHazards) {
664 // Otherwise, we have a pipeline stall, but no other problem, just advance
665 // the current cycle and try again.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000666 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000667 HazardRec->AdvanceCycle();
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000668 ++NumStalls;
Chris Lattnere50c0922006-03-05 22:45:01 +0000669 } else {
670 // Otherwise, we have no instructions to issue and we have instructions
671 // that will fault if we don't do this right. This is the case for
672 // processors without pipeline interlocks and other cases.
Chris Lattner0c801bd2006-03-07 05:40:43 +0000673 DEBUG(std::cerr << "*** Emitting noop\n");
Chris Lattner543832d2006-03-08 04:25:59 +0000674 HazardRec->EmitNoop();
Chris Lattner00b52ea2006-03-05 23:59:20 +0000675 Sequence.push_back(0); // NULL SUnit* -> noop
Chris Lattnerfa5e1c92006-03-05 23:13:56 +0000676 ++NumNoops;
Chris Lattnere50c0922006-03-05 22:45:01 +0000677 }
Chris Lattner572003c2006-03-12 00:38:57 +0000678 ++CurCycle;
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000679 }
680
681#ifndef NDEBUG
682 // Verify that all SUnits were scheduled.
683 bool AnyNotSched = false;
Chris Lattner42e20262006-03-08 04:54:34 +0000684 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
685 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000686 if (!AnyNotSched)
687 std::cerr << "*** List scheduling failed! ***\n";
Chris Lattner42e20262006-03-08 04:54:34 +0000688 SUnits[i].dump(&DAG);
Chris Lattner98ecb8e2006-03-05 21:10:33 +0000689 std::cerr << "has not been scheduled!\n";
690 AnyNotSched = true;
691 }
692 }
693 assert(!AnyNotSched);
694#endif
695}
696
Chris Lattner9df64752006-03-09 06:35:14 +0000697//===----------------------------------------------------------------------===//
698// RegReductionPriorityQueue Implementation
699//===----------------------------------------------------------------------===//
700//
701// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
702// to reduce register pressure.
703//
704namespace {
705 class RegReductionPriorityQueue;
706
707 /// Sorting functions for the Available queue.
708 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
709 RegReductionPriorityQueue *SPQ;
710 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
711 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
712
713 bool operator()(const SUnit* left, const SUnit* right) const;
714 };
715} // end anonymous namespace
716
717namespace {
718 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
719 // SUnits - The SUnits for the current graph.
720 const std::vector<SUnit> *SUnits;
721
722 // SethiUllmanNumbers - The SethiUllman number for each node.
723 std::vector<int> SethiUllmanNumbers;
724
725 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
726 public:
727 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
728 }
729
730 void initNodes(const std::vector<SUnit> &sunits) {
731 SUnits = &sunits;
732 // Calculate node priorities.
733 CalculatePriorities();
734 }
735 void releaseState() {
736 SUnits = 0;
737 SethiUllmanNumbers.clear();
738 }
739
740 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
741 assert(NodeNum < SethiUllmanNumbers.size());
742 return SethiUllmanNumbers[NodeNum];
743 }
744
745 bool empty() const { return Queue.empty(); }
746
747 void push(SUnit *U) {
748 Queue.push(U);
749 }
Chris Lattner25e25562006-03-10 04:32:49 +0000750 void push_all(const std::vector<SUnit *> &Nodes) {
751 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
752 Queue.push(Nodes[i]);
753 }
754
Chris Lattner9df64752006-03-09 06:35:14 +0000755 SUnit *pop() {
756 SUnit *V = Queue.top();
757 Queue.pop();
758 return V;
759 }
760 private:
761 void CalculatePriorities();
762 int CalcNodePriority(const SUnit *SU);
763 };
764}
765
766bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
767 unsigned LeftNum = left->NodeNum;
768 unsigned RightNum = right->NodeNum;
769
770 int LBonus = (int)left ->isDefNUseOperand;
771 int RBonus = (int)right->isDefNUseOperand;
772
773 // Special tie breaker: if two nodes share a operand, the one that
774 // use it as a def&use operand is preferred.
775 if (left->isTwoAddress && !right->isTwoAddress) {
776 SDNode *DUNode = left->Node->getOperand(0).Val;
777 if (DUNode->isOperand(right->Node))
778 LBonus++;
779 }
780 if (!left->isTwoAddress && right->isTwoAddress) {
781 SDNode *DUNode = right->Node->getOperand(0).Val;
782 if (DUNode->isOperand(left->Node))
783 RBonus++;
784 }
785
786 // Priority1 is just the number of live range genned.
787 int LPriority1 = left ->NumPredsLeft - LBonus;
788 int RPriority1 = right->NumPredsLeft - RBonus;
789 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
790 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
791
792 if (LPriority1 > RPriority1)
793 return true;
794 else if (LPriority1 == RPriority1)
795 if (LPriority2 < RPriority2)
796 return true;
797 else if (LPriority2 == RPriority2)
798 if (left->CycleBound > right->CycleBound)
799 return true;
800
801 return false;
802}
803
804
805/// CalcNodePriority - Priority is the Sethi Ullman number.
806/// Smaller number is the higher priority.
807int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
808 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
809 if (SethiUllmanNumber != INT_MIN)
810 return SethiUllmanNumber;
811
812 if (SU->Preds.size() == 0) {
813 SethiUllmanNumber = 1;
814 } else {
815 int Extra = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000816 for (std::set<std::pair<SUnit*, bool> >::const_iterator
817 I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
818 if (I->second) continue; // ignore chain preds.
819 SUnit *PredSU = I->first;
Chris Lattner9df64752006-03-09 06:35:14 +0000820 int PredSethiUllman = CalcNodePriority(PredSU);
821 if (PredSethiUllman > SethiUllmanNumber) {
822 SethiUllmanNumber = PredSethiUllman;
823 Extra = 0;
824 } else if (PredSethiUllman == SethiUllmanNumber)
825 Extra++;
826 }
827
828 if (SU->Node->getOpcode() != ISD::TokenFactor)
829 SethiUllmanNumber += Extra;
830 else
831 SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
832 }
833
834 return SethiUllmanNumber;
835}
836
837/// CalculatePriorities - Calculate priorities of all scheduling units.
838void RegReductionPriorityQueue::CalculatePriorities() {
839 SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
840
841 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
842 CalcNodePriority(&(*SUnits)[i]);
843}
844
Chris Lattner6398c132006-03-09 07:38:27 +0000845//===----------------------------------------------------------------------===//
846// LatencyPriorityQueue Implementation
847//===----------------------------------------------------------------------===//
848//
849// This is a SchedulingPriorityQueue that schedules using latency information to
850// reduce the length of the critical path through the basic block.
851//
852namespace {
853 class LatencyPriorityQueue;
854
855 /// Sorting functions for the Available queue.
856 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
857 LatencyPriorityQueue *PQ;
858 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
859 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
860
861 bool operator()(const SUnit* left, const SUnit* right) const;
862 };
863} // end anonymous namespace
864
865namespace {
866 class LatencyPriorityQueue : public SchedulingPriorityQueue {
867 // SUnits - The SUnits for the current graph.
868 const std::vector<SUnit> *SUnits;
869
870 // Latencies - The latency (max of latency from this node to the bb exit)
871 // for each node.
872 std::vector<int> Latencies;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000873
874 /// NumNodesSolelyBlocking - This vector contains, for every node in the
875 /// Queue, the number of nodes that the node is the sole unscheduled
876 /// predecessor for. This is used as a tie-breaker heuristic for better
877 /// mobility.
878 std::vector<unsigned> NumNodesSolelyBlocking;
879
Chris Lattner6398c132006-03-09 07:38:27 +0000880 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
881public:
882 LatencyPriorityQueue() : Queue(latency_sort(this)) {
883 }
884
885 void initNodes(const std::vector<SUnit> &sunits) {
886 SUnits = &sunits;
887 // Calculate node priorities.
888 CalculatePriorities();
889 }
890 void releaseState() {
891 SUnits = 0;
892 Latencies.clear();
893 }
894
895 unsigned getLatency(unsigned NodeNum) const {
896 assert(NodeNum < Latencies.size());
897 return Latencies[NodeNum];
898 }
899
Chris Lattner349e9dd2006-03-10 05:51:05 +0000900 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
901 assert(NodeNum < NumNodesSolelyBlocking.size());
902 return NumNodesSolelyBlocking[NodeNum];
903 }
904
Chris Lattner6398c132006-03-09 07:38:27 +0000905 bool empty() const { return Queue.empty(); }
906
Chris Lattner349e9dd2006-03-10 05:51:05 +0000907 virtual void push(SUnit *U) {
908 push_impl(U);
Chris Lattner6398c132006-03-09 07:38:27 +0000909 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000910 void push_impl(SUnit *U);
911
Chris Lattner25e25562006-03-10 04:32:49 +0000912 void push_all(const std::vector<SUnit *> &Nodes) {
913 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner349e9dd2006-03-10 05:51:05 +0000914 push_impl(Nodes[i]);
Chris Lattner25e25562006-03-10 04:32:49 +0000915 }
916
Chris Lattner6398c132006-03-09 07:38:27 +0000917 SUnit *pop() {
918 SUnit *V = Queue.top();
919 Queue.pop();
Chris Lattner6398c132006-03-09 07:38:27 +0000920 return V;
921 }
Chris Lattner349e9dd2006-03-10 05:51:05 +0000922
923 // ScheduledNode - As nodes are scheduled, we look to see if there are any
924 // successor nodes that have a single unscheduled predecessor. If so, that
925 // single predecessor has a higher priority, since scheduling it will make
926 // the node available.
927 void ScheduledNode(SUnit *Node);
928
Chris Lattner6398c132006-03-09 07:38:27 +0000929private:
930 void CalculatePriorities();
931 int CalcLatency(const SUnit &SU);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000932 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
933
934 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
935 /// node from a priority queue. We should roll our own heap to make this
936 /// better or something.
937 void RemoveFromPriorityQueue(SUnit *SU) {
938 std::vector<SUnit*> Temp;
939
940 assert(!Queue.empty() && "Not in queue!");
941 while (Queue.top() != SU) {
942 Temp.push_back(Queue.top());
943 Queue.pop();
944 assert(!Queue.empty() && "Not in queue!");
945 }
946
947 // Remove the node from the PQ.
948 Queue.pop();
949
950 // Add all the other nodes back.
951 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
952 Queue.push(Temp[i]);
953 }
Chris Lattner6398c132006-03-09 07:38:27 +0000954 };
955}
956
957bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
958 unsigned LHSNum = LHS->NodeNum;
959 unsigned RHSNum = RHS->NodeNum;
Chris Lattner349e9dd2006-03-10 05:51:05 +0000960
961 // The most important heuristic is scheduling the critical path.
962 unsigned LHSLatency = PQ->getLatency(LHSNum);
963 unsigned RHSLatency = PQ->getLatency(RHSNum);
964 if (LHSLatency < RHSLatency) return true;
965 if (LHSLatency > RHSLatency) return false;
Chris Lattner6398c132006-03-09 07:38:27 +0000966
Chris Lattner349e9dd2006-03-10 05:51:05 +0000967 // After that, if two nodes have identical latencies, look to see if one will
968 // unblock more other nodes than the other.
969 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
970 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
971 if (LHSBlocked < RHSBlocked) return true;
972 if (LHSBlocked > RHSBlocked) return false;
973
974 // Finally, just to provide a stable ordering, use the node number as a
975 // deciding factor.
976 return LHSNum < RHSNum;
Chris Lattner6398c132006-03-09 07:38:27 +0000977}
978
979
980/// CalcNodePriority - Calculate the maximal path from the node to the exit.
981///
982int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
983 int &Latency = Latencies[SU.NodeNum];
984 if (Latency != -1)
985 return Latency;
986
987 int MaxSuccLatency = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +0000988 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
Chris Lattner6398c132006-03-09 07:38:27 +0000989 E = SU.Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +0000990 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
Chris Lattner6398c132006-03-09 07:38:27 +0000991
992 return Latency = MaxSuccLatency + SU.Latency;
993}
994
995/// CalculatePriorities - Calculate priorities of all scheduling units.
996void LatencyPriorityQueue::CalculatePriorities() {
997 Latencies.assign(SUnits->size(), -1);
Chris Lattner349e9dd2006-03-10 05:51:05 +0000998 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
Chris Lattner6398c132006-03-09 07:38:27 +0000999
1000 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1001 CalcLatency((*SUnits)[i]);
1002}
1003
Chris Lattner349e9dd2006-03-10 05:51:05 +00001004/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
1005/// of SU, return it, otherwise return null.
1006static SUnit *getSingleUnscheduledPred(SUnit *SU) {
1007 SUnit *OnlyAvailablePred = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +00001008 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +00001009 E = SU->Preds.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +00001010 if (!I->first->isScheduled) {
Chris Lattner349e9dd2006-03-10 05:51:05 +00001011 // We found an available, but not scheduled, predecessor. If it's the
1012 // only one we have found, keep track of it... otherwise give up.
Chris Lattner578d8fc2006-03-11 22:24:20 +00001013 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
Chris Lattner349e9dd2006-03-10 05:51:05 +00001014 return 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +00001015 OnlyAvailablePred = I->first;
Chris Lattner349e9dd2006-03-10 05:51:05 +00001016 }
1017
1018 return OnlyAvailablePred;
1019}
1020
1021void LatencyPriorityQueue::push_impl(SUnit *SU) {
1022 // Look at all of the successors of this node. Count the number of nodes that
1023 // this node is the sole unscheduled node for.
1024 unsigned NumNodesBlocking = 0;
Chris Lattner578d8fc2006-03-11 22:24:20 +00001025 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +00001026 E = SU->Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +00001027 if (getSingleUnscheduledPred(I->first) == SU)
Chris Lattner349e9dd2006-03-10 05:51:05 +00001028 ++NumNodesBlocking;
Chris Lattner578d8fc2006-03-11 22:24:20 +00001029 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
Chris Lattner349e9dd2006-03-10 05:51:05 +00001030
1031 Queue.push(SU);
1032}
1033
1034
1035// ScheduledNode - As nodes are scheduled, we look to see if there are any
1036// successor nodes that have a single unscheduled predecessor. If so, that
1037// single predecessor has a higher priority, since scheduling it will make
1038// the node available.
1039void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
Chris Lattner578d8fc2006-03-11 22:24:20 +00001040 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
Chris Lattner349e9dd2006-03-10 05:51:05 +00001041 E = SU->Succs.end(); I != E; ++I)
Chris Lattner578d8fc2006-03-11 22:24:20 +00001042 AdjustPriorityOfUnscheduledPreds(I->first);
Chris Lattner349e9dd2006-03-10 05:51:05 +00001043}
1044
1045/// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1046/// scheduled. If SU is not itself available, then there is at least one
1047/// predecessor node that has not been scheduled yet. If SU has exactly ONE
1048/// unscheduled predecessor, we want to increase its priority: it getting
1049/// scheduled will make this node available, so it is better than some other
1050/// node of the same priority that will not make a node available.
1051void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
Chris Lattner572003c2006-03-12 00:38:57 +00001052 if (SU->isPending) return; // All preds scheduled.
Chris Lattner349e9dd2006-03-10 05:51:05 +00001053
1054 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1055 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1056
1057 // Okay, we found a single predecessor that is available, but not scheduled.
1058 // Since it is available, it must be in the priority queue. First remove it.
1059 RemoveFromPriorityQueue(OnlyAvailablePred);
1060
1061 // Reinsert the node into the priority queue, which recomputes its
1062 // NumNodesSolelyBlocking value.
1063 push(OnlyAvailablePred);
1064}
1065
Chris Lattner9df64752006-03-09 06:35:14 +00001066
1067//===----------------------------------------------------------------------===//
1068// Public Constructor Functions
1069//===----------------------------------------------------------------------===//
1070
Evan Chengab495562006-01-25 09:14:32 +00001071llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1072 MachineBasicBlock *BB) {
Chris Lattner543832d2006-03-08 04:25:59 +00001073 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
Chris Lattner9df64752006-03-09 06:35:14 +00001074 new RegReductionPriorityQueue(),
Chris Lattner543832d2006-03-08 04:25:59 +00001075 new HazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00001076}
1077
Chris Lattner47639db2006-03-06 00:22:00 +00001078/// createTDListDAGScheduler - This creates a top-down list scheduler with the
1079/// specified hazard recognizer.
1080ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1081 MachineBasicBlock *BB,
Chris Lattner543832d2006-03-08 04:25:59 +00001082 HazardRecognizer *HR) {
Chris Lattner9df64752006-03-09 06:35:14 +00001083 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
Chris Lattner6398c132006-03-09 07:38:27 +00001084 new LatencyPriorityQueue(),
Chris Lattner9df64752006-03-09 06:35:14 +00001085 HR);
Evan Cheng31272342006-01-23 08:26:10 +00001086}