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 "pre-RA-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"
31 #include "llvm/Support/CommandLine.h"
34 static RegisterScheduler
35 burrListDAGScheduler("list-burr",
36 " Bottom-up register reduction list scheduling",
37 createBURRListDAGScheduler);
38 static RegisterScheduler
39 tdrListrDAGScheduler("list-tdrr",
40 " Top-down register reduction list scheduling",
41 createTDRRListDAGScheduler);
44 //===----------------------------------------------------------------------===//
45 /// ScheduleDAGRRList - The actual register reduction list scheduler
46 /// implementation. This supports both top-down and bottom-up scheduling.
48 class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
50 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
54 /// AvailableQueue - The priority queue to use for the available SUnits.
56 SchedulingPriorityQueue *AvailableQueue;
59 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
60 const TargetMachine &tm, bool isbottomup,
61 SchedulingPriorityQueue *availqueue)
62 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
63 AvailableQueue(availqueue) {
66 ~ScheduleDAGRRList() {
67 delete AvailableQueue;
73 void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
74 void ReleaseSucc(SUnit *SuccSU, bool isChain, unsigned CurCycle);
75 void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
76 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
77 void ListScheduleTopDown();
78 void ListScheduleBottomUp();
79 void CommuteNodesToReducePressure();
81 } // end anonymous namespace
84 /// Schedule - Schedule the DAG using list scheduling.
85 void ScheduleDAGRRList::Schedule() {
86 DOUT << "********** List Scheduling **********\n";
88 // Build scheduling units.
91 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
92 SUnits[su].dumpAll(&DAG));
96 AvailableQueue->initNodes(SUnitMap, SUnits);
98 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
100 ListScheduleBottomUp();
102 ListScheduleTopDown();
104 AvailableQueue->releaseState();
106 CommuteNodesToReducePressure();
108 DOUT << "*** Final schedule ***\n";
109 DEBUG(dumpSchedule());
112 // Emit in scheduled order
116 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
117 /// it is not the last use of its first operand, add it to the CommuteSet if
118 /// possible. It will be commuted when it is translated to a MI.
119 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
120 SmallPtrSet<SUnit*, 4> OperandSeen;
121 for (unsigned i = Sequence.size()-1; i != 0; --i) { // Ignore first node.
122 SUnit *SU = Sequence[i];
124 if (SU->isCommutable) {
125 unsigned Opc = SU->Node->getTargetOpcode();
126 unsigned NumRes = CountResults(SU->Node);
127 unsigned NumOps = CountOperands(SU->Node);
128 for (unsigned j = 0; j != NumOps; ++j) {
129 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) == -1)
132 SDNode *OpN = SU->Node->getOperand(j).Val;
133 SUnit *OpSU = SUnitMap[OpN];
134 if (OpSU && OperandSeen.count(OpSU) == 1) {
135 // Ok, so SU is not the last use of OpSU, but SU is two-address so
136 // it will clobber OpSU. Try to commute SU if no other source operands
138 bool DoCommute = true;
139 for (unsigned k = 0; k < NumOps; ++k) {
141 OpN = SU->Node->getOperand(k).Val;
142 OpSU = SUnitMap[OpN];
143 if (OpSU && OperandSeen.count(OpSU) == 1) {
150 CommuteSet.insert(SU->Node);
153 // Only look at the first use&def node for now.
158 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
161 OperandSeen.insert(I->first);
166 //===----------------------------------------------------------------------===//
167 // Bottom-Up Scheduling
168 //===----------------------------------------------------------------------===//
170 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
171 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
172 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
174 // FIXME: the distance between two nodes is not always == the predecessor's
175 // latency. For example, the reader can very well read the register written
176 // by the predecessor later than the issue cycle. It also depends on the
177 // interrupt model (drain vs. freeze).
178 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
181 PredSU->NumSuccsLeft--;
183 PredSU->NumChainSuccsLeft--;
186 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
187 cerr << "*** List scheduling failed! ***\n";
189 cerr << " has been released too many times!\n";
194 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
195 // EntryToken has to go last! Special case it here.
196 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
197 PredSU->isAvailable = true;
198 AvailableQueue->push(PredSU);
203 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
204 /// count of its predecessors. If a predecessor pending count is zero, add it to
205 /// the Available queue.
206 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
207 DOUT << "*** Scheduling [" << CurCycle << "]: ";
208 DEBUG(SU->dump(&DAG));
209 SU->Cycle = CurCycle;
211 AvailableQueue->ScheduledNode(SU);
212 Sequence.push_back(SU);
214 // Bottom up: release predecessors
215 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
217 ReleasePred(I->first, I->second, CurCycle);
218 SU->isScheduled = true;
221 /// isReady - True if node's lower cycle bound is less or equal to the current
222 /// scheduling cycle. Always true if all nodes have uniform latency 1.
223 static inline bool isReady(SUnit *SU, unsigned CurCycle) {
224 return SU->CycleBound <= CurCycle;
227 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
229 void ScheduleDAGRRList::ListScheduleBottomUp() {
230 unsigned CurCycle = 0;
231 // Add root to Available queue.
232 AvailableQueue->push(SUnitMap[DAG.getRoot().Val]);
234 // While Available queue is not empty, grab the node with the highest
235 // priority. If it is not ready put it back. Schedule the node.
236 std::vector<SUnit*> NotReady;
237 while (!AvailableQueue->empty()) {
238 SUnit *CurNode = AvailableQueue->pop();
239 while (CurNode && !isReady(CurNode, CurCycle)) {
240 NotReady.push_back(CurNode);
241 CurNode = AvailableQueue->pop();
244 // Add the nodes that aren't ready back onto the available list.
245 AvailableQueue->push_all(NotReady);
249 ScheduleNodeBottomUp(CurNode, CurCycle);
253 // Add entry node last
254 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
255 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
256 Sequence.push_back(Entry);
259 // Reverse the order if it is bottom up.
260 std::reverse(Sequence.begin(), Sequence.end());
264 // Verify that all SUnits were scheduled.
265 bool AnyNotSched = false;
266 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
267 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
269 cerr << "*** List scheduling failed! ***\n";
270 SUnits[i].dump(&DAG);
271 cerr << "has not been scheduled!\n";
275 assert(!AnyNotSched);
279 //===----------------------------------------------------------------------===//
280 // Top-Down Scheduling
281 //===----------------------------------------------------------------------===//
283 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
284 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
285 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
287 // FIXME: the distance between two nodes is not always == the predecessor's
288 // latency. For example, the reader can very well read the register written
289 // by the predecessor later than the issue cycle. It also depends on the
290 // interrupt model (drain vs. freeze).
291 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
294 SuccSU->NumPredsLeft--;
296 SuccSU->NumChainPredsLeft--;
299 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
300 cerr << "*** List scheduling failed! ***\n";
302 cerr << " has been released too many times!\n";
307 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
308 SuccSU->isAvailable = true;
309 AvailableQueue->push(SuccSU);
314 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
315 /// count of its successors. If a successor pending count is zero, add it to
316 /// the Available queue.
317 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
318 DOUT << "*** Scheduling [" << CurCycle << "]: ";
319 DEBUG(SU->dump(&DAG));
320 SU->Cycle = CurCycle;
322 AvailableQueue->ScheduledNode(SU);
323 Sequence.push_back(SU);
325 // Top down: release successors
326 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
328 ReleaseSucc(I->first, I->second, CurCycle);
329 SU->isScheduled = true;
332 /// ListScheduleTopDown - The main loop of list scheduling for top-down
334 void ScheduleDAGRRList::ListScheduleTopDown() {
335 unsigned CurCycle = 0;
336 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
338 // All leaves to Available queue.
339 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
340 // It is available if it has no predecessors.
341 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
342 AvailableQueue->push(&SUnits[i]);
343 SUnits[i].isAvailable = true;
347 // Emit the entry node first.
348 ScheduleNodeTopDown(Entry, CurCycle);
351 // While Available queue is not empty, grab the node with the highest
352 // priority. If it is not ready put it back. Schedule the node.
353 std::vector<SUnit*> NotReady;
354 while (!AvailableQueue->empty()) {
355 SUnit *CurNode = AvailableQueue->pop();
356 while (CurNode && !isReady(CurNode, CurCycle)) {
357 NotReady.push_back(CurNode);
358 CurNode = AvailableQueue->pop();
361 // Add the nodes that aren't ready back onto the available list.
362 AvailableQueue->push_all(NotReady);
366 ScheduleNodeTopDown(CurNode, CurCycle);
372 // Verify that all SUnits were scheduled.
373 bool AnyNotSched = false;
374 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
375 if (!SUnits[i].isScheduled) {
377 cerr << "*** List scheduling failed! ***\n";
378 SUnits[i].dump(&DAG);
379 cerr << "has not been scheduled!\n";
383 assert(!AnyNotSched);
389 //===----------------------------------------------------------------------===//
390 // RegReductionPriorityQueue Implementation
391 //===----------------------------------------------------------------------===//
393 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
394 // to reduce register pressure.
398 class RegReductionPriorityQueue;
400 /// Sorting functions for the Available queue.
401 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
402 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
403 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
404 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
406 bool operator()(const SUnit* left, const SUnit* right) const;
409 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
410 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
411 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
412 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
414 bool operator()(const SUnit* left, const SUnit* right) const;
416 } // end anonymous namespace
418 static inline bool isCopyFromLiveIn(const SUnit *SU) {
419 SDNode *N = SU->Node;
420 return N->getOpcode() == ISD::CopyFromReg &&
421 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
426 class VISIBILITY_HIDDEN RegReductionPriorityQueue
427 : public SchedulingPriorityQueue {
428 std::priority_queue<SUnit*, std::vector<SUnit*>, SF> Queue;
431 RegReductionPriorityQueue() :
434 virtual void initNodes(DenseMap<SDNode*, SUnit*> &sumap,
435 std::vector<SUnit> &sunits) {}
436 virtual void releaseState() {}
438 virtual unsigned getNodePriority(const SUnit *SU) const {
442 bool empty() const { return Queue.empty(); }
444 void push(SUnit *U) {
447 void push_all(const std::vector<SUnit *> &Nodes) {
448 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
449 Queue.push(Nodes[i]);
453 if (empty()) return NULL;
454 SUnit *V = Queue.top();
459 virtual bool isDUOperand(const SUnit *SU1, const SUnit *SU2) {
465 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
466 : public RegReductionPriorityQueue<SF> {
467 // SUnitMap SDNode to SUnit mapping (n -> 1).
468 DenseMap<SDNode*, SUnit*> *SUnitMap;
470 // SUnits - The SUnits for the current graph.
471 const std::vector<SUnit> *SUnits;
473 // SethiUllmanNumbers - The SethiUllman number for each node.
474 std::vector<unsigned> SethiUllmanNumbers;
476 const TargetInstrInfo *TII;
478 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii)
481 void initNodes(DenseMap<SDNode*, SUnit*> &sumap,
482 std::vector<SUnit> &sunits) {
485 // Add pseudo dependency edges for two-address nodes.
486 AddPseudoTwoAddrDeps();
487 // Calculate node priorities.
488 CalculateSethiUllmanNumbers();
491 void releaseState() {
493 SethiUllmanNumbers.clear();
496 unsigned getNodePriority(const SUnit *SU) const {
497 assert(SU->NodeNum < SethiUllmanNumbers.size());
498 unsigned Opc = SU->Node->getOpcode();
499 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
500 // CopyFromReg should be close to its def because it restricts
501 // allocation choices. But if it is a livein then perhaps we want it
502 // closer to its uses so it can be coalesced.
504 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
505 // CopyToReg should be close to its uses to facilitate coalescing and
508 else if (SU->NumSuccs == 0)
509 // If SU does not have a use, i.e. it doesn't produce a value that would
510 // be consumed (e.g. store), then it terminates a chain of computation.
511 // Give it a large SethiUllman number so it will be scheduled right
512 // before its predecessors that it doesn't lengthen their live ranges.
514 else if (SU->NumPreds == 0)
515 // If SU does not have a def, schedule it close to its uses because it
516 // does not lengthen any live ranges.
519 return SethiUllmanNumbers[SU->NodeNum];
522 bool isDUOperand(const SUnit *SU1, const SUnit *SU2) {
523 unsigned Opc = SU1->Node->getTargetOpcode();
524 unsigned NumRes = ScheduleDAG::CountResults(SU1->Node);
525 unsigned NumOps = ScheduleDAG::CountOperands(SU1->Node);
526 for (unsigned i = 0; i != NumOps; ++i) {
527 if (TII->getOperandConstraint(Opc, i+NumRes, TOI::TIED_TO) == -1)
529 if (SU1->Node->getOperand(i).isOperand(SU2->Node))
535 bool canClobber(SUnit *SU, SUnit *Op);
536 void AddPseudoTwoAddrDeps();
537 void CalculateSethiUllmanNumbers();
538 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
543 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
544 : public RegReductionPriorityQueue<SF> {
545 // SUnitMap SDNode to SUnit mapping (n -> 1).
546 DenseMap<SDNode*, SUnit*> *SUnitMap;
548 // SUnits - The SUnits for the current graph.
549 const std::vector<SUnit> *SUnits;
551 // SethiUllmanNumbers - The SethiUllman number for each node.
552 std::vector<unsigned> SethiUllmanNumbers;
555 TDRegReductionPriorityQueue() {}
557 void initNodes(DenseMap<SDNode*, SUnit*> &sumap,
558 std::vector<SUnit> &sunits) {
561 // Calculate node priorities.
562 CalculateSethiUllmanNumbers();
565 void releaseState() {
567 SethiUllmanNumbers.clear();
570 unsigned getNodePriority(const SUnit *SU) const {
571 assert(SU->NodeNum < SethiUllmanNumbers.size());
572 return SethiUllmanNumbers[SU->NodeNum];
576 void CalculateSethiUllmanNumbers();
577 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
581 /// closestSucc - Returns the scheduled cycle of the successor which is
582 /// closet to the current cycle.
583 static unsigned closestSucc(const SUnit *SU) {
584 unsigned MaxCycle = 0;
585 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
587 unsigned Cycle = I->first->Cycle;
588 // If there are bunch of CopyToRegs stacked up, they should be considered
589 // to be at the same position.
590 if (I->first->Node->getOpcode() == ISD::CopyToReg)
591 Cycle = closestSucc(I->first)+1;
592 if (Cycle > MaxCycle)
598 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
599 /// for scratch registers. Live-in operands and live-out results don't count
600 /// since they are "fixed".
601 static unsigned calcMaxScratches(const SUnit *SU) {
602 unsigned Scratches = 0;
603 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
605 if (I->second) continue; // ignore chain preds
606 if (I->first->Node->getOpcode() != ISD::CopyFromReg)
609 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
611 if (I->second) continue; // ignore chain succs
612 if (I->first->Node->getOpcode() != ISD::CopyToReg)
619 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
620 // There used to be a special tie breaker here that looked for
621 // two-address instructions and preferred the instruction with a
622 // def&use operand. The special case triggered diagnostics when
623 // _GLIBCXX_DEBUG was enabled because it broke the strict weak
624 // ordering that priority_queue requires. It didn't help much anyway
625 // because AddPseudoTwoAddrDeps already covers many of the cases
626 // where it would have applied. In addition, it's counter-intuitive
627 // that a tie breaker would be the first thing attempted. There's a
628 // "real" tie breaker below that is the operation of last resort.
629 // The fact that the "special tie breaker" would trigger when there
630 // wasn't otherwise a tie is what broke the strict weak ordering
633 unsigned LPriority = SPQ->getNodePriority(left);
634 unsigned RPriority = SPQ->getNodePriority(right);
635 if (LPriority > RPriority)
637 else if (LPriority == RPriority) {
638 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
643 // and the following instructions are both ready.
647 // Then schedule t2 = op first.
654 // This creates more short live intervals.
655 unsigned LDist = closestSucc(left);
656 unsigned RDist = closestSucc(right);
659 else if (LDist == RDist) {
660 // Intuitively, it's good to push down instructions whose results are
661 // liveout so their long live ranges won't conflict with other values
662 // which are needed inside the BB. Further prioritize liveout instructions
663 // by the number of operands which are calculated within the BB.
664 unsigned LScratch = calcMaxScratches(left);
665 unsigned RScratch = calcMaxScratches(right);
666 if (LScratch > RScratch)
668 else if (LScratch == RScratch)
669 if (left->Height > right->Height)
671 else if (left->Height == right->Height)
672 if (left->Depth < right->Depth)
674 else if (left->Depth == right->Depth)
675 if (left->CycleBound > right->CycleBound)
682 // FIXME: This is probably too slow!
683 static void isReachable(SUnit *SU, SUnit *TargetSU,
684 SmallPtrSet<SUnit*, 32> &Visited, bool &Reached) {
686 if (SU == TargetSU) {
690 if (!Visited.insert(SU)) return;
692 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); I != E;
694 isReachable(I->first, TargetSU, Visited, Reached);
697 static bool isReachable(SUnit *SU, SUnit *TargetSU) {
698 SmallPtrSet<SUnit*, 32> Visited;
699 bool Reached = false;
700 isReachable(SU, TargetSU, Visited, Reached);
705 bool BURegReductionPriorityQueue<SF>::canClobber(SUnit *SU, SUnit *Op) {
706 if (SU->isTwoAddress) {
707 unsigned Opc = SU->Node->getTargetOpcode();
708 unsigned NumRes = ScheduleDAG::CountResults(SU->Node);
709 unsigned NumOps = ScheduleDAG::CountOperands(SU->Node);
710 for (unsigned i = 0; i != NumOps; ++i) {
711 if (TII->getOperandConstraint(Opc, i+NumRes, TOI::TIED_TO) != -1) {
712 SDNode *DU = SU->Node->getOperand(i).Val;
713 if (Op == (*SUnitMap)[DU])
722 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
723 /// it as a def&use operand. Add a pseudo control edge from it to the other
724 /// node (if it won't create a cycle) so the two-address one will be scheduled
725 /// first (lower in the schedule).
727 void BURegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
728 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
729 SUnit *SU = (SUnit *)&((*SUnits)[i]);
730 if (!SU->isTwoAddress)
733 SDNode *Node = SU->Node;
734 if (!Node->isTargetOpcode())
737 unsigned Opc = Node->getTargetOpcode();
738 unsigned NumRes = ScheduleDAG::CountResults(Node);
739 unsigned NumOps = ScheduleDAG::CountOperands(Node);
740 for (unsigned j = 0; j != NumOps; ++j) {
741 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) != -1) {
742 SDNode *DU = SU->Node->getOperand(j).Val;
743 SUnit *DUSU = (*SUnitMap)[DU];
745 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
747 if (I->second) continue;
748 SUnit *SuccSU = I->first;
750 (!canClobber(SuccSU, DUSU) ||
751 (!SU->isCommutable && SuccSU->isCommutable))){
752 if (SuccSU->Depth == SU->Depth && !isReachable(SuccSU, SU)) {
753 DOUT << "Adding an edge from SU # " << SU->NodeNum
754 << " to SU #" << SuccSU->NodeNum << "\n";
755 if (SU->addPred(SuccSU, true))
756 SU->NumChainPredsLeft++;
757 if (SuccSU->addSucc(SU, true))
758 SuccSU->NumChainSuccsLeft++;
767 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
768 /// Smaller number is the higher priority.
770 unsigned BURegReductionPriorityQueue<SF>::
771 CalcNodeSethiUllmanNumber(const SUnit *SU) {
772 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
773 if (SethiUllmanNumber != 0)
774 return SethiUllmanNumber;
777 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
779 if (I->second) continue; // ignore chain preds
780 SUnit *PredSU = I->first;
781 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
782 if (PredSethiUllman > SethiUllmanNumber) {
783 SethiUllmanNumber = PredSethiUllman;
785 } else if (PredSethiUllman == SethiUllmanNumber && !I->second)
789 SethiUllmanNumber += Extra;
791 if (SethiUllmanNumber == 0)
792 SethiUllmanNumber = 1;
794 return SethiUllmanNumber;
797 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
798 /// scheduling units.
800 void BURegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
801 SethiUllmanNumbers.assign(SUnits->size(), 0);
803 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
804 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
807 static unsigned SumOfUnscheduledPredsOfSuccs(const SUnit *SU) {
809 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
811 SUnit *SuccSU = I->first;
812 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
813 EE = SuccSU->Preds.end(); II != EE; ++II) {
814 SUnit *PredSU = II->first;
815 if (!PredSU->isScheduled)
825 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
826 unsigned LPriority = SPQ->getNodePriority(left);
827 unsigned RPriority = SPQ->getNodePriority(right);
828 bool LIsTarget = left->Node->isTargetOpcode();
829 bool RIsTarget = right->Node->isTargetOpcode();
830 bool LIsFloater = LIsTarget && left->NumPreds == 0;
831 bool RIsFloater = RIsTarget && right->NumPreds == 0;
832 unsigned LBonus = (SumOfUnscheduledPredsOfSuccs(left) == 1) ? 2 : 0;
833 unsigned RBonus = (SumOfUnscheduledPredsOfSuccs(right) == 1) ? 2 : 0;
835 if (left->NumSuccs == 0 && right->NumSuccs != 0)
837 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
840 // Special tie breaker: if two nodes share a operand, the one that use it
841 // as a def&use operand is preferred.
842 if (LIsTarget && RIsTarget) {
843 if (left->isTwoAddress && !right->isTwoAddress) {
844 SDNode *DUNode = left->Node->getOperand(0).Val;
845 if (DUNode->isOperand(right->Node))
848 if (!left->isTwoAddress && right->isTwoAddress) {
849 SDNode *DUNode = right->Node->getOperand(0).Val;
850 if (DUNode->isOperand(left->Node))
858 if (left->NumSuccs == 1)
860 if (right->NumSuccs == 1)
863 if (LPriority+LBonus < RPriority+RBonus)
865 else if (LPriority == RPriority)
866 if (left->Depth < right->Depth)
868 else if (left->Depth == right->Depth)
869 if (left->NumSuccsLeft > right->NumSuccsLeft)
871 else if (left->NumSuccsLeft == right->NumSuccsLeft)
872 if (left->CycleBound > right->CycleBound)
877 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
878 /// Smaller number is the higher priority.
880 unsigned TDRegReductionPriorityQueue<SF>::
881 CalcNodeSethiUllmanNumber(const SUnit *SU) {
882 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
883 if (SethiUllmanNumber != 0)
884 return SethiUllmanNumber;
886 unsigned Opc = SU->Node->getOpcode();
887 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
888 SethiUllmanNumber = 0xffff;
889 else if (SU->NumSuccsLeft == 0)
890 // If SU does not have a use, i.e. it doesn't produce a value that would
891 // be consumed (e.g. store), then it terminates a chain of computation.
892 // Give it a small SethiUllman number so it will be scheduled right before
893 // its predecessors that it doesn't lengthen their live ranges.
894 SethiUllmanNumber = 0;
895 else if (SU->NumPredsLeft == 0 &&
896 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
897 SethiUllmanNumber = 0xffff;
900 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
902 if (I->second) continue; // ignore chain preds
903 SUnit *PredSU = I->first;
904 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
905 if (PredSethiUllman > SethiUllmanNumber) {
906 SethiUllmanNumber = PredSethiUllman;
908 } else if (PredSethiUllman == SethiUllmanNumber && !I->second)
912 SethiUllmanNumber += Extra;
915 return SethiUllmanNumber;
918 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
919 /// scheduling units.
921 void TDRegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
922 SethiUllmanNumbers.assign(SUnits->size(), 0);
924 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
925 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
928 //===----------------------------------------------------------------------===//
929 // Public Constructor Functions
930 //===----------------------------------------------------------------------===//
932 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
934 MachineBasicBlock *BB) {
935 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
936 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true,
937 new BURegReductionPriorityQueue<bu_ls_rr_sort>(TII));
940 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
942 MachineBasicBlock *BB) {
943 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
944 new TDRegReductionPriorityQueue<td_ls_rr_sort>());