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 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
221 /// the Available queue is the count reaches zero. Also update its cycle bound.
222 void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain) {
223 // FIXME: the distance between two nodes is not always == the predecessor's
224 // latency. For example, the reader can very well read the register written
225 // by the predecessor later than the issue cycle. It also depends on the
226 // interrupt model (drain vs. freeze).
227 PredSU->CycleBound = std::max(PredSU->CycleBound,CurrCycle + PredSU->Latency);
230 PredSU->NumSuccsLeft--;
232 PredSU->NumChainSuccsLeft--;
235 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
236 std::cerr << "*** List scheduling failed! ***\n";
238 std::cerr << " has been released too many times!\n";
243 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
244 // EntryToken has to go last! Special case it here.
245 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
246 PredSU->isAvailable = true;
247 PriorityQueue->push(PredSU);
252 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
253 /// the Available queue is the count reaches zero. Also update its cycle bound.
254 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
255 // FIXME: the distance between two nodes is not always == the predecessor's
256 // latency. For example, the reader can very well read the register written
257 // by the predecessor later than the issue cycle. It also depends on the
258 // interrupt model (drain vs. freeze).
259 SuccSU->CycleBound = std::max(SuccSU->CycleBound,CurrCycle + SuccSU->Latency);
262 SuccSU->NumPredsLeft--;
264 SuccSU->NumChainPredsLeft--;
267 if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
268 std::cerr << "*** List scheduling failed! ***\n";
270 std::cerr << " has been released too many times!\n";
275 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
276 SuccSU->isAvailable = true;
277 PriorityQueue->push(SuccSU);
281 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
282 /// count of its predecessors. If a predecessor pending count is zero, add it to
283 /// the Available queue.
284 void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU) {
285 DEBUG(std::cerr << "*** Scheduling: ");
286 DEBUG(SU->dump(&DAG));
288 Sequence.push_back(SU);
290 // Bottom up: release predecessors
291 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
292 E = SU->Preds.end(); I != E; ++I) {
293 ReleasePred(I->first, I->second);
300 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
301 /// count of its successors. If a successor pending count is zero, add it to
302 /// the Available queue.
303 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU) {
304 DEBUG(std::cerr << "*** Scheduling: ");
305 DEBUG(SU->dump(&DAG));
307 Sequence.push_back(SU);
309 // Bottom up: release successors.
310 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
311 E = SU->Succs.end(); I != E; ++I) {
312 ReleaseSucc(I->first, I->second);
319 /// isReady - True if node's lower cycle bound is less or equal to the current
320 /// scheduling cycle. Always true if all nodes have uniform latency 1.
321 static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
322 return SU->CycleBound <= CurrCycle;
325 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
327 void ScheduleDAGList::ListScheduleBottomUp() {
328 // Add root to Available queue.
329 PriorityQueue->push(SUnitMap[DAG.getRoot().Val]);
331 // While Available queue is not empty, grab the node with the highest
332 // priority. If it is not ready put it back. Schedule the node.
333 std::vector<SUnit*> NotReady;
334 while (!PriorityQueue->empty()) {
335 SUnit *CurrNode = PriorityQueue->pop();
337 while (!isReady(CurrNode, CurrCycle)) {
338 NotReady.push_back(CurrNode);
339 CurrNode = PriorityQueue->pop();
342 // Add the nodes that aren't ready back onto the available list.
343 PriorityQueue->push_all(NotReady);
346 ScheduleNodeBottomUp(CurrNode);
347 CurrNode->isScheduled = true;
348 PriorityQueue->ScheduledNode(CurrNode);
351 // Add entry node last
352 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
353 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
354 Sequence.push_back(Entry);
357 // Reverse the order if it is bottom up.
358 std::reverse(Sequence.begin(), Sequence.end());
362 // Verify that all SUnits were scheduled.
363 bool AnyNotSched = false;
364 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
365 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
367 std::cerr << "*** List scheduling failed! ***\n";
368 SUnits[i].dump(&DAG);
369 std::cerr << "has not been scheduled!\n";
373 assert(!AnyNotSched);
377 /// ListScheduleTopDown - The main loop of list scheduling for top-down
379 void ScheduleDAGList::ListScheduleTopDown() {
380 // Emit the entry node first.
381 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
382 ScheduleNodeTopDown(Entry);
383 HazardRec->EmitInstruction(Entry->Node);
385 // All leaves to Available queue.
386 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
387 // It is available if it has no predecessors.
388 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry)
389 PriorityQueue->push(&SUnits[i]);
392 // While Available queue is not empty, grab the node with the highest
393 // priority. If it is not ready put it back. Schedule the node.
394 std::vector<SUnit*> NotReady;
395 while (!PriorityQueue->empty()) {
396 SUnit *FoundNode = 0;
398 bool HasNoopHazards = false;
400 SUnit *CurNode = PriorityQueue->pop();
402 // Get the node represented by this SUnit.
403 SDNode *N = CurNode->Node;
404 // If this is a pseudo op, like copyfromreg, look to see if there is a
405 // real target node flagged to it. If so, use the target node.
406 for (unsigned i = 0, e = CurNode->FlaggedNodes.size();
407 N->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
408 N = CurNode->FlaggedNodes[i];
410 HazardRecognizer::HazardType HT = HazardRec->getHazardType(N);
411 if (HT == HazardRecognizer::NoHazard) {
416 // Remember if this is a noop hazard.
417 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
419 NotReady.push_back(CurNode);
420 } while (!PriorityQueue->empty());
422 // Add the nodes that aren't ready back onto the available list.
423 PriorityQueue->push_all(NotReady);
426 // If we found a node to schedule, do it now.
428 ScheduleNodeTopDown(FoundNode);
429 HazardRec->EmitInstruction(FoundNode->Node);
430 FoundNode->isScheduled = true;
431 PriorityQueue->ScheduledNode(FoundNode);
432 } else if (!HasNoopHazards) {
433 // Otherwise, we have a pipeline stall, but no other problem, just advance
434 // the current cycle and try again.
435 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
436 HazardRec->AdvanceCycle();
439 // Otherwise, we have no instructions to issue and we have instructions
440 // that will fault if we don't do this right. This is the case for
441 // processors without pipeline interlocks and other cases.
442 DEBUG(std::cerr << "*** Emitting noop\n");
443 HazardRec->EmitNoop();
444 Sequence.push_back(0); // NULL SUnit* -> noop
450 // Verify that all SUnits were scheduled.
451 bool AnyNotSched = false;
452 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
453 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
455 std::cerr << "*** List scheduling failed! ***\n";
456 SUnits[i].dump(&DAG);
457 std::cerr << "has not been scheduled!\n";
461 assert(!AnyNotSched);
466 void ScheduleDAGList::BuildSchedUnits() {
467 // Reserve entries in the vector for each of the SUnits we are creating. This
468 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
470 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
472 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
474 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
475 E = DAG.allnodes_end(); NI != E; ++NI) {
476 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
479 // If this node has already been processed, stop now.
480 if (SUnitMap[NI]) continue;
482 SUnit *NodeSUnit = NewSUnit(NI);
484 // See if anything is flagged to this node, if so, add them to flagged
485 // nodes. Nodes can have at most one flag input and one flag output. Flags
486 // are required the be the last operand and result of a node.
488 // Scan up, adding flagged preds to FlaggedNodes.
490 while (N->getNumOperands() &&
491 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
492 N = N->getOperand(N->getNumOperands()-1).Val;
493 NodeSUnit->FlaggedNodes.push_back(N);
494 SUnitMap[N] = NodeSUnit;
497 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
498 // have a user of the flag operand.
500 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
501 SDOperand FlagVal(N, N->getNumValues()-1);
503 // There are either zero or one users of the Flag result.
504 bool HasFlagUse = false;
505 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
507 if (FlagVal.isOperand(*UI)) {
509 NodeSUnit->FlaggedNodes.push_back(N);
510 SUnitMap[N] = NodeSUnit;
514 if (!HasFlagUse) break;
517 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
520 SUnitMap[N] = NodeSUnit;
522 // Compute the latency for the node. We use the sum of the latencies for
523 // all nodes flagged together into this SUnit.
524 if (InstrItins.isEmpty()) {
525 // No latency information.
526 NodeSUnit->Latency = 1;
528 NodeSUnit->Latency = 0;
529 if (N->isTargetOpcode()) {
530 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
531 InstrStage *S = InstrItins.begin(SchedClass);
532 InstrStage *E = InstrItins.end(SchedClass);
534 NodeSUnit->Latency += S->Cycles;
536 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
537 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
538 if (FNode->isTargetOpcode()) {
539 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
540 InstrStage *S = InstrItins.begin(SchedClass);
541 InstrStage *E = InstrItins.end(SchedClass);
543 NodeSUnit->Latency += S->Cycles;
549 // Pass 2: add the preds, succs, etc.
550 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
551 SUnit *SU = &SUnits[su];
552 SDNode *MainNode = SU->Node;
554 if (MainNode->isTargetOpcode() &&
555 TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
556 SU->isTwoAddress = true;
558 // Find all predecessors and successors of the group.
559 // Temporarily add N to make code simpler.
560 SU->FlaggedNodes.push_back(MainNode);
562 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
563 SDNode *N = SU->FlaggedNodes[n];
565 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
566 SDNode *OpN = N->getOperand(i).Val;
567 if (isPassiveNode(OpN)) continue; // Not scheduled.
568 SUnit *OpSU = SUnitMap[OpN];
569 assert(OpSU && "Node has no SUnit!");
570 if (OpSU == SU) continue; // In the same group.
572 MVT::ValueType OpVT = N->getOperand(i).getValueType();
573 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
574 bool isChain = OpVT == MVT::Other;
576 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
580 SU->NumChainPredsLeft++;
583 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
585 OpSU->NumSuccsLeft++;
587 OpSU->NumChainSuccsLeft++;
593 // Remove MainNode from FlaggedNodes again.
594 SU->FlaggedNodes.pop_back();
596 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
597 SUnits[su].dumpAll(&DAG));
600 /// EmitSchedule - Emit the machine code in scheduled order.
601 void ScheduleDAGList::EmitSchedule() {
602 std::map<SDNode*, unsigned> VRBaseMap;
603 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
604 if (SUnit *SU = Sequence[i]) {
605 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
606 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
607 EmitNode(SU->Node, VRBaseMap);
609 // Null SUnit* is a noop.
615 /// dump - dump the schedule.
616 void ScheduleDAGList::dumpSchedule() const {
617 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
618 if (SUnit *SU = Sequence[i])
621 std::cerr << "**** NOOP ****\n";
625 /// Schedule - Schedule the DAG using list scheduling.
626 /// FIXME: Right now it only supports the burr (bottom up register reducing)
628 void ScheduleDAGList::Schedule() {
629 DEBUG(std::cerr << "********** List Scheduling **********\n");
631 // Build scheduling units.
634 PriorityQueue->initNodes(SUnits);
636 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
638 ListScheduleBottomUp();
640 ListScheduleTopDown();
642 PriorityQueue->releaseState();
644 DEBUG(std::cerr << "*** Final schedule ***\n");
645 DEBUG(dumpSchedule());
646 DEBUG(std::cerr << "\n");
648 // Emit in scheduled order
652 //===----------------------------------------------------------------------===//
653 // RegReductionPriorityQueue Implementation
654 //===----------------------------------------------------------------------===//
656 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
657 // to reduce register pressure.
660 class RegReductionPriorityQueue;
662 /// Sorting functions for the Available queue.
663 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
664 RegReductionPriorityQueue *SPQ;
665 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
666 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
668 bool operator()(const SUnit* left, const SUnit* right) const;
670 } // end anonymous namespace
673 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
674 // SUnits - The SUnits for the current graph.
675 const std::vector<SUnit> *SUnits;
677 // SethiUllmanNumbers - The SethiUllman number for each node.
678 std::vector<int> SethiUllmanNumbers;
680 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
682 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
685 void initNodes(const std::vector<SUnit> &sunits) {
687 // Calculate node priorities.
688 CalculatePriorities();
690 void releaseState() {
692 SethiUllmanNumbers.clear();
695 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
696 assert(NodeNum < SethiUllmanNumbers.size());
697 return SethiUllmanNumbers[NodeNum];
700 bool empty() const { return Queue.empty(); }
702 void push(SUnit *U) {
705 void push_all(const std::vector<SUnit *> &Nodes) {
706 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
707 Queue.push(Nodes[i]);
711 SUnit *V = Queue.top();
716 void CalculatePriorities();
717 int CalcNodePriority(const SUnit *SU);
721 bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
722 unsigned LeftNum = left->NodeNum;
723 unsigned RightNum = right->NodeNum;
725 int LBonus = (int)left ->isDefNUseOperand;
726 int RBonus = (int)right->isDefNUseOperand;
728 // Special tie breaker: if two nodes share a operand, the one that
729 // use it as a def&use operand is preferred.
730 if (left->isTwoAddress && !right->isTwoAddress) {
731 SDNode *DUNode = left->Node->getOperand(0).Val;
732 if (DUNode->isOperand(right->Node))
735 if (!left->isTwoAddress && right->isTwoAddress) {
736 SDNode *DUNode = right->Node->getOperand(0).Val;
737 if (DUNode->isOperand(left->Node))
741 // Priority1 is just the number of live range genned.
742 int LPriority1 = left ->NumPredsLeft - LBonus;
743 int RPriority1 = right->NumPredsLeft - RBonus;
744 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
745 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
747 if (LPriority1 > RPriority1)
749 else if (LPriority1 == RPriority1)
750 if (LPriority2 < RPriority2)
752 else if (LPriority2 == RPriority2)
753 if (left->CycleBound > right->CycleBound)
760 /// CalcNodePriority - Priority is the Sethi Ullman number.
761 /// Smaller number is the higher priority.
762 int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
763 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
764 if (SethiUllmanNumber != INT_MIN)
765 return SethiUllmanNumber;
767 if (SU->Preds.size() == 0) {
768 SethiUllmanNumber = 1;
771 for (std::set<std::pair<SUnit*, bool> >::const_iterator
772 I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
773 if (I->second) continue; // ignore chain preds.
774 SUnit *PredSU = I->first;
775 int PredSethiUllman = CalcNodePriority(PredSU);
776 if (PredSethiUllman > SethiUllmanNumber) {
777 SethiUllmanNumber = PredSethiUllman;
779 } else if (PredSethiUllman == SethiUllmanNumber)
783 if (SU->Node->getOpcode() != ISD::TokenFactor)
784 SethiUllmanNumber += Extra;
786 SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
789 return SethiUllmanNumber;
792 /// CalculatePriorities - Calculate priorities of all scheduling units.
793 void RegReductionPriorityQueue::CalculatePriorities() {
794 SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
796 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
797 CalcNodePriority(&(*SUnits)[i]);
800 //===----------------------------------------------------------------------===//
801 // LatencyPriorityQueue Implementation
802 //===----------------------------------------------------------------------===//
804 // This is a SchedulingPriorityQueue that schedules using latency information to
805 // reduce the length of the critical path through the basic block.
808 class LatencyPriorityQueue;
810 /// Sorting functions for the Available queue.
811 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
812 LatencyPriorityQueue *PQ;
813 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
814 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
816 bool operator()(const SUnit* left, const SUnit* right) const;
818 } // end anonymous namespace
821 class LatencyPriorityQueue : public SchedulingPriorityQueue {
822 // SUnits - The SUnits for the current graph.
823 const std::vector<SUnit> *SUnits;
825 // Latencies - The latency (max of latency from this node to the bb exit)
827 std::vector<int> Latencies;
829 /// NumNodesSolelyBlocking - This vector contains, for every node in the
830 /// Queue, the number of nodes that the node is the sole unscheduled
831 /// predecessor for. This is used as a tie-breaker heuristic for better
833 std::vector<unsigned> NumNodesSolelyBlocking;
835 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
837 LatencyPriorityQueue() : Queue(latency_sort(this)) {
840 void initNodes(const std::vector<SUnit> &sunits) {
842 // Calculate node priorities.
843 CalculatePriorities();
845 void releaseState() {
850 unsigned getLatency(unsigned NodeNum) const {
851 assert(NodeNum < Latencies.size());
852 return Latencies[NodeNum];
855 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
856 assert(NodeNum < NumNodesSolelyBlocking.size());
857 return NumNodesSolelyBlocking[NodeNum];
860 bool empty() const { return Queue.empty(); }
862 virtual void push(SUnit *U) {
865 void push_impl(SUnit *U);
867 void push_all(const std::vector<SUnit *> &Nodes) {
868 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
873 SUnit *V = Queue.top();
878 // ScheduledNode - As nodes are scheduled, we look to see if there are any
879 // successor nodes that have a single unscheduled predecessor. If so, that
880 // single predecessor has a higher priority, since scheduling it will make
881 // the node available.
882 void ScheduledNode(SUnit *Node);
885 void CalculatePriorities();
886 int CalcLatency(const SUnit &SU);
887 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
889 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
890 /// node from a priority queue. We should roll our own heap to make this
891 /// better or something.
892 void RemoveFromPriorityQueue(SUnit *SU) {
893 std::vector<SUnit*> Temp;
895 assert(!Queue.empty() && "Not in queue!");
896 while (Queue.top() != SU) {
897 Temp.push_back(Queue.top());
899 assert(!Queue.empty() && "Not in queue!");
902 // Remove the node from the PQ.
905 // Add all the other nodes back.
906 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
912 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
913 unsigned LHSNum = LHS->NodeNum;
914 unsigned RHSNum = RHS->NodeNum;
916 // The most important heuristic is scheduling the critical path.
917 unsigned LHSLatency = PQ->getLatency(LHSNum);
918 unsigned RHSLatency = PQ->getLatency(RHSNum);
919 if (LHSLatency < RHSLatency) return true;
920 if (LHSLatency > RHSLatency) return false;
922 // After that, if two nodes have identical latencies, look to see if one will
923 // unblock more other nodes than the other.
924 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
925 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
926 if (LHSBlocked < RHSBlocked) return true;
927 if (LHSBlocked > RHSBlocked) return false;
929 // Finally, just to provide a stable ordering, use the node number as a
931 return LHSNum < RHSNum;
935 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
937 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
938 int &Latency = Latencies[SU.NodeNum];
942 int MaxSuccLatency = 0;
943 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
944 E = SU.Succs.end(); I != E; ++I)
945 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
947 return Latency = MaxSuccLatency + SU.Latency;
950 /// CalculatePriorities - Calculate priorities of all scheduling units.
951 void LatencyPriorityQueue::CalculatePriorities() {
952 Latencies.assign(SUnits->size(), -1);
953 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
955 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
956 CalcLatency((*SUnits)[i]);
959 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
960 /// of SU, return it, otherwise return null.
961 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
962 SUnit *OnlyAvailablePred = 0;
963 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
964 E = SU->Preds.end(); I != E; ++I)
965 if (!I->first->isScheduled) {
966 // We found an available, but not scheduled, predecessor. If it's the
967 // only one we have found, keep track of it... otherwise give up.
968 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
970 OnlyAvailablePred = I->first;
973 return OnlyAvailablePred;
976 void LatencyPriorityQueue::push_impl(SUnit *SU) {
977 // Look at all of the successors of this node. Count the number of nodes that
978 // this node is the sole unscheduled node for.
979 unsigned NumNodesBlocking = 0;
980 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
981 E = SU->Succs.end(); I != E; ++I)
982 if (getSingleUnscheduledPred(I->first) == SU)
984 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
990 // ScheduledNode - As nodes are scheduled, we look to see if there are any
991 // successor nodes that have a single unscheduled predecessor. If so, that
992 // single predecessor has a higher priority, since scheduling it will make
993 // the node available.
994 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
995 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
996 E = SU->Succs.end(); I != E; ++I)
997 AdjustPriorityOfUnscheduledPreds(I->first);
1000 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1001 /// scheduled. If SU is not itself available, then there is at least one
1002 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
1003 /// unscheduled predecessor, we want to increase its priority: it getting
1004 /// scheduled will make this node available, so it is better than some other
1005 /// node of the same priority that will not make a node available.
1006 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1007 if (SU->isAvailable) return; // All preds scheduled.
1009 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1010 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1012 // Okay, we found a single predecessor that is available, but not scheduled.
1013 // Since it is available, it must be in the priority queue. First remove it.
1014 RemoveFromPriorityQueue(OnlyAvailablePred);
1016 // Reinsert the node into the priority queue, which recomputes its
1017 // NumNodesSolelyBlocking value.
1018 push(OnlyAvailablePred);
1022 //===----------------------------------------------------------------------===//
1023 // Public Constructor Functions
1024 //===----------------------------------------------------------------------===//
1026 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1027 MachineBasicBlock *BB) {
1028 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
1029 new RegReductionPriorityQueue(),
1030 new HazardRecognizer());
1033 /// createTDListDAGScheduler - This creates a top-down list scheduler with the
1034 /// specified hazard recognizer.
1035 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1036 MachineBasicBlock *BB,
1037 HazardRecognizer *HR) {
1038 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
1039 new LatencyPriorityQueue(),