1 //===----- ScheduleDAGList.cpp - Reg pressure reduction list scheduler ----===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Evan Cheng and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements 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.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "sched"
19 #include "llvm/CodeGen/ScheduleDAG.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Target/MRegisterInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
35 static RegisterScheduler
36 burrListDAGScheduler("list-burr",
37 " Bottom-up register reduction list scheduling",
38 createBURRListDAGScheduler);
39 static RegisterScheduler
40 tdrListrDAGScheduler("list-tdrr",
41 " Top-down register reduction list scheduling",
42 createTDRRListDAGScheduler);
45 //===----------------------------------------------------------------------===//
46 /// ScheduleDAGRRList - The actual register reduction list scheduler
47 /// implementation. This supports both top-down and bottom-up scheduling.
50 class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
52 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
56 /// AvailableQueue - The priority queue to use for the available SUnits.
58 SchedulingPriorityQueue *AvailableQueue;
61 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
62 const TargetMachine &tm, bool isbottomup,
63 SchedulingPriorityQueue *availqueue)
64 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
65 AvailableQueue(availqueue) {
68 ~ScheduleDAGRRList() {
69 delete AvailableQueue;
75 void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
76 void ReleaseSucc(SUnit *SuccSU, bool isChain, unsigned CurCycle);
77 void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
78 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
79 void ListScheduleTopDown();
80 void ListScheduleBottomUp();
81 void CommuteNodesToReducePressure();
83 } // end anonymous namespace
86 /// Schedule - Schedule the DAG using list scheduling.
87 void ScheduleDAGRRList::Schedule() {
88 DEBUG(std::cerr << "********** List Scheduling **********\n");
90 // Build scheduling units.
93 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
94 SUnits[su].dumpAll(&DAG));
98 AvailableQueue->initNodes(SUnitMap, SUnits);
100 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
102 ListScheduleBottomUp();
104 ListScheduleTopDown();
106 AvailableQueue->releaseState();
108 CommuteNodesToReducePressure();
110 DEBUG(std::cerr << "*** Final schedule ***\n");
111 DEBUG(dumpSchedule());
112 DEBUG(std::cerr << "\n");
114 // Emit in scheduled order
118 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
119 /// it is not the last use of its first operand, add it to the CommuteSet if
120 /// possible. It will be commuted when it is translated to a MI.
121 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
122 std::set<SUnit *> OperandSeen;
123 for (unsigned i = Sequence.size()-1; i != 0; --i) { // Ignore first node.
124 SUnit *SU = Sequence[i];
126 if (SU->isCommutable) {
127 unsigned Opc = SU->Node->getTargetOpcode();
128 unsigned NumRes = CountResults(SU->Node);
129 unsigned NumOps = CountOperands(SU->Node);
130 for (unsigned j = 0; j != NumOps; ++j) {
131 if (TII->getOperandConstraint(Opc, j+NumRes,
132 TargetInstrInfo::TIED_TO) == -1)
135 SDNode *OpN = SU->Node->getOperand(j).Val;
136 SUnit *OpSU = SUnitMap[OpN];
137 if (OpSU && OperandSeen.count(OpSU) == 1) {
138 // Ok, so SU is not the last use of OpSU, but SU is two-address so
139 // it will clobber OpSU. Try to commute SU if no other source operands
141 bool DoCommute = true;
142 for (unsigned k = 0; k < NumOps; ++k) {
144 OpN = SU->Node->getOperand(k).Val;
145 OpSU = SUnitMap[OpN];
146 if (OpSU && OperandSeen.count(OpSU) == 1) {
153 CommuteSet.insert(SU->Node);
156 // Only look at the first use&def node for now.
161 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
164 OperandSeen.insert(I->first);
169 //===----------------------------------------------------------------------===//
170 // Bottom-Up Scheduling
171 //===----------------------------------------------------------------------===//
173 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
174 /// the Available queue is the count reaches zero. Also update its cycle bound.
175 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
177 // FIXME: the distance between two nodes is not always == the predecessor's
178 // latency. For example, the reader can very well read the register written
179 // by the predecessor later than the issue cycle. It also depends on the
180 // interrupt model (drain vs. freeze).
181 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
184 PredSU->NumSuccsLeft--;
186 PredSU->NumChainSuccsLeft--;
189 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
190 std::cerr << "*** List scheduling failed! ***\n";
192 std::cerr << " has been released too many times!\n";
197 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
198 // EntryToken has to go last! Special case it here.
199 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
200 PredSU->isAvailable = true;
201 AvailableQueue->push(PredSU);
206 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
207 /// count of its predecessors. If a predecessor pending count is zero, add it to
208 /// the Available queue.
209 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
210 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
211 DEBUG(SU->dump(&DAG));
212 SU->Cycle = CurCycle;
214 AvailableQueue->ScheduledNode(SU);
215 Sequence.push_back(SU);
217 // Bottom up: release predecessors
218 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
220 ReleasePred(I->first, I->second, CurCycle);
221 SU->isScheduled = true;
224 /// isReady - True if node's lower cycle bound is less or equal to the current
225 /// scheduling cycle. Always true if all nodes have uniform latency 1.
226 static inline bool isReady(SUnit *SU, unsigned CurCycle) {
227 return SU->CycleBound <= CurCycle;
230 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
232 void ScheduleDAGRRList::ListScheduleBottomUp() {
233 unsigned CurCycle = 0;
234 // Add root to Available queue.
235 AvailableQueue->push(SUnitMap[DAG.getRoot().Val]);
237 // While Available queue is not empty, grab the node with the highest
238 // priority. If it is not ready put it back. Schedule the node.
239 std::vector<SUnit*> NotReady;
240 while (!AvailableQueue->empty()) {
241 SUnit *CurNode = AvailableQueue->pop();
242 while (CurNode && !isReady(CurNode, CurCycle)) {
243 NotReady.push_back(CurNode);
244 CurNode = AvailableQueue->pop();
247 // Add the nodes that aren't ready back onto the available list.
248 AvailableQueue->push_all(NotReady);
252 ScheduleNodeBottomUp(CurNode, CurCycle);
256 // Add entry node last
257 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
258 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
259 Sequence.push_back(Entry);
262 // Reverse the order if it is bottom up.
263 std::reverse(Sequence.begin(), Sequence.end());
267 // Verify that all SUnits were scheduled.
268 bool AnyNotSched = false;
269 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
270 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
272 std::cerr << "*** List scheduling failed! ***\n";
273 SUnits[i].dump(&DAG);
274 std::cerr << "has not been scheduled!\n";
278 assert(!AnyNotSched);
282 //===----------------------------------------------------------------------===//
283 // Top-Down Scheduling
284 //===----------------------------------------------------------------------===//
286 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
287 /// the PendingQueue if the count reaches zero.
288 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
290 // FIXME: the distance between two nodes is not always == the predecessor's
291 // latency. For example, the reader can very well read the register written
292 // by the predecessor later than the issue cycle. It also depends on the
293 // interrupt model (drain vs. freeze).
294 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
297 SuccSU->NumPredsLeft--;
299 SuccSU->NumChainPredsLeft--;
302 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
303 std::cerr << "*** List scheduling failed! ***\n";
305 std::cerr << " has been released too many times!\n";
310 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
311 SuccSU->isAvailable = true;
312 AvailableQueue->push(SuccSU);
317 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
318 /// count of its successors. If a successor pending count is zero, add it to
319 /// the Available queue.
320 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
321 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
322 DEBUG(SU->dump(&DAG));
323 SU->Cycle = CurCycle;
325 AvailableQueue->ScheduledNode(SU);
326 Sequence.push_back(SU);
328 // Top down: release successors
329 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
331 ReleaseSucc(I->first, I->second, CurCycle);
332 SU->isScheduled = true;
335 void ScheduleDAGRRList::ListScheduleTopDown() {
336 unsigned CurCycle = 0;
337 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
339 // All leaves to Available queue.
340 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
341 // It is available if it has no predecessors.
342 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
343 AvailableQueue->push(&SUnits[i]);
344 SUnits[i].isAvailable = true;
348 // Emit the entry node first.
349 ScheduleNodeTopDown(Entry, CurCycle);
352 // While Available queue is not empty, grab the node with the highest
353 // priority. If it is not ready put it back. Schedule the node.
354 std::vector<SUnit*> NotReady;
355 while (!AvailableQueue->empty()) {
356 SUnit *CurNode = AvailableQueue->pop();
357 while (CurNode && !isReady(CurNode, CurCycle)) {
358 NotReady.push_back(CurNode);
359 CurNode = AvailableQueue->pop();
362 // Add the nodes that aren't ready back onto the available list.
363 AvailableQueue->push_all(NotReady);
367 ScheduleNodeTopDown(CurNode, CurCycle);
373 // Verify that all SUnits were scheduled.
374 bool AnyNotSched = false;
375 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
376 if (!SUnits[i].isScheduled) {
378 std::cerr << "*** List scheduling failed! ***\n";
379 SUnits[i].dump(&DAG);
380 std::cerr << "has not been scheduled!\n";
384 assert(!AnyNotSched);
390 //===----------------------------------------------------------------------===//
391 // RegReductionPriorityQueue Implementation
392 //===----------------------------------------------------------------------===//
394 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
395 // to reduce register pressure.
399 class RegReductionPriorityQueue;
401 /// Sorting functions for the Available queue.
402 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
403 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
404 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
405 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
407 bool operator()(const SUnit* left, const SUnit* right) const;
410 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
411 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
412 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
413 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
415 bool operator()(const SUnit* left, const SUnit* right) const;
417 } // end anonymous namespace
421 class VISIBILITY_HIDDEN RegReductionPriorityQueue
422 : public SchedulingPriorityQueue {
423 std::priority_queue<SUnit*, std::vector<SUnit*>, SF> Queue;
426 RegReductionPriorityQueue() :
429 virtual void initNodes(std::map<SDNode*, SUnit*> &sumap,
430 std::vector<SUnit> &sunits) {}
431 virtual void releaseState() {}
433 virtual int getSethiUllmanNumber(unsigned NodeNum) const {
437 bool empty() const { return Queue.empty(); }
439 void push(SUnit *U) {
442 void push_all(const std::vector<SUnit *> &Nodes) {
443 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
444 Queue.push(Nodes[i]);
448 if (empty()) return NULL;
449 SUnit *V = Queue.top();
454 virtual bool isDUOperand(const SUnit *SU1, const SUnit *SU2) {
460 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
461 : public RegReductionPriorityQueue<SF> {
462 // SUnitMap SDNode to SUnit mapping (n -> 1).
463 std::map<SDNode*, SUnit*> *SUnitMap;
465 // SUnits - The SUnits for the current graph.
466 const std::vector<SUnit> *SUnits;
468 // SethiUllmanNumbers - The SethiUllman number for each node.
469 std::vector<int> SethiUllmanNumbers;
471 const TargetInstrInfo *TII;
473 BURegReductionPriorityQueue(const TargetInstrInfo *tii)
476 void initNodes(std::map<SDNode*, SUnit*> &sumap,
477 std::vector<SUnit> &sunits) {
480 // Add pseudo dependency edges for two-address nodes.
481 AddPseudoTwoAddrDeps();
482 // Calculate node priorities.
483 CalculatePriorities();
486 void releaseState() {
488 SethiUllmanNumbers.clear();
491 int getSethiUllmanNumber(unsigned NodeNum) const {
492 assert(NodeNum < SethiUllmanNumbers.size());
493 return SethiUllmanNumbers[NodeNum];
496 bool isDUOperand(const SUnit *SU1, const SUnit *SU2) {
497 unsigned Opc = SU1->Node->getTargetOpcode();
498 unsigned NumRes = ScheduleDAG::CountResults(SU1->Node);
499 unsigned NumOps = ScheduleDAG::CountOperands(SU1->Node);
500 for (unsigned i = 0; i != NumOps; ++i) {
501 if (TII->getOperandConstraint(Opc, i+NumRes,
502 TargetInstrInfo::TIED_TO) == -1)
504 if (SU1->Node->getOperand(i).isOperand(SU2->Node))
510 bool canClobber(SUnit *SU, SUnit *Op);
511 void AddPseudoTwoAddrDeps();
512 void CalculatePriorities();
513 int CalcNodePriority(const SUnit *SU);
518 class TDRegReductionPriorityQueue : public RegReductionPriorityQueue<SF> {
519 // SUnitMap SDNode to SUnit mapping (n -> 1).
520 std::map<SDNode*, SUnit*> *SUnitMap;
522 // SUnits - The SUnits for the current graph.
523 const std::vector<SUnit> *SUnits;
525 // SethiUllmanNumbers - The SethiUllman number for each node.
526 std::vector<int> SethiUllmanNumbers;
529 TDRegReductionPriorityQueue() {}
531 void initNodes(std::map<SDNode*, SUnit*> &sumap,
532 std::vector<SUnit> &sunits) {
535 // Calculate node priorities.
536 CalculatePriorities();
539 void releaseState() {
541 SethiUllmanNumbers.clear();
544 int getSethiUllmanNumber(unsigned NodeNum) const {
545 assert(NodeNum < SethiUllmanNumbers.size());
546 return SethiUllmanNumbers[NodeNum];
550 void CalculatePriorities();
551 int CalcNodePriority(const SUnit *SU);
555 static bool isFloater(const SUnit *SU) {
556 if (SU->Node->isTargetOpcode()) {
557 if (SU->NumPreds == 0)
559 if (SU->NumPreds == 1) {
560 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
562 if (I->second) continue;
564 SUnit *PredSU = I->first;
565 unsigned Opc = PredSU->Node->getOpcode();
566 if (Opc != ISD::EntryToken && Opc != ISD::TokenFactor &&
567 Opc != ISD::CopyToReg)
576 static bool isSimpleFloaterUse(const SUnit *SU) {
578 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
580 if (I->second) continue;
583 if (!isFloater(I->first))
590 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
591 unsigned LeftNum = left->NodeNum;
592 unsigned RightNum = right->NodeNum;
593 bool LIsTarget = left->Node->isTargetOpcode();
594 bool RIsTarget = right->Node->isTargetOpcode();
595 int LPriority = SPQ->getSethiUllmanNumber(LeftNum);
596 int RPriority = SPQ->getSethiUllmanNumber(RightNum);
600 // Schedule floaters (e.g. load from some constant address) and those nodes
601 // with a single predecessor each first. They maintain / reduce register
603 if (isFloater(left) || isSimpleFloaterUse(left))
605 if (isFloater(right) || isSimpleFloaterUse(right))
608 // Special tie breaker: if two nodes share a operand, the one that use it
609 // as a def&use operand is preferred.
610 if (LIsTarget && RIsTarget) {
611 if (left->isTwoAddress && !right->isTwoAddress) {
612 if (SPQ->isDUOperand(left, right))
615 if (!left->isTwoAddress && right->isTwoAddress) {
616 if (SPQ->isDUOperand(right, left))
621 if (LPriority+LBonus < RPriority+RBonus)
623 else if (LPriority+LBonus == RPriority+RBonus)
624 if (left->Height > right->Height)
626 else if (left->Height == right->Height)
627 if (left->Depth < right->Depth)
629 else if (left->Depth == right->Depth)
630 if (left->CycleBound > right->CycleBound)
635 static inline bool isCopyFromLiveIn(const SUnit *SU) {
636 SDNode *N = SU->Node;
637 return N->getOpcode() == ISD::CopyFromReg &&
638 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
641 // FIXME: This is probably too slow!
642 static void isReachable(SUnit *SU, SUnit *TargetSU,
643 std::set<SUnit *> &Visited, bool &Reached) {
645 if (SU == TargetSU) {
649 if (!Visited.insert(SU).second) return;
651 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); I != E;
653 isReachable(I->first, TargetSU, Visited, Reached);
656 static bool isReachable(SUnit *SU, SUnit *TargetSU) {
657 std::set<SUnit *> Visited;
658 bool Reached = false;
659 isReachable(SU, TargetSU, Visited, Reached);
664 bool BURegReductionPriorityQueue<SF>::canClobber(SUnit *SU, SUnit *Op) {
665 if (SU->isTwoAddress) {
666 unsigned Opc = SU->Node->getTargetOpcode();
667 unsigned NumRes = ScheduleDAG::CountResults(SU->Node);
668 unsigned NumOps = ScheduleDAG::CountOperands(SU->Node);
669 for (unsigned i = 0; i != NumOps; ++i) {
670 if (TII->getOperandConstraint(Opc, i+NumRes,
671 TargetInstrInfo::TIED_TO) != -1) {
672 SDNode *DU = SU->Node->getOperand(i).Val;
673 if (Op == (*SUnitMap)[DU])
682 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
683 /// it as a def&use operand. Add a pseudo control edge from it to the other
684 /// node (if it won't create a cycle) so the two-address one will be scheduled
685 /// first (lower in the schedule).
687 void BURegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
689 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
690 SUnit *SU = (SUnit *)&((*SUnits)[i]);
691 if (!SU->isTwoAddress)
694 SDNode *Node = SU->Node;
695 if (!Node->isTargetOpcode())
698 unsigned Opc = Node->getTargetOpcode();
699 unsigned NumRes = ScheduleDAG::CountResults(Node);
700 unsigned NumOps = ScheduleDAG::CountOperands(Node);
701 for (unsigned j = 0; j != NumOps; ++j) {
702 if (TII->getOperandConstraint(Opc, j+NumRes,
703 TargetInstrInfo::TIED_TO) != -1) {
704 SDNode *DU = SU->Node->getOperand(j).Val;
705 SUnit *DUSU = (*SUnitMap)[DU];
706 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
708 if (I->second) continue;
709 SUnit *SuccSU = I->first;
711 (!canClobber(SuccSU, DUSU) ||
712 (!SU->isCommutable && SuccSU->isCommutable))){
713 if (SuccSU->Depth == SU->Depth && !isReachable(SuccSU, SU)) {
714 DEBUG(std::cerr << "Adding an edge from SU # " << SU->NodeNum
715 << " to SU #" << SuccSU->NodeNum << "\n");
716 if (SU->addPred(SuccSU, true))
717 SU->NumChainPredsLeft++;
718 if (SuccSU->addSucc(SU, true))
719 SuccSU->NumChainSuccsLeft++;
727 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
728 SUnit *SU = (SUnit *)&((*SUnits)[i]);
729 SDNode *Node = SU->Node;
730 if (!Node->isTargetOpcode())
733 if (SU->isTwoAddress) {
734 SUnit *DUSU = getDefUsePredecessor(SU, TII);
737 for (SUnit::succ_iterator I = DUSU->Succs.begin(), E = DUSU->Succs.end();
739 if (I->second) continue;
740 SUnit *SuccSU = I->first;
742 (!canClobber(SuccSU, DUSU, TII) ||
743 (!SU->isCommutable && SuccSU->isCommutable))){
744 if (SuccSU->Depth == SU->Depth && !isReachable(SuccSU, SU)) {
745 DEBUG(std::cerr << "Adding an edge from SU # " << SU->NodeNum
746 << " to SU #" << SuccSU->NodeNum << "\n");
747 if (SU->addPred(SuccSU, true))
748 SU->NumChainPredsLeft++;
749 if (SuccSU->addSucc(SU, true))
750 SuccSU->NumChainSuccsLeft++;
759 /// CalcNodePriority - Priority is the Sethi Ullman number.
760 /// Smaller number is the higher priority.
762 int BURegReductionPriorityQueue<SF>::CalcNodePriority(const SUnit *SU) {
763 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
764 if (SethiUllmanNumber != 0)
765 return SethiUllmanNumber;
767 unsigned Opc = SU->Node->getOpcode();
768 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
769 // CopyFromReg should be close to its def because it restricts allocation
770 // choices. But if it is a livein then perhaps we want it closer to the
771 // uses so it can be coalesced.
772 SethiUllmanNumber = INT_MIN + 10;
773 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
774 // CopyToReg should be close to its uses to facilitate coalescing and avoid
776 SethiUllmanNumber = INT_MAX - 10;
777 else if (SU->NumSuccsLeft == 0)
778 // If SU does not have a use, i.e. it doesn't produce a value that would
779 // be consumed (e.g. store), then it terminates a chain of computation.
780 // Give it a small SethiUllman number so it will be scheduled right before its
781 // predecessors that it doesn't lengthen their live ranges.
782 SethiUllmanNumber = INT_MIN + 10;
783 else if (SU->NumPredsLeft == 0)
784 // If SU does not have a def, schedule it close to its uses because it does
785 // not lengthen any live ranges.
786 SethiUllmanNumber = INT_MAX - 10;
789 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
791 if (I->second) continue; // ignore chain preds
792 SUnit *PredSU = I->first;
793 int PredSethiUllman = CalcNodePriority(PredSU);
794 if (PredSethiUllman > SethiUllmanNumber) {
795 SethiUllmanNumber = PredSethiUllman;
797 } else if (PredSethiUllman == SethiUllmanNumber && !I->second)
801 SethiUllmanNumber += Extra;
804 return SethiUllmanNumber;
807 /// CalculatePriorities - Calculate priorities of all scheduling units.
809 void BURegReductionPriorityQueue<SF>::CalculatePriorities() {
810 SethiUllmanNumbers.assign(SUnits->size(), 0);
812 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
813 CalcNodePriority(&(*SUnits)[i]);
816 static unsigned SumOfUnscheduledPredsOfSuccs(const SUnit *SU) {
818 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
820 SUnit *SuccSU = I->first;
821 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
822 EE = SuccSU->Preds.end(); II != EE; ++II) {
823 SUnit *PredSU = II->first;
824 if (!PredSU->isScheduled)
834 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
835 unsigned LeftNum = left->NodeNum;
836 unsigned RightNum = right->NodeNum;
837 int LPriority = SPQ->getSethiUllmanNumber(LeftNum);
838 int RPriority = SPQ->getSethiUllmanNumber(RightNum);
839 bool LIsTarget = left->Node->isTargetOpcode();
840 bool RIsTarget = right->Node->isTargetOpcode();
841 bool LIsFloater = LIsTarget && left->NumPreds == 0;
842 bool RIsFloater = RIsTarget && right->NumPreds == 0;
843 unsigned LBonus = (SumOfUnscheduledPredsOfSuccs(left) == 1) ? 2 : 0;
844 unsigned RBonus = (SumOfUnscheduledPredsOfSuccs(right) == 1) ? 2 : 0;
846 if (left->NumSuccs == 0 && right->NumSuccs != 0)
848 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
851 // Special tie breaker: if two nodes share a operand, the one that use it
852 // as a def&use operand is preferred.
853 if (LIsTarget && RIsTarget) {
854 if (left->isTwoAddress && !right->isTwoAddress) {
855 SDNode *DUNode = left->Node->getOperand(0).Val;
856 if (DUNode->isOperand(right->Node))
859 if (!left->isTwoAddress && right->isTwoAddress) {
860 SDNode *DUNode = right->Node->getOperand(0).Val;
861 if (DUNode->isOperand(left->Node))
869 if (left->NumSuccs == 1)
871 if (right->NumSuccs == 1)
874 if (LPriority+LBonus < RPriority+RBonus)
876 else if (LPriority == RPriority)
877 if (left->Depth < right->Depth)
879 else if (left->Depth == right->Depth)
880 if (left->NumSuccsLeft > right->NumSuccsLeft)
882 else if (left->NumSuccsLeft == right->NumSuccsLeft)
883 if (left->CycleBound > right->CycleBound)
888 /// CalcNodePriority - Priority is the Sethi Ullman number.
889 /// Smaller number is the higher priority.
891 int TDRegReductionPriorityQueue<SF>::CalcNodePriority(const SUnit *SU) {
892 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
893 if (SethiUllmanNumber != 0)
894 return SethiUllmanNumber;
896 unsigned Opc = SU->Node->getOpcode();
897 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
898 SethiUllmanNumber = INT_MAX - 10;
899 else if (SU->NumSuccsLeft == 0)
900 // If SU does not have a use, i.e. it doesn't produce a value that would
901 // be consumed (e.g. store), then it terminates a chain of computation.
902 // Give it a small SethiUllman number so it will be scheduled right before its
903 // predecessors that it doesn't lengthen their live ranges.
904 SethiUllmanNumber = INT_MIN + 10;
905 else if (SU->NumPredsLeft == 0 &&
906 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
907 SethiUllmanNumber = 1;
910 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
912 if (I->second) continue; // ignore chain preds
913 SUnit *PredSU = I->first;
914 int PredSethiUllman = CalcNodePriority(PredSU);
915 if (PredSethiUllman > SethiUllmanNumber) {
916 SethiUllmanNumber = PredSethiUllman;
918 } else if (PredSethiUllman == SethiUllmanNumber && !I->second)
922 SethiUllmanNumber += Extra;
925 return SethiUllmanNumber;
928 /// CalculatePriorities - Calculate priorities of all scheduling units.
930 void TDRegReductionPriorityQueue<SF>::CalculatePriorities() {
931 SethiUllmanNumbers.assign(SUnits->size(), 0);
933 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
934 CalcNodePriority(&(*SUnits)[i]);
937 //===----------------------------------------------------------------------===//
938 // Public Constructor Functions
939 //===----------------------------------------------------------------------===//
941 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
943 MachineBasicBlock *BB) {
944 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
945 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true,
946 new BURegReductionPriorityQueue<bu_ls_rr_sort>(TII));
949 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
951 MachineBasicBlock *BB) {
952 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
953 new TDRegReductionPriorityQueue<td_ls_rr_sort>());