blob: 2ae0c361161ec729e24f89ce15194ebe9179726a [file] [log] [blame]
Evan Chengd38c22b2006-05-11 23:55:42 +00001//===----- ScheduleDAGList.cpp - Reg pressure reduction list scheduler ----===//
2//
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//
10// This implements bottom-up and top-down register pressure reduction list
11// schedulers, using standard algorithms. The basic approach uses a priority
12// queue of available nodes to schedule. One at a time, nodes are taken from
13// the priority queue (thus in priority order), checked for legality to
14// schedule, and emitted if legal.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "sched"
19#include "llvm/CodeGen/ScheduleDAG.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000020#include "llvm/CodeGen/SchedulerRegistry.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000021#include "llvm/CodeGen/SSARegMap.h"
22#include "llvm/Target/MRegisterInfo.h"
Owen Anderson8c2c1e92006-05-12 06:33:49 +000023#include "llvm/Target/TargetData.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000024#include "llvm/Target/TargetMachine.h"
25#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000027#include "llvm/Support/Compiler.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000028#include "llvm/ADT/Statistic.h"
29#include <climits>
Evan Chengd38c22b2006-05-11 23:55:42 +000030#include <queue>
31#include "llvm/Support/CommandLine.h"
32using namespace llvm;
33
Jim Laskey95eda5b2006-08-01 14:21:23 +000034static RegisterScheduler
35 burrListDAGScheduler("list-burr",
36 " Bottom-up register reduction list scheduling",
37 createBURRListDAGScheduler);
38static RegisterScheduler
39 tdrListrDAGScheduler("list-tdrr",
40 " Top-down register reduction list scheduling",
41 createTDRRListDAGScheduler);
42
Evan Chengd38c22b2006-05-11 23:55:42 +000043namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +000044//===----------------------------------------------------------------------===//
45/// ScheduleDAGRRList - The actual register reduction list scheduler
46/// implementation. This supports both top-down and bottom-up scheduling.
47///
48
Chris Lattnere097e6f2006-06-28 22:17:39 +000049class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
Evan Chengd38c22b2006-05-11 23:55:42 +000050private:
51 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
52 /// it is top-down.
53 bool isBottomUp;
54
55 /// AvailableQueue - The priority queue to use for the available SUnits.
56 ///
57 SchedulingPriorityQueue *AvailableQueue;
58
59public:
60 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
61 const TargetMachine &tm, bool isbottomup,
62 SchedulingPriorityQueue *availqueue)
63 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
64 AvailableQueue(availqueue) {
65 }
66
67 ~ScheduleDAGRRList() {
68 delete AvailableQueue;
69 }
70
71 void Schedule();
72
73private:
74 void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
75 void ReleaseSucc(SUnit *SuccSU, bool isChain, unsigned CurCycle);
Evan Chengd12c97d2006-05-30 18:05:39 +000076 void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
77 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +000078 void ListScheduleTopDown();
79 void ListScheduleBottomUp();
Evan Chengafed73e2006-05-12 01:58:24 +000080 void CommuteNodesToReducePressure();
Evan Chengd38c22b2006-05-11 23:55:42 +000081};
82} // end anonymous namespace
83
84
85/// Schedule - Schedule the DAG using list scheduling.
86void ScheduleDAGRRList::Schedule() {
Bill Wendling22e978a2006-12-07 20:04:42 +000087 DOUT << "********** List Scheduling **********\n";
Evan Chengd38c22b2006-05-11 23:55:42 +000088
89 // Build scheduling units.
90 BuildSchedUnits();
91
Evan Chengd38c22b2006-05-11 23:55:42 +000092 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Chris Lattnerd86418a2006-08-17 00:09:56 +000093 SUnits[su].dumpAll(&DAG));
Evan Cheng47fbeda2006-10-14 08:34:06 +000094 CalculateDepths();
95 CalculateHeights();
Evan Chengd38c22b2006-05-11 23:55:42 +000096
Evan Chengfd2c5dd2006-11-04 09:44:31 +000097 AvailableQueue->initNodes(SUnitMap, SUnits);
Evan Chengd38c22b2006-05-11 23:55:42 +000098
99 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
100 if (isBottomUp)
101 ListScheduleBottomUp();
102 else
103 ListScheduleTopDown();
104
105 AvailableQueue->releaseState();
Evan Chengafed73e2006-05-12 01:58:24 +0000106
Evan Cheng009f5f52006-05-25 08:37:31 +0000107 CommuteNodesToReducePressure();
Evan Chengd38c22b2006-05-11 23:55:42 +0000108
Bill Wendling22e978a2006-12-07 20:04:42 +0000109 DOUT << "*** Final schedule ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000110 DEBUG(dumpSchedule());
Bill Wendling22e978a2006-12-07 20:04:42 +0000111 DOUT << "\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000112
113 // Emit in scheduled order
114 EmitSchedule();
115}
116
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000117/// CommuteNodesToReducePressure - If a node is two-address and commutable, and
Evan Chengafed73e2006-05-12 01:58:24 +0000118/// it is not the last use of its first operand, add it to the CommuteSet if
119/// possible. It will be commuted when it is translated to a MI.
120void ScheduleDAGRRList::CommuteNodesToReducePressure() {
121 std::set<SUnit *> OperandSeen;
122 for (unsigned i = Sequence.size()-1; i != 0; --i) { // Ignore first node.
123 SUnit *SU = Sequence[i];
124 if (!SU) continue;
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000125 if (SU->isCommutable) {
126 unsigned Opc = SU->Node->getTargetOpcode();
127 unsigned NumRes = CountResults(SU->Node);
128 unsigned NumOps = CountOperands(SU->Node);
129 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng67fc1412006-12-01 21:52:58 +0000130 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) == -1)
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000131 continue;
132
133 SDNode *OpN = SU->Node->getOperand(j).Val;
134 SUnit *OpSU = SUnitMap[OpN];
135 if (OpSU && OperandSeen.count(OpSU) == 1) {
136 // Ok, so SU is not the last use of OpSU, but SU is two-address so
137 // it will clobber OpSU. Try to commute SU if no other source operands
138 // are live below.
139 bool DoCommute = true;
140 for (unsigned k = 0; k < NumOps; ++k) {
141 if (k != j) {
142 OpN = SU->Node->getOperand(k).Val;
143 OpSU = SUnitMap[OpN];
144 if (OpSU && OperandSeen.count(OpSU) == 1) {
145 DoCommute = false;
146 break;
147 }
148 }
Evan Chengafed73e2006-05-12 01:58:24 +0000149 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000150 if (DoCommute)
151 CommuteSet.insert(SU->Node);
Evan Chengafed73e2006-05-12 01:58:24 +0000152 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000153
154 // Only look at the first use&def node for now.
155 break;
Evan Chengafed73e2006-05-12 01:58:24 +0000156 }
157 }
158
Chris Lattnerd86418a2006-08-17 00:09:56 +0000159 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
160 I != E; ++I) {
Evan Chengafed73e2006-05-12 01:58:24 +0000161 if (!I->second)
162 OperandSeen.insert(I->first);
163 }
164 }
165}
Evan Chengd38c22b2006-05-11 23:55:42 +0000166
167//===----------------------------------------------------------------------===//
168// Bottom-Up Scheduling
169//===----------------------------------------------------------------------===//
170
Evan Chengd38c22b2006-05-11 23:55:42 +0000171/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
172/// the Available queue is the count reaches zero. Also update its cycle bound.
173void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
174 unsigned CurCycle) {
175 // FIXME: the distance between two nodes is not always == the predecessor's
176 // latency. For example, the reader can very well read the register written
177 // by the predecessor later than the issue cycle. It also depends on the
178 // interrupt model (drain vs. freeze).
179 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
180
181 if (!isChain)
182 PredSU->NumSuccsLeft--;
183 else
184 PredSU->NumChainSuccsLeft--;
185
186#ifndef NDEBUG
187 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000188 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000189 PredSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000190 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000191 assert(0);
192 }
193#endif
194
195 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
196 // EntryToken has to go last! Special case it here.
197 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
198 PredSU->isAvailable = true;
199 AvailableQueue->push(PredSU);
200 }
201 }
202}
203
204/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
205/// count of its predecessors. If a predecessor pending count is zero, add it to
206/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +0000207void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000208 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +0000209 DEBUG(SU->dump(&DAG));
210 SU->Cycle = CurCycle;
211
212 AvailableQueue->ScheduledNode(SU);
213 Sequence.push_back(SU);
214
215 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000216 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
217 I != E; ++I)
Evan Chengd38c22b2006-05-11 23:55:42 +0000218 ReleasePred(I->first, I->second, CurCycle);
219 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000220}
221
222/// isReady - True if node's lower cycle bound is less or equal to the current
223/// scheduling cycle. Always true if all nodes have uniform latency 1.
224static inline bool isReady(SUnit *SU, unsigned CurCycle) {
225 return SU->CycleBound <= CurCycle;
226}
227
228/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
229/// schedulers.
230void ScheduleDAGRRList::ListScheduleBottomUp() {
231 unsigned CurCycle = 0;
232 // Add root to Available queue.
233 AvailableQueue->push(SUnitMap[DAG.getRoot().Val]);
234
235 // While Available queue is not empty, grab the node with the highest
236 // priority. If it is not ready put it back. Schedule the node.
237 std::vector<SUnit*> NotReady;
Evan Chengd38c22b2006-05-11 23:55:42 +0000238 while (!AvailableQueue->empty()) {
239 SUnit *CurNode = AvailableQueue->pop();
Evan Chengd12c97d2006-05-30 18:05:39 +0000240 while (CurNode && !isReady(CurNode, CurCycle)) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000241 NotReady.push_back(CurNode);
242 CurNode = AvailableQueue->pop();
243 }
244
245 // Add the nodes that aren't ready back onto the available list.
246 AvailableQueue->push_all(NotReady);
247 NotReady.clear();
248
Evan Chengd12c97d2006-05-30 18:05:39 +0000249 if (CurNode != NULL)
250 ScheduleNodeBottomUp(CurNode, CurCycle);
251 CurCycle++;
Evan Chengd38c22b2006-05-11 23:55:42 +0000252 }
253
254 // Add entry node last
255 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
256 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
257 Sequence.push_back(Entry);
258 }
259
260 // Reverse the order if it is bottom up.
261 std::reverse(Sequence.begin(), Sequence.end());
262
263
264#ifndef NDEBUG
265 // Verify that all SUnits were scheduled.
266 bool AnyNotSched = false;
267 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
268 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
269 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +0000270 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000271 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000272 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000273 AnyNotSched = true;
274 }
275 }
276 assert(!AnyNotSched);
277#endif
278}
279
280//===----------------------------------------------------------------------===//
281// Top-Down Scheduling
282//===----------------------------------------------------------------------===//
283
284/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
285/// the PendingQueue if the count reaches zero.
286void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
287 unsigned CurCycle) {
288 // FIXME: the distance between two nodes is not always == the predecessor's
289 // latency. For example, the reader can very well read the register written
290 // by the predecessor later than the issue cycle. It also depends on the
291 // interrupt model (drain vs. freeze).
292 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
293
294 if (!isChain)
295 SuccSU->NumPredsLeft--;
296 else
297 SuccSU->NumChainPredsLeft--;
298
299#ifndef NDEBUG
300 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000301 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000302 SuccSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000303 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000304 assert(0);
305 }
306#endif
307
308 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
309 SuccSU->isAvailable = true;
310 AvailableQueue->push(SuccSU);
311 }
312}
313
314
315/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
316/// count of its successors. If a successor pending count is zero, add it to
317/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +0000318void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000319 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +0000320 DEBUG(SU->dump(&DAG));
321 SU->Cycle = CurCycle;
322
323 AvailableQueue->ScheduledNode(SU);
324 Sequence.push_back(SU);
325
326 // Top down: release successors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000327 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
328 I != E; ++I)
Evan Chengd38c22b2006-05-11 23:55:42 +0000329 ReleaseSucc(I->first, I->second, CurCycle);
330 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000331}
332
333void ScheduleDAGRRList::ListScheduleTopDown() {
334 unsigned CurCycle = 0;
335 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
336
337 // All leaves to Available queue.
338 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
339 // It is available if it has no predecessors.
340 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
341 AvailableQueue->push(&SUnits[i]);
342 SUnits[i].isAvailable = true;
343 }
344 }
345
346 // Emit the entry node first.
347 ScheduleNodeTopDown(Entry, CurCycle);
Evan Chengd12c97d2006-05-30 18:05:39 +0000348 CurCycle++;
Evan Chengd38c22b2006-05-11 23:55:42 +0000349
350 // While Available queue is not empty, grab the node with the highest
351 // priority. If it is not ready put it back. Schedule the node.
352 std::vector<SUnit*> NotReady;
Evan Chengd38c22b2006-05-11 23:55:42 +0000353 while (!AvailableQueue->empty()) {
354 SUnit *CurNode = AvailableQueue->pop();
Evan Chengd12c97d2006-05-30 18:05:39 +0000355 while (CurNode && !isReady(CurNode, CurCycle)) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000356 NotReady.push_back(CurNode);
357 CurNode = AvailableQueue->pop();
358 }
359
360 // Add the nodes that aren't ready back onto the available list.
361 AvailableQueue->push_all(NotReady);
362 NotReady.clear();
363
Evan Chengd12c97d2006-05-30 18:05:39 +0000364 if (CurNode != NULL)
365 ScheduleNodeTopDown(CurNode, CurCycle);
366 CurCycle++;
Evan Chengd38c22b2006-05-11 23:55:42 +0000367 }
368
369
370#ifndef NDEBUG
371 // Verify that all SUnits were scheduled.
372 bool AnyNotSched = false;
373 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
374 if (!SUnits[i].isScheduled) {
375 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +0000376 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000377 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000378 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000379 AnyNotSched = true;
380 }
381 }
382 assert(!AnyNotSched);
383#endif
384}
385
386
387
388//===----------------------------------------------------------------------===//
389// RegReductionPriorityQueue Implementation
390//===----------------------------------------------------------------------===//
391//
392// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
393// to reduce register pressure.
394//
395namespace {
396 template<class SF>
397 class RegReductionPriorityQueue;
398
399 /// Sorting functions for the Available queue.
400 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
401 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
402 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
403 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
404
405 bool operator()(const SUnit* left, const SUnit* right) const;
406 };
407
408 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
409 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
410 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
411 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
412
413 bool operator()(const SUnit* left, const SUnit* right) const;
414 };
415} // end anonymous namespace
416
417namespace {
418 template<class SF>
Chris Lattner996795b2006-06-28 23:17:24 +0000419 class VISIBILITY_HIDDEN RegReductionPriorityQueue
420 : public SchedulingPriorityQueue {
Evan Chengd38c22b2006-05-11 23:55:42 +0000421 std::priority_queue<SUnit*, std::vector<SUnit*>, SF> Queue;
422
423 public:
424 RegReductionPriorityQueue() :
425 Queue(SF(this)) {}
426
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000427 virtual void initNodes(std::map<SDNode*, SUnit*> &sumap,
428 std::vector<SUnit> &sunits) {}
Evan Chengd38c22b2006-05-11 23:55:42 +0000429 virtual void releaseState() {}
430
431 virtual int getSethiUllmanNumber(unsigned NodeNum) const {
432 return 0;
433 }
434
435 bool empty() const { return Queue.empty(); }
436
437 void push(SUnit *U) {
438 Queue.push(U);
439 }
440 void push_all(const std::vector<SUnit *> &Nodes) {
441 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
442 Queue.push(Nodes[i]);
443 }
444
445 SUnit *pop() {
Evan Chengd12c97d2006-05-30 18:05:39 +0000446 if (empty()) return NULL;
Evan Chengd38c22b2006-05-11 23:55:42 +0000447 SUnit *V = Queue.top();
448 Queue.pop();
449 return V;
450 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000451
452 virtual bool isDUOperand(const SUnit *SU1, const SUnit *SU2) {
453 return false;
454 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000455 };
456
457 template<class SF>
Chris Lattner996795b2006-06-28 23:17:24 +0000458 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
459 : public RegReductionPriorityQueue<SF> {
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000460 // SUnitMap SDNode to SUnit mapping (n -> 1).
461 std::map<SDNode*, SUnit*> *SUnitMap;
462
Evan Chengd38c22b2006-05-11 23:55:42 +0000463 // SUnits - The SUnits for the current graph.
464 const std::vector<SUnit> *SUnits;
465
466 // SethiUllmanNumbers - The SethiUllman number for each node.
467 std::vector<int> SethiUllmanNumbers;
468
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000469 const TargetInstrInfo *TII;
Evan Chengd38c22b2006-05-11 23:55:42 +0000470 public:
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000471 BURegReductionPriorityQueue(const TargetInstrInfo *tii)
472 : TII(tii) {}
Evan Chengd38c22b2006-05-11 23:55:42 +0000473
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000474 void initNodes(std::map<SDNode*, SUnit*> &sumap,
475 std::vector<SUnit> &sunits) {
476 SUnitMap = &sumap;
Evan Chengd38c22b2006-05-11 23:55:42 +0000477 SUnits = &sunits;
478 // Add pseudo dependency edges for two-address nodes.
Evan Chengafed73e2006-05-12 01:58:24 +0000479 AddPseudoTwoAddrDeps();
Evan Chengd38c22b2006-05-11 23:55:42 +0000480 // Calculate node priorities.
481 CalculatePriorities();
482 }
483
484 void releaseState() {
485 SUnits = 0;
486 SethiUllmanNumbers.clear();
487 }
488
489 int getSethiUllmanNumber(unsigned NodeNum) const {
490 assert(NodeNum < SethiUllmanNumbers.size());
491 return SethiUllmanNumbers[NodeNum];
492 }
493
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000494 bool isDUOperand(const SUnit *SU1, const SUnit *SU2) {
495 unsigned Opc = SU1->Node->getTargetOpcode();
496 unsigned NumRes = ScheduleDAG::CountResults(SU1->Node);
497 unsigned NumOps = ScheduleDAG::CountOperands(SU1->Node);
498 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng67fc1412006-12-01 21:52:58 +0000499 if (TII->getOperandConstraint(Opc, i+NumRes, TOI::TIED_TO) == -1)
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000500 continue;
501 if (SU1->Node->getOperand(i).isOperand(SU2->Node))
502 return true;
503 }
504 return false;
505 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000506 private:
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000507 bool canClobber(SUnit *SU, SUnit *Op);
Evan Chengd38c22b2006-05-11 23:55:42 +0000508 void AddPseudoTwoAddrDeps();
509 void CalculatePriorities();
510 int CalcNodePriority(const SUnit *SU);
511 };
512
513
514 template<class SF>
515 class TDRegReductionPriorityQueue : public RegReductionPriorityQueue<SF> {
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000516 // SUnitMap SDNode to SUnit mapping (n -> 1).
517 std::map<SDNode*, SUnit*> *SUnitMap;
518
Evan Chengd38c22b2006-05-11 23:55:42 +0000519 // SUnits - The SUnits for the current graph.
520 const std::vector<SUnit> *SUnits;
521
522 // SethiUllmanNumbers - The SethiUllman number for each node.
523 std::vector<int> SethiUllmanNumbers;
524
525 public:
526 TDRegReductionPriorityQueue() {}
527
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000528 void initNodes(std::map<SDNode*, SUnit*> &sumap,
529 std::vector<SUnit> &sunits) {
530 SUnitMap = &sumap;
Evan Chengd38c22b2006-05-11 23:55:42 +0000531 SUnits = &sunits;
532 // Calculate node priorities.
533 CalculatePriorities();
534 }
535
536 void releaseState() {
537 SUnits = 0;
538 SethiUllmanNumbers.clear();
539 }
540
541 int getSethiUllmanNumber(unsigned NodeNum) const {
542 assert(NodeNum < SethiUllmanNumbers.size());
543 return SethiUllmanNumbers[NodeNum];
544 }
545
546 private:
547 void CalculatePriorities();
548 int CalcNodePriority(const SUnit *SU);
549 };
550}
551
Evan Cheng99f2f792006-05-13 08:22:24 +0000552static bool isFloater(const SUnit *SU) {
553 if (SU->Node->isTargetOpcode()) {
554 if (SU->NumPreds == 0)
555 return true;
556 if (SU->NumPreds == 1) {
Chris Lattnerd86418a2006-08-17 00:09:56 +0000557 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
558 I != E; ++I) {
Evan Cheng99f2f792006-05-13 08:22:24 +0000559 if (I->second) continue;
560
561 SUnit *PredSU = I->first;
562 unsigned Opc = PredSU->Node->getOpcode();
563 if (Opc != ISD::EntryToken && Opc != ISD::TokenFactor &&
Evan Cheng47218fa2006-11-01 22:17:06 +0000564 Opc != ISD::CopyToReg)
Evan Cheng99f2f792006-05-13 08:22:24 +0000565 return false;
566 }
567 return true;
568 }
569 }
570 return false;
571}
572
573static bool isSimpleFloaterUse(const SUnit *SU) {
574 unsigned NumOps = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +0000575 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
576 I != E; ++I) {
Evan Cheng99f2f792006-05-13 08:22:24 +0000577 if (I->second) continue;
578 if (++NumOps > 1)
579 return false;
580 if (!isFloater(I->first))
581 return false;
582 }
583 return true;
584}
585
Evan Chengd38c22b2006-05-11 23:55:42 +0000586// Bottom up
587bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
588 unsigned LeftNum = left->NodeNum;
589 unsigned RightNum = right->NodeNum;
590 bool LIsTarget = left->Node->isTargetOpcode();
591 bool RIsTarget = right->Node->isTargetOpcode();
592 int LPriority = SPQ->getSethiUllmanNumber(LeftNum);
593 int RPriority = SPQ->getSethiUllmanNumber(RightNum);
Evan Chengd38c22b2006-05-11 23:55:42 +0000594 int LBonus = 0;
595 int RBonus = 0;
596
597 // Schedule floaters (e.g. load from some constant address) and those nodes
598 // with a single predecessor each first. They maintain / reduce register
599 // pressure.
Evan Cheng99f2f792006-05-13 08:22:24 +0000600 if (isFloater(left) || isSimpleFloaterUse(left))
Evan Chengd38c22b2006-05-11 23:55:42 +0000601 LBonus += 2;
Evan Cheng99f2f792006-05-13 08:22:24 +0000602 if (isFloater(right) || isSimpleFloaterUse(right))
Evan Chengd38c22b2006-05-11 23:55:42 +0000603 RBonus += 2;
604
Evan Cheng99f2f792006-05-13 08:22:24 +0000605 // Special tie breaker: if two nodes share a operand, the one that use it
606 // as a def&use operand is preferred.
607 if (LIsTarget && RIsTarget) {
608 if (left->isTwoAddress && !right->isTwoAddress) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000609 if (SPQ->isDUOperand(left, right))
Evan Cheng99f2f792006-05-13 08:22:24 +0000610 LBonus += 2;
611 }
612 if (!left->isTwoAddress && right->isTwoAddress) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000613 if (SPQ->isDUOperand(right, left))
Evan Cheng99f2f792006-05-13 08:22:24 +0000614 RBonus += 2;
615 }
616 }
617
Evan Chengd38c22b2006-05-11 23:55:42 +0000618 if (LPriority+LBonus < RPriority+RBonus)
619 return true;
620 else if (LPriority+LBonus == RPriority+RBonus)
Evan Cheng99f2f792006-05-13 08:22:24 +0000621 if (left->Height > right->Height)
Evan Chengd38c22b2006-05-11 23:55:42 +0000622 return true;
Evan Cheng99f2f792006-05-13 08:22:24 +0000623 else if (left->Height == right->Height)
624 if (left->Depth < right->Depth)
Evan Chengd38c22b2006-05-11 23:55:42 +0000625 return true;
Evan Cheng99f2f792006-05-13 08:22:24 +0000626 else if (left->Depth == right->Depth)
627 if (left->CycleBound > right->CycleBound)
628 return true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000629 return false;
630}
631
632static inline bool isCopyFromLiveIn(const SUnit *SU) {
633 SDNode *N = SU->Node;
634 return N->getOpcode() == ISD::CopyFromReg &&
635 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
636}
637
638// FIXME: This is probably too slow!
639static void isReachable(SUnit *SU, SUnit *TargetSU,
640 std::set<SUnit *> &Visited, bool &Reached) {
641 if (Reached) return;
642 if (SU == TargetSU) {
643 Reached = true;
644 return;
645 }
646 if (!Visited.insert(SU).second) return;
647
Chris Lattnerd86418a2006-08-17 00:09:56 +0000648 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); I != E;
649 ++I)
Evan Chengd38c22b2006-05-11 23:55:42 +0000650 isReachable(I->first, TargetSU, Visited, Reached);
651}
652
653static bool isReachable(SUnit *SU, SUnit *TargetSU) {
654 std::set<SUnit *> Visited;
655 bool Reached = false;
656 isReachable(SU, TargetSU, Visited, Reached);
657 return Reached;
658}
659
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000660template<class SF>
661bool BURegReductionPriorityQueue<SF>::canClobber(SUnit *SU, SUnit *Op) {
662 if (SU->isTwoAddress) {
663 unsigned Opc = SU->Node->getTargetOpcode();
664 unsigned NumRes = ScheduleDAG::CountResults(SU->Node);
665 unsigned NumOps = ScheduleDAG::CountOperands(SU->Node);
666 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng67fc1412006-12-01 21:52:58 +0000667 if (TII->getOperandConstraint(Opc, i+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000668 SDNode *DU = SU->Node->getOperand(i).Val;
669 if (Op == (*SUnitMap)[DU])
670 return true;
671 }
672 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000673 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000674 return false;
675}
676
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000677
Evan Chengd38c22b2006-05-11 23:55:42 +0000678/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
679/// it as a def&use operand. Add a pseudo control edge from it to the other
680/// node (if it won't create a cycle) so the two-address one will be scheduled
681/// first (lower in the schedule).
682template<class SF>
683void BURegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000684 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
685 SUnit *SU = (SUnit *)&((*SUnits)[i]);
686 if (!SU->isTwoAddress)
687 continue;
688
689 SDNode *Node = SU->Node;
690 if (!Node->isTargetOpcode())
691 continue;
692
693 unsigned Opc = Node->getTargetOpcode();
694 unsigned NumRes = ScheduleDAG::CountResults(Node);
695 unsigned NumOps = ScheduleDAG::CountOperands(Node);
696 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng67fc1412006-12-01 21:52:58 +0000697 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000698 SDNode *DU = SU->Node->getOperand(j).Val;
699 SUnit *DUSU = (*SUnitMap)[DU];
Evan Chengf24d15f2006-11-06 21:33:46 +0000700 if (!DUSU) continue;
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000701 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
702 I != E; ++I) {
703 if (I->second) continue;
704 SUnit *SuccSU = I->first;
705 if (SuccSU != SU &&
706 (!canClobber(SuccSU, DUSU) ||
707 (!SU->isCommutable && SuccSU->isCommutable))){
708 if (SuccSU->Depth == SU->Depth && !isReachable(SuccSU, SU)) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000709 DOUT << "Adding an edge from SU # " << SU->NodeNum
710 << " to SU #" << SuccSU->NodeNum << "\n";
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000711 if (SU->addPred(SuccSU, true))
712 SU->NumChainPredsLeft++;
713 if (SuccSU->addSucc(SU, true))
714 SuccSU->NumChainSuccsLeft++;
715 }
716 }
717 }
718 }
719 }
720 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000721}
722
723/// CalcNodePriority - Priority is the Sethi Ullman number.
724/// Smaller number is the higher priority.
725template<class SF>
726int BURegReductionPriorityQueue<SF>::CalcNodePriority(const SUnit *SU) {
727 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
728 if (SethiUllmanNumber != 0)
729 return SethiUllmanNumber;
730
731 unsigned Opc = SU->Node->getOpcode();
Evan Cheng13591962006-11-01 22:39:30 +0000732 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
733 // CopyFromReg should be close to its def because it restricts allocation
734 // choices. But if it is a livein then perhaps we want it closer to the
735 // uses so it can be coalesced.
736 SethiUllmanNumber = INT_MIN + 10;
737 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
738 // CopyToReg should be close to its uses to facilitate coalescing and avoid
739 // spilling.
Evan Chengd38c22b2006-05-11 23:55:42 +0000740 SethiUllmanNumber = INT_MAX - 10;
741 else if (SU->NumSuccsLeft == 0)
742 // If SU does not have a use, i.e. it doesn't produce a value that would
743 // be consumed (e.g. store), then it terminates a chain of computation.
744 // Give it a small SethiUllman number so it will be scheduled right before its
745 // predecessors that it doesn't lengthen their live ranges.
746 SethiUllmanNumber = INT_MIN + 10;
Evan Cheng13591962006-11-01 22:39:30 +0000747 else if (SU->NumPredsLeft == 0)
748 // If SU does not have a def, schedule it close to its uses because it does
749 // not lengthen any live ranges.
Evan Cheng99f2f792006-05-13 08:22:24 +0000750 SethiUllmanNumber = INT_MAX - 10;
Evan Chengd38c22b2006-05-11 23:55:42 +0000751 else {
752 int Extra = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +0000753 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
754 I != E; ++I) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000755 if (I->second) continue; // ignore chain preds
756 SUnit *PredSU = I->first;
757 int PredSethiUllman = CalcNodePriority(PredSU);
758 if (PredSethiUllman > SethiUllmanNumber) {
759 SethiUllmanNumber = PredSethiUllman;
760 Extra = 0;
761 } else if (PredSethiUllman == SethiUllmanNumber && !I->second)
762 Extra++;
763 }
764
765 SethiUllmanNumber += Extra;
766 }
767
768 return SethiUllmanNumber;
769}
770
771/// CalculatePriorities - Calculate priorities of all scheduling units.
772template<class SF>
773void BURegReductionPriorityQueue<SF>::CalculatePriorities() {
774 SethiUllmanNumbers.assign(SUnits->size(), 0);
775
776 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
777 CalcNodePriority(&(*SUnits)[i]);
778}
779
780static unsigned SumOfUnscheduledPredsOfSuccs(const SUnit *SU) {
781 unsigned Sum = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +0000782 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
783 I != E; ++I) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000784 SUnit *SuccSU = I->first;
Chris Lattnerd86418a2006-08-17 00:09:56 +0000785 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
786 EE = SuccSU->Preds.end(); II != EE; ++II) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000787 SUnit *PredSU = II->first;
788 if (!PredSU->isScheduled)
789 Sum++;
790 }
791 }
792
793 return Sum;
794}
795
796
797// Top down
798bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
799 unsigned LeftNum = left->NodeNum;
800 unsigned RightNum = right->NodeNum;
801 int LPriority = SPQ->getSethiUllmanNumber(LeftNum);
802 int RPriority = SPQ->getSethiUllmanNumber(RightNum);
803 bool LIsTarget = left->Node->isTargetOpcode();
804 bool RIsTarget = right->Node->isTargetOpcode();
805 bool LIsFloater = LIsTarget && left->NumPreds == 0;
806 bool RIsFloater = RIsTarget && right->NumPreds == 0;
807 unsigned LBonus = (SumOfUnscheduledPredsOfSuccs(left) == 1) ? 2 : 0;
808 unsigned RBonus = (SumOfUnscheduledPredsOfSuccs(right) == 1) ? 2 : 0;
809
810 if (left->NumSuccs == 0 && right->NumSuccs != 0)
811 return false;
812 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
813 return true;
814
815 // Special tie breaker: if two nodes share a operand, the one that use it
816 // as a def&use operand is preferred.
817 if (LIsTarget && RIsTarget) {
818 if (left->isTwoAddress && !right->isTwoAddress) {
819 SDNode *DUNode = left->Node->getOperand(0).Val;
820 if (DUNode->isOperand(right->Node))
821 RBonus += 2;
822 }
823 if (!left->isTwoAddress && right->isTwoAddress) {
824 SDNode *DUNode = right->Node->getOperand(0).Val;
825 if (DUNode->isOperand(left->Node))
826 LBonus += 2;
827 }
828 }
829 if (LIsFloater)
830 LBonus -= 2;
831 if (RIsFloater)
832 RBonus -= 2;
833 if (left->NumSuccs == 1)
834 LBonus += 2;
835 if (right->NumSuccs == 1)
836 RBonus += 2;
837
838 if (LPriority+LBonus < RPriority+RBonus)
839 return true;
840 else if (LPriority == RPriority)
841 if (left->Depth < right->Depth)
842 return true;
843 else if (left->Depth == right->Depth)
844 if (left->NumSuccsLeft > right->NumSuccsLeft)
845 return true;
846 else if (left->NumSuccsLeft == right->NumSuccsLeft)
847 if (left->CycleBound > right->CycleBound)
848 return true;
849 return false;
850}
851
852/// CalcNodePriority - Priority is the Sethi Ullman number.
853/// Smaller number is the higher priority.
854template<class SF>
855int TDRegReductionPriorityQueue<SF>::CalcNodePriority(const SUnit *SU) {
856 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
857 if (SethiUllmanNumber != 0)
858 return SethiUllmanNumber;
859
860 unsigned Opc = SU->Node->getOpcode();
861 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
862 SethiUllmanNumber = INT_MAX - 10;
863 else if (SU->NumSuccsLeft == 0)
864 // If SU does not have a use, i.e. it doesn't produce a value that would
865 // be consumed (e.g. store), then it terminates a chain of computation.
866 // Give it a small SethiUllman number so it will be scheduled right before its
867 // predecessors that it doesn't lengthen their live ranges.
868 SethiUllmanNumber = INT_MIN + 10;
869 else if (SU->NumPredsLeft == 0 &&
870 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
871 SethiUllmanNumber = 1;
872 else {
873 int Extra = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +0000874 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
875 I != E; ++I) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000876 if (I->second) continue; // ignore chain preds
877 SUnit *PredSU = I->first;
878 int PredSethiUllman = CalcNodePriority(PredSU);
879 if (PredSethiUllman > SethiUllmanNumber) {
880 SethiUllmanNumber = PredSethiUllman;
881 Extra = 0;
882 } else if (PredSethiUllman == SethiUllmanNumber && !I->second)
883 Extra++;
884 }
885
886 SethiUllmanNumber += Extra;
887 }
888
889 return SethiUllmanNumber;
890}
891
892/// CalculatePriorities - Calculate priorities of all scheduling units.
893template<class SF>
894void TDRegReductionPriorityQueue<SF>::CalculatePriorities() {
895 SethiUllmanNumbers.assign(SUnits->size(), 0);
896
897 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
898 CalcNodePriority(&(*SUnits)[i]);
899}
900
901//===----------------------------------------------------------------------===//
902// Public Constructor Functions
903//===----------------------------------------------------------------------===//
904
Jim Laskey03593f72006-08-01 18:29:48 +0000905llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
906 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +0000907 MachineBasicBlock *BB) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000908 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
Jim Laskey95eda5b2006-08-01 14:21:23 +0000909 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true,
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000910 new BURegReductionPriorityQueue<bu_ls_rr_sort>(TII));
Evan Chengd38c22b2006-05-11 23:55:42 +0000911}
912
Jim Laskey03593f72006-08-01 18:29:48 +0000913llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
914 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +0000915 MachineBasicBlock *BB) {
Jim Laskey95eda5b2006-08-01 14:21:23 +0000916 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
Evan Chengd38c22b2006-05-11 23:55:42 +0000917 new TDRegReductionPriorityQueue<td_ls_rr_sort>());
918}
919