1 //===---- ScheduleDAGList.cpp - Implement a list scheduler for isel DAG ---===//
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 list schedulers, using standard
11 // algorithms. The basic approach uses a priority queue of available nodes to
12 // schedule. One at a time, nodes are taken from the priority queue (thus in
13 // priority order), checked for legality to schedule, and emitted if legal.
15 // Nodes may not be legal to schedule either due to structural hazards (e.g.
16 // pipeline or resource constraints) or because an input to the instruction has
17 // not completed execution.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "sched"
22 #include "llvm/CodeGen/ScheduleDAG.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
36 Statistic<> NumNoops ("scheduler", "Number of noops inserted");
37 Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
39 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
40 /// a group of nodes flagged together.
42 SDNode *Node; // Representative node.
43 std::vector<SDNode*> FlaggedNodes; // All nodes flagged to Node.
45 // Preds/Succs - The SUnits before/after us in the graph. The boolean value
46 // is true if the edge is a token chain edge, false if it is a value edge.
47 std::set<std::pair<SUnit*,bool> > Preds; // All sunit predecessors.
48 std::set<std::pair<SUnit*,bool> > Succs; // All sunit successors.
50 short NumPredsLeft; // # of preds not scheduled.
51 short NumSuccsLeft; // # of succs not scheduled.
52 short NumChainPredsLeft; // # of chain preds not scheduled.
53 short NumChainSuccsLeft; // # of chain succs not scheduled.
54 bool isTwoAddress : 1; // Is a two-address instruction.
55 bool isDefNUseOperand : 1; // Is a def&use operand.
56 bool isAvailable : 1; // True once available.
57 bool isScheduled : 1; // True once scheduled.
58 unsigned short Latency; // Node latency.
59 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
60 unsigned NodeNum; // Entry # of node in the node vector.
62 SUnit(SDNode *node, unsigned nodenum)
63 : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
64 NumChainPredsLeft(0), NumChainSuccsLeft(0),
65 isTwoAddress(false), isDefNUseOperand(false),
66 isAvailable(false), isScheduled(false),
67 Latency(0), CycleBound(0), NodeNum(nodenum) {}
69 void dump(const SelectionDAG *G) const;
70 void dumpAll(const SelectionDAG *G) const;
74 void SUnit::dump(const SelectionDAG *G) const {
78 if (FlaggedNodes.size() != 0) {
79 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
81 FlaggedNodes[i]->dump(G);
87 void SUnit::dumpAll(const SelectionDAG *G) const {
90 std::cerr << " # preds left : " << NumPredsLeft << "\n";
91 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
92 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
93 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
94 std::cerr << " Latency : " << Latency << "\n";
96 if (Preds.size() != 0) {
97 std::cerr << " Predecessors:\n";
98 for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
99 E = Preds.end(); I != E; ++I) {
103 std::cerr << " val ";
107 if (Succs.size() != 0) {
108 std::cerr << " Successors:\n";
109 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
110 E = Succs.end(); I != E; ++I) {
114 std::cerr << " val ";
121 //===----------------------------------------------------------------------===//
122 /// SchedulingPriorityQueue - This interface is used to plug different
123 /// priorities computation algorithms into the list scheduler. It implements the
124 /// interface of a standard priority queue, where nodes are inserted in
125 /// arbitrary order and returned in priority order. The computation of the
126 /// priority and the representation of the queue are totally up to the
127 /// implementation to decide.
130 class SchedulingPriorityQueue {
132 virtual ~SchedulingPriorityQueue() {}
134 virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
135 virtual void releaseState() = 0;
137 virtual bool empty() const = 0;
138 virtual void push(SUnit *U) = 0;
140 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
141 virtual SUnit *pop() = 0;
143 /// ScheduledNode - As each node is scheduled, this method is invoked. This
144 /// allows the priority function to adjust the priority of node that have
145 /// already been emitted.
146 virtual void ScheduledNode(SUnit *Node) {}
153 //===----------------------------------------------------------------------===//
154 /// ScheduleDAGList - The actual list scheduler implementation. This supports
155 /// both top-down and bottom-up scheduling.
157 class ScheduleDAGList : public ScheduleDAG {
159 // SDNode to SUnit mapping (many to one).
160 std::map<SDNode*, SUnit*> SUnitMap;
161 // The schedule. Null SUnit*'s represent noop instructions.
162 std::vector<SUnit*> Sequence;
163 // Current scheduling cycle.
166 // The scheduling units.
167 std::vector<SUnit> SUnits;
169 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
173 /// PriorityQueue - The priority queue to use.
174 SchedulingPriorityQueue *PriorityQueue;
176 /// HazardRec - The hazard recognizer to use.
177 HazardRecognizer *HazardRec;
180 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
181 const TargetMachine &tm, bool isbottomup,
182 SchedulingPriorityQueue *priorityqueue,
183 HazardRecognizer *HR)
184 : ScheduleDAG(dag, bb, tm),
185 CurrCycle(0), isBottomUp(isbottomup),
186 PriorityQueue(priorityqueue), HazardRec(HR) {
191 delete PriorityQueue;
196 void dumpSchedule() const;
199 SUnit *NewSUnit(SDNode *N);
200 void ReleasePred(SUnit *PredSU, bool isChain);
201 void ReleaseSucc(SUnit *SuccSU, bool isChain);
202 void ScheduleNodeBottomUp(SUnit *SU);
203 void ScheduleNodeTopDown(SUnit *SU);
204 void ListScheduleTopDown();
205 void ListScheduleBottomUp();
206 void BuildSchedUnits();
209 } // end anonymous namespace
211 HazardRecognizer::~HazardRecognizer() {}
214 /// NewSUnit - Creates a new SUnit and return a ptr to it.
215 SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
216 SUnits.push_back(SUnit(N, SUnits.size()));
217 return &SUnits.back();
220 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
221 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
222 /// together nodes with a single SUnit.
223 void ScheduleDAGList::BuildSchedUnits() {
224 // Reserve entries in the vector for each of the SUnits we are creating. This
225 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
227 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
229 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
231 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
232 E = DAG.allnodes_end(); NI != E; ++NI) {
233 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
236 // If this node has already been processed, stop now.
237 if (SUnitMap[NI]) continue;
239 SUnit *NodeSUnit = NewSUnit(NI);
241 // See if anything is flagged to this node, if so, add them to flagged
242 // nodes. Nodes can have at most one flag input and one flag output. Flags
243 // are required the be the last operand and result of a node.
245 // Scan up, adding flagged preds to FlaggedNodes.
247 while (N->getNumOperands() &&
248 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
249 N = N->getOperand(N->getNumOperands()-1).Val;
250 NodeSUnit->FlaggedNodes.push_back(N);
251 SUnitMap[N] = NodeSUnit;
254 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
255 // have a user of the flag operand.
257 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
258 SDOperand FlagVal(N, N->getNumValues()-1);
260 // There are either zero or one users of the Flag result.
261 bool HasFlagUse = false;
262 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
264 if (FlagVal.isOperand(*UI)) {
266 NodeSUnit->FlaggedNodes.push_back(N);
267 SUnitMap[N] = NodeSUnit;
271 if (!HasFlagUse) break;
274 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
277 SUnitMap[N] = NodeSUnit;
279 // Compute the latency for the node. We use the sum of the latencies for
280 // all nodes flagged together into this SUnit.
281 if (InstrItins.isEmpty()) {
282 // No latency information.
283 NodeSUnit->Latency = 1;
285 NodeSUnit->Latency = 0;
286 if (N->isTargetOpcode()) {
287 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
288 InstrStage *S = InstrItins.begin(SchedClass);
289 InstrStage *E = InstrItins.end(SchedClass);
291 NodeSUnit->Latency += S->Cycles;
293 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
294 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
295 if (FNode->isTargetOpcode()) {
296 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
297 InstrStage *S = InstrItins.begin(SchedClass);
298 InstrStage *E = InstrItins.end(SchedClass);
300 NodeSUnit->Latency += S->Cycles;
306 // Pass 2: add the preds, succs, etc.
307 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
308 SUnit *SU = &SUnits[su];
309 SDNode *MainNode = SU->Node;
311 if (MainNode->isTargetOpcode() &&
312 TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
313 SU->isTwoAddress = true;
315 // Find all predecessors and successors of the group.
316 // Temporarily add N to make code simpler.
317 SU->FlaggedNodes.push_back(MainNode);
319 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
320 SDNode *N = SU->FlaggedNodes[n];
322 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
323 SDNode *OpN = N->getOperand(i).Val;
324 if (isPassiveNode(OpN)) continue; // Not scheduled.
325 SUnit *OpSU = SUnitMap[OpN];
326 assert(OpSU && "Node has no SUnit!");
327 if (OpSU == SU) continue; // In the same group.
329 MVT::ValueType OpVT = N->getOperand(i).getValueType();
330 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
331 bool isChain = OpVT == MVT::Other;
333 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
337 SU->NumChainPredsLeft++;
340 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
342 OpSU->NumSuccsLeft++;
344 OpSU->NumChainSuccsLeft++;
350 // Remove MainNode from FlaggedNodes again.
351 SU->FlaggedNodes.pop_back();
353 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
354 SUnits[su].dumpAll(&DAG));
357 /// EmitSchedule - Emit the machine code in scheduled order.
358 void ScheduleDAGList::EmitSchedule() {
359 std::map<SDNode*, unsigned> VRBaseMap;
360 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
361 if (SUnit *SU = Sequence[i]) {
362 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
363 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
364 EmitNode(SU->Node, VRBaseMap);
366 // Null SUnit* is a noop.
372 /// dump - dump the schedule.
373 void ScheduleDAGList::dumpSchedule() const {
374 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
375 if (SUnit *SU = Sequence[i])
378 std::cerr << "**** NOOP ****\n";
382 /// Schedule - Schedule the DAG using list scheduling.
383 /// FIXME: Right now it only supports the burr (bottom up register reducing)
385 void ScheduleDAGList::Schedule() {
386 DEBUG(std::cerr << "********** List Scheduling **********\n");
388 // Build scheduling units.
391 PriorityQueue->initNodes(SUnits);
393 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
395 ListScheduleBottomUp();
397 ListScheduleTopDown();
399 PriorityQueue->releaseState();
401 DEBUG(std::cerr << "*** Final schedule ***\n");
402 DEBUG(dumpSchedule());
403 DEBUG(std::cerr << "\n");
405 // Emit in scheduled order
409 //===----------------------------------------------------------------------===//
410 // Bottom-Up Scheduling
411 //===----------------------------------------------------------------------===//
413 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
414 /// the Available queue is the count reaches zero. Also update its cycle bound.
415 void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain) {
416 // FIXME: the distance between two nodes is not always == the predecessor's
417 // latency. For example, the reader can very well read the register written
418 // by the predecessor later than the issue cycle. It also depends on the
419 // interrupt model (drain vs. freeze).
420 PredSU->CycleBound = std::max(PredSU->CycleBound,CurrCycle + PredSU->Latency);
423 PredSU->NumSuccsLeft--;
425 PredSU->NumChainSuccsLeft--;
428 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
429 std::cerr << "*** List scheduling failed! ***\n";
431 std::cerr << " has been released too many times!\n";
436 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
437 // EntryToken has to go last! Special case it here.
438 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
439 PredSU->isAvailable = true;
440 PriorityQueue->push(PredSU);
444 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
445 /// count of its predecessors. If a predecessor pending count is zero, add it to
446 /// the Available queue.
447 void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU) {
448 DEBUG(std::cerr << "*** Scheduling: ");
449 DEBUG(SU->dump(&DAG));
451 Sequence.push_back(SU);
453 // Bottom up: release predecessors
454 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
455 E = SU->Preds.end(); I != E; ++I) {
456 ReleasePred(I->first, I->second);
463 /// isReady - True if node's lower cycle bound is less or equal to the current
464 /// scheduling cycle. Always true if all nodes have uniform latency 1.
465 static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
466 return SU->CycleBound <= CurrCycle;
469 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
471 void ScheduleDAGList::ListScheduleBottomUp() {
472 // Add root to Available queue.
473 PriorityQueue->push(SUnitMap[DAG.getRoot().Val]);
475 // While Available queue is not empty, grab the node with the highest
476 // priority. If it is not ready put it back. Schedule the node.
477 std::vector<SUnit*> NotReady;
478 while (!PriorityQueue->empty()) {
479 SUnit *CurrNode = PriorityQueue->pop();
481 while (!isReady(CurrNode, CurrCycle)) {
482 NotReady.push_back(CurrNode);
483 CurrNode = PriorityQueue->pop();
486 // Add the nodes that aren't ready back onto the available list.
487 PriorityQueue->push_all(NotReady);
490 ScheduleNodeBottomUp(CurrNode);
491 CurrNode->isScheduled = true;
492 PriorityQueue->ScheduledNode(CurrNode);
495 // Add entry node last
496 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
497 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
498 Sequence.push_back(Entry);
501 // Reverse the order if it is bottom up.
502 std::reverse(Sequence.begin(), Sequence.end());
506 // Verify that all SUnits were scheduled.
507 bool AnyNotSched = false;
508 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
509 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
511 std::cerr << "*** List scheduling failed! ***\n";
512 SUnits[i].dump(&DAG);
513 std::cerr << "has not been scheduled!\n";
517 assert(!AnyNotSched);
521 //===----------------------------------------------------------------------===//
522 // Top-Down Scheduling
523 //===----------------------------------------------------------------------===//
525 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
526 /// the Available queue is the count reaches zero. Also update its cycle bound.
527 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
528 // FIXME: the distance between two nodes is not always == the predecessor's
529 // latency. For example, the reader can very well read the register written
530 // by the predecessor later than the issue cycle. It also depends on the
531 // interrupt model (drain vs. freeze).
532 SuccSU->CycleBound = std::max(SuccSU->CycleBound,CurrCycle + SuccSU->Latency);
535 SuccSU->NumPredsLeft--;
537 SuccSU->NumChainPredsLeft--;
540 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
541 std::cerr << "*** List scheduling failed! ***\n";
543 std::cerr << " has been released too many times!\n";
548 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
549 SuccSU->isAvailable = true;
550 PriorityQueue->push(SuccSU);
554 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
555 /// count of its successors. If a successor pending count is zero, add it to
556 /// the Available queue.
557 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU) {
558 DEBUG(std::cerr << "*** Scheduling: ");
559 DEBUG(SU->dump(&DAG));
561 Sequence.push_back(SU);
563 // Bottom up: release successors.
564 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
565 E = SU->Succs.end(); I != E; ++I) {
566 ReleaseSucc(I->first, I->second);
573 /// ListScheduleTopDown - The main loop of list scheduling for top-down
575 void ScheduleDAGList::ListScheduleTopDown() {
576 // Emit the entry node first.
577 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
578 ScheduleNodeTopDown(Entry);
579 HazardRec->EmitInstruction(Entry->Node);
581 // All leaves to Available queue.
582 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
583 // It is available if it has no predecessors.
584 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry)
585 PriorityQueue->push(&SUnits[i]);
588 // While Available queue is not empty, grab the node with the highest
589 // priority. If it is not ready put it back. Schedule the node.
590 std::vector<SUnit*> NotReady;
591 while (!PriorityQueue->empty()) {
592 SUnit *FoundNode = 0;
594 bool HasNoopHazards = false;
596 SUnit *CurNode = PriorityQueue->pop();
598 // Get the node represented by this SUnit.
599 SDNode *N = CurNode->Node;
600 // If this is a pseudo op, like copyfromreg, look to see if there is a
601 // real target node flagged to it. If so, use the target node.
602 for (unsigned i = 0, e = CurNode->FlaggedNodes.size();
603 N->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
604 N = CurNode->FlaggedNodes[i];
606 HazardRecognizer::HazardType HT = HazardRec->getHazardType(N);
607 if (HT == HazardRecognizer::NoHazard) {
612 // Remember if this is a noop hazard.
613 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
615 NotReady.push_back(CurNode);
616 } while (!PriorityQueue->empty());
618 // Add the nodes that aren't ready back onto the available list.
619 PriorityQueue->push_all(NotReady);
622 // If we found a node to schedule, do it now.
624 ScheduleNodeTopDown(FoundNode);
625 HazardRec->EmitInstruction(FoundNode->Node);
626 FoundNode->isScheduled = true;
627 PriorityQueue->ScheduledNode(FoundNode);
628 } else if (!HasNoopHazards) {
629 // Otherwise, we have a pipeline stall, but no other problem, just advance
630 // the current cycle and try again.
631 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
632 HazardRec->AdvanceCycle();
635 // Otherwise, we have no instructions to issue and we have instructions
636 // that will fault if we don't do this right. This is the case for
637 // processors without pipeline interlocks and other cases.
638 DEBUG(std::cerr << "*** Emitting noop\n");
639 HazardRec->EmitNoop();
640 Sequence.push_back(0); // NULL SUnit* -> noop
646 // Verify that all SUnits were scheduled.
647 bool AnyNotSched = false;
648 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
649 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
651 std::cerr << "*** List scheduling failed! ***\n";
652 SUnits[i].dump(&DAG);
653 std::cerr << "has not been scheduled!\n";
657 assert(!AnyNotSched);
661 //===----------------------------------------------------------------------===//
662 // RegReductionPriorityQueue Implementation
663 //===----------------------------------------------------------------------===//
665 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
666 // to reduce register pressure.
669 class RegReductionPriorityQueue;
671 /// Sorting functions for the Available queue.
672 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
673 RegReductionPriorityQueue *SPQ;
674 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
675 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
677 bool operator()(const SUnit* left, const SUnit* right) const;
679 } // end anonymous namespace
682 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
683 // SUnits - The SUnits for the current graph.
684 const std::vector<SUnit> *SUnits;
686 // SethiUllmanNumbers - The SethiUllman number for each node.
687 std::vector<int> SethiUllmanNumbers;
689 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
691 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
694 void initNodes(const std::vector<SUnit> &sunits) {
696 // Calculate node priorities.
697 CalculatePriorities();
699 void releaseState() {
701 SethiUllmanNumbers.clear();
704 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
705 assert(NodeNum < SethiUllmanNumbers.size());
706 return SethiUllmanNumbers[NodeNum];
709 bool empty() const { return Queue.empty(); }
711 void push(SUnit *U) {
714 void push_all(const std::vector<SUnit *> &Nodes) {
715 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
716 Queue.push(Nodes[i]);
720 SUnit *V = Queue.top();
725 void CalculatePriorities();
726 int CalcNodePriority(const SUnit *SU);
730 bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
731 unsigned LeftNum = left->NodeNum;
732 unsigned RightNum = right->NodeNum;
734 int LBonus = (int)left ->isDefNUseOperand;
735 int RBonus = (int)right->isDefNUseOperand;
737 // Special tie breaker: if two nodes share a operand, the one that
738 // use it as a def&use operand is preferred.
739 if (left->isTwoAddress && !right->isTwoAddress) {
740 SDNode *DUNode = left->Node->getOperand(0).Val;
741 if (DUNode->isOperand(right->Node))
744 if (!left->isTwoAddress && right->isTwoAddress) {
745 SDNode *DUNode = right->Node->getOperand(0).Val;
746 if (DUNode->isOperand(left->Node))
750 // Priority1 is just the number of live range genned.
751 int LPriority1 = left ->NumPredsLeft - LBonus;
752 int RPriority1 = right->NumPredsLeft - RBonus;
753 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
754 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
756 if (LPriority1 > RPriority1)
758 else if (LPriority1 == RPriority1)
759 if (LPriority2 < RPriority2)
761 else if (LPriority2 == RPriority2)
762 if (left->CycleBound > right->CycleBound)
769 /// CalcNodePriority - Priority is the Sethi Ullman number.
770 /// Smaller number is the higher priority.
771 int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
772 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
773 if (SethiUllmanNumber != INT_MIN)
774 return SethiUllmanNumber;
776 if (SU->Preds.size() == 0) {
777 SethiUllmanNumber = 1;
780 for (std::set<std::pair<SUnit*, bool> >::const_iterator
781 I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
782 if (I->second) continue; // ignore chain preds.
783 SUnit *PredSU = I->first;
784 int PredSethiUllman = CalcNodePriority(PredSU);
785 if (PredSethiUllman > SethiUllmanNumber) {
786 SethiUllmanNumber = PredSethiUllman;
788 } else if (PredSethiUllman == SethiUllmanNumber)
792 if (SU->Node->getOpcode() != ISD::TokenFactor)
793 SethiUllmanNumber += Extra;
795 SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
798 return SethiUllmanNumber;
801 /// CalculatePriorities - Calculate priorities of all scheduling units.
802 void RegReductionPriorityQueue::CalculatePriorities() {
803 SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
805 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
806 CalcNodePriority(&(*SUnits)[i]);
809 //===----------------------------------------------------------------------===//
810 // LatencyPriorityQueue Implementation
811 //===----------------------------------------------------------------------===//
813 // This is a SchedulingPriorityQueue that schedules using latency information to
814 // reduce the length of the critical path through the basic block.
817 class LatencyPriorityQueue;
819 /// Sorting functions for the Available queue.
820 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
821 LatencyPriorityQueue *PQ;
822 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
823 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
825 bool operator()(const SUnit* left, const SUnit* right) const;
827 } // end anonymous namespace
830 class LatencyPriorityQueue : public SchedulingPriorityQueue {
831 // SUnits - The SUnits for the current graph.
832 const std::vector<SUnit> *SUnits;
834 // Latencies - The latency (max of latency from this node to the bb exit)
836 std::vector<int> Latencies;
838 /// NumNodesSolelyBlocking - This vector contains, for every node in the
839 /// Queue, the number of nodes that the node is the sole unscheduled
840 /// predecessor for. This is used as a tie-breaker heuristic for better
842 std::vector<unsigned> NumNodesSolelyBlocking;
844 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
846 LatencyPriorityQueue() : Queue(latency_sort(this)) {
849 void initNodes(const std::vector<SUnit> &sunits) {
851 // Calculate node priorities.
852 CalculatePriorities();
854 void releaseState() {
859 unsigned getLatency(unsigned NodeNum) const {
860 assert(NodeNum < Latencies.size());
861 return Latencies[NodeNum];
864 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
865 assert(NodeNum < NumNodesSolelyBlocking.size());
866 return NumNodesSolelyBlocking[NodeNum];
869 bool empty() const { return Queue.empty(); }
871 virtual void push(SUnit *U) {
874 void push_impl(SUnit *U);
876 void push_all(const std::vector<SUnit *> &Nodes) {
877 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
882 SUnit *V = Queue.top();
887 // ScheduledNode - As nodes are scheduled, we look to see if there are any
888 // successor nodes that have a single unscheduled predecessor. If so, that
889 // single predecessor has a higher priority, since scheduling it will make
890 // the node available.
891 void ScheduledNode(SUnit *Node);
894 void CalculatePriorities();
895 int CalcLatency(const SUnit &SU);
896 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
898 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
899 /// node from a priority queue. We should roll our own heap to make this
900 /// better or something.
901 void RemoveFromPriorityQueue(SUnit *SU) {
902 std::vector<SUnit*> Temp;
904 assert(!Queue.empty() && "Not in queue!");
905 while (Queue.top() != SU) {
906 Temp.push_back(Queue.top());
908 assert(!Queue.empty() && "Not in queue!");
911 // Remove the node from the PQ.
914 // Add all the other nodes back.
915 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
921 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
922 unsigned LHSNum = LHS->NodeNum;
923 unsigned RHSNum = RHS->NodeNum;
925 // The most important heuristic is scheduling the critical path.
926 unsigned LHSLatency = PQ->getLatency(LHSNum);
927 unsigned RHSLatency = PQ->getLatency(RHSNum);
928 if (LHSLatency < RHSLatency) return true;
929 if (LHSLatency > RHSLatency) return false;
931 // After that, if two nodes have identical latencies, look to see if one will
932 // unblock more other nodes than the other.
933 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
934 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
935 if (LHSBlocked < RHSBlocked) return true;
936 if (LHSBlocked > RHSBlocked) return false;
938 // Finally, just to provide a stable ordering, use the node number as a
940 return LHSNum < RHSNum;
944 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
946 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
947 int &Latency = Latencies[SU.NodeNum];
951 int MaxSuccLatency = 0;
952 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
953 E = SU.Succs.end(); I != E; ++I)
954 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
956 return Latency = MaxSuccLatency + SU.Latency;
959 /// CalculatePriorities - Calculate priorities of all scheduling units.
960 void LatencyPriorityQueue::CalculatePriorities() {
961 Latencies.assign(SUnits->size(), -1);
962 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
964 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
965 CalcLatency((*SUnits)[i]);
968 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
969 /// of SU, return it, otherwise return null.
970 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
971 SUnit *OnlyAvailablePred = 0;
972 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
973 E = SU->Preds.end(); I != E; ++I)
974 if (!I->first->isScheduled) {
975 // We found an available, but not scheduled, predecessor. If it's the
976 // only one we have found, keep track of it... otherwise give up.
977 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
979 OnlyAvailablePred = I->first;
982 return OnlyAvailablePred;
985 void LatencyPriorityQueue::push_impl(SUnit *SU) {
986 // Look at all of the successors of this node. Count the number of nodes that
987 // this node is the sole unscheduled node for.
988 unsigned NumNodesBlocking = 0;
989 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
990 E = SU->Succs.end(); I != E; ++I)
991 if (getSingleUnscheduledPred(I->first) == SU)
993 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
999 // ScheduledNode - As nodes are scheduled, we look to see if there are any
1000 // successor nodes that have a single unscheduled predecessor. If so, that
1001 // single predecessor has a higher priority, since scheduling it will make
1002 // the node available.
1003 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
1004 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
1005 E = SU->Succs.end(); I != E; ++I)
1006 AdjustPriorityOfUnscheduledPreds(I->first);
1009 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1010 /// scheduled. If SU is not itself available, then there is at least one
1011 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
1012 /// unscheduled predecessor, we want to increase its priority: it getting
1013 /// scheduled will make this node available, so it is better than some other
1014 /// node of the same priority that will not make a node available.
1015 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1016 if (SU->isAvailable) return; // All preds scheduled.
1018 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1019 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1021 // Okay, we found a single predecessor that is available, but not scheduled.
1022 // Since it is available, it must be in the priority queue. First remove it.
1023 RemoveFromPriorityQueue(OnlyAvailablePred);
1025 // Reinsert the node into the priority queue, which recomputes its
1026 // NumNodesSolelyBlocking value.
1027 push(OnlyAvailablePred);
1031 //===----------------------------------------------------------------------===//
1032 // Public Constructor Functions
1033 //===----------------------------------------------------------------------===//
1035 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1036 MachineBasicBlock *BB) {
1037 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
1038 new RegReductionPriorityQueue(),
1039 new HazardRecognizer());
1042 /// createTDListDAGScheduler - This creates a top-down list scheduler with the
1043 /// specified hazard recognizer.
1044 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1045 MachineBasicBlock *BB,
1046 HazardRecognizer *HR) {
1047 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
1048 new LatencyPriorityQueue(),