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;
164 // The scheduling units.
165 std::vector<SUnit> SUnits;
167 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
171 /// PriorityQueue - The priority queue to use.
172 SchedulingPriorityQueue *PriorityQueue;
174 /// HazardRec - The hazard recognizer to use.
175 HazardRecognizer *HazardRec;
178 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
179 const TargetMachine &tm, bool isbottomup,
180 SchedulingPriorityQueue *priorityqueue,
181 HazardRecognizer *HR)
182 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
183 PriorityQueue(priorityqueue), HazardRec(HR) {
188 delete PriorityQueue;
193 void dumpSchedule() const;
196 SUnit *NewSUnit(SDNode *N);
197 void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
198 void ReleaseSucc(SUnit *SuccSU, bool isChain, unsigned CurCycle);
199 void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
200 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
201 void ListScheduleTopDown();
202 void ListScheduleBottomUp();
203 void BuildSchedUnits();
206 } // end anonymous namespace
208 HazardRecognizer::~HazardRecognizer() {}
211 /// NewSUnit - Creates a new SUnit and return a ptr to it.
212 SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
213 SUnits.push_back(SUnit(N, SUnits.size()));
214 return &SUnits.back();
217 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
218 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
219 /// together nodes with a single SUnit.
220 void ScheduleDAGList::BuildSchedUnits() {
221 // Reserve entries in the vector for each of the SUnits we are creating. This
222 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
224 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
226 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
228 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
229 E = DAG.allnodes_end(); NI != E; ++NI) {
230 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
233 // If this node has already been processed, stop now.
234 if (SUnitMap[NI]) continue;
236 SUnit *NodeSUnit = NewSUnit(NI);
238 // See if anything is flagged to this node, if so, add them to flagged
239 // nodes. Nodes can have at most one flag input and one flag output. Flags
240 // are required the be the last operand and result of a node.
242 // Scan up, adding flagged preds to FlaggedNodes.
244 while (N->getNumOperands() &&
245 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
246 N = N->getOperand(N->getNumOperands()-1).Val;
247 NodeSUnit->FlaggedNodes.push_back(N);
248 SUnitMap[N] = NodeSUnit;
251 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
252 // have a user of the flag operand.
254 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
255 SDOperand FlagVal(N, N->getNumValues()-1);
257 // There are either zero or one users of the Flag result.
258 bool HasFlagUse = false;
259 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
261 if (FlagVal.isOperand(*UI)) {
263 NodeSUnit->FlaggedNodes.push_back(N);
264 SUnitMap[N] = NodeSUnit;
268 if (!HasFlagUse) break;
271 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
274 SUnitMap[N] = NodeSUnit;
276 // Compute the latency for the node. We use the sum of the latencies for
277 // all nodes flagged together into this SUnit.
278 if (InstrItins.isEmpty()) {
279 // No latency information.
280 NodeSUnit->Latency = 1;
282 NodeSUnit->Latency = 0;
283 if (N->isTargetOpcode()) {
284 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
285 InstrStage *S = InstrItins.begin(SchedClass);
286 InstrStage *E = InstrItins.end(SchedClass);
288 NodeSUnit->Latency += S->Cycles;
290 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
291 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
292 if (FNode->isTargetOpcode()) {
293 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
294 InstrStage *S = InstrItins.begin(SchedClass);
295 InstrStage *E = InstrItins.end(SchedClass);
297 NodeSUnit->Latency += S->Cycles;
303 // Pass 2: add the preds, succs, etc.
304 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
305 SUnit *SU = &SUnits[su];
306 SDNode *MainNode = SU->Node;
308 if (MainNode->isTargetOpcode() &&
309 TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
310 SU->isTwoAddress = true;
312 // Find all predecessors and successors of the group.
313 // Temporarily add N to make code simpler.
314 SU->FlaggedNodes.push_back(MainNode);
316 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
317 SDNode *N = SU->FlaggedNodes[n];
319 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
320 SDNode *OpN = N->getOperand(i).Val;
321 if (isPassiveNode(OpN)) continue; // Not scheduled.
322 SUnit *OpSU = SUnitMap[OpN];
323 assert(OpSU && "Node has no SUnit!");
324 if (OpSU == SU) continue; // In the same group.
326 MVT::ValueType OpVT = N->getOperand(i).getValueType();
327 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
328 bool isChain = OpVT == MVT::Other;
330 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
334 SU->NumChainPredsLeft++;
337 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
339 OpSU->NumSuccsLeft++;
341 OpSU->NumChainSuccsLeft++;
347 // Remove MainNode from FlaggedNodes again.
348 SU->FlaggedNodes.pop_back();
350 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
351 SUnits[su].dumpAll(&DAG));
354 /// EmitSchedule - Emit the machine code in scheduled order.
355 void ScheduleDAGList::EmitSchedule() {
356 std::map<SDNode*, unsigned> VRBaseMap;
357 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
358 if (SUnit *SU = Sequence[i]) {
359 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
360 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
361 EmitNode(SU->Node, VRBaseMap);
363 // Null SUnit* is a noop.
369 /// dump - dump the schedule.
370 void ScheduleDAGList::dumpSchedule() const {
371 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
372 if (SUnit *SU = Sequence[i])
375 std::cerr << "**** NOOP ****\n";
379 /// Schedule - Schedule the DAG using list scheduling.
380 /// FIXME: Right now it only supports the burr (bottom up register reducing)
382 void ScheduleDAGList::Schedule() {
383 DEBUG(std::cerr << "********** List Scheduling **********\n");
385 // Build scheduling units.
388 PriorityQueue->initNodes(SUnits);
390 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
392 ListScheduleBottomUp();
394 ListScheduleTopDown();
396 PriorityQueue->releaseState();
398 DEBUG(std::cerr << "*** Final schedule ***\n");
399 DEBUG(dumpSchedule());
400 DEBUG(std::cerr << "\n");
402 // Emit in scheduled order
406 //===----------------------------------------------------------------------===//
407 // Bottom-Up Scheduling
408 //===----------------------------------------------------------------------===//
410 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
411 /// the Available queue is the count reaches zero. Also update its cycle bound.
412 void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain,
413 unsigned CurrCycle) {
414 // FIXME: the distance between two nodes is not always == the predecessor's
415 // latency. For example, the reader can very well read the register written
416 // by the predecessor later than the issue cycle. It also depends on the
417 // interrupt model (drain vs. freeze).
418 PredSU->CycleBound = std::max(PredSU->CycleBound,CurrCycle + PredSU->Latency);
421 PredSU->NumSuccsLeft--;
423 PredSU->NumChainSuccsLeft--;
426 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
427 std::cerr << "*** List scheduling failed! ***\n";
429 std::cerr << " has been released too many times!\n";
434 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
435 // EntryToken has to go last! Special case it here.
436 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
437 PredSU->isAvailable = true;
438 PriorityQueue->push(PredSU);
442 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
443 /// count of its predecessors. If a predecessor pending count is zero, add it to
444 /// the Available queue.
445 void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurrCycle) {
446 DEBUG(std::cerr << "*** Scheduling: ");
447 DEBUG(SU->dump(&DAG));
449 Sequence.push_back(SU);
451 // Bottom up: release predecessors
452 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
453 E = SU->Preds.end(); I != E; ++I) {
454 ReleasePred(I->first, I->second, CurrCycle);
460 /// isReady - True if node's lower cycle bound is less or equal to the current
461 /// scheduling cycle. Always true if all nodes have uniform latency 1.
462 static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
463 return SU->CycleBound <= CurrCycle;
466 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
468 void ScheduleDAGList::ListScheduleBottomUp() {
469 unsigned CurrCycle = 0;
470 // Add root to Available queue.
471 PriorityQueue->push(SUnitMap[DAG.getRoot().Val]);
473 // While Available queue is not empty, grab the node with the highest
474 // priority. If it is not ready put it back. Schedule the node.
475 std::vector<SUnit*> NotReady;
476 while (!PriorityQueue->empty()) {
477 SUnit *CurrNode = PriorityQueue->pop();
479 while (!isReady(CurrNode, CurrCycle)) {
480 NotReady.push_back(CurrNode);
481 CurrNode = PriorityQueue->pop();
484 // Add the nodes that aren't ready back onto the available list.
485 PriorityQueue->push_all(NotReady);
488 ScheduleNodeBottomUp(CurrNode, CurrCycle);
490 CurrNode->isScheduled = true;
491 PriorityQueue->ScheduledNode(CurrNode);
494 // Add entry node last
495 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
496 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
497 Sequence.push_back(Entry);
500 // Reverse the order if it is bottom up.
501 std::reverse(Sequence.begin(), Sequence.end());
505 // Verify that all SUnits were scheduled.
506 bool AnyNotSched = false;
507 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
508 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
510 std::cerr << "*** List scheduling failed! ***\n";
511 SUnits[i].dump(&DAG);
512 std::cerr << "has not been scheduled!\n";
516 assert(!AnyNotSched);
520 //===----------------------------------------------------------------------===//
521 // Top-Down Scheduling
522 //===----------------------------------------------------------------------===//
524 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
525 /// the Available queue is the count reaches zero. Also update its cycle bound.
526 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain,
527 unsigned CurrCycle) {
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, unsigned CurrCycle) {
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, CurrCycle);
572 /// ListScheduleTopDown - The main loop of list scheduling for top-down
574 void ScheduleDAGList::ListScheduleTopDown() {
575 unsigned CurrCycle = 0;
576 // Emit the entry node first.
577 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
578 ScheduleNodeTopDown(Entry, CurrCycle);
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, CurrCycle);
625 CurrCycle++; // Fixme don't increment for pseudo-ops!
626 HazardRec->EmitInstruction(FoundNode->Node);
627 FoundNode->isScheduled = true;
628 PriorityQueue->ScheduledNode(FoundNode);
629 } else if (!HasNoopHazards) {
630 // Otherwise, we have a pipeline stall, but no other problem, just advance
631 // the current cycle and try again.
632 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
633 HazardRec->AdvanceCycle();
636 // Otherwise, we have no instructions to issue and we have instructions
637 // that will fault if we don't do this right. This is the case for
638 // processors without pipeline interlocks and other cases.
639 DEBUG(std::cerr << "*** Emitting noop\n");
640 HazardRec->EmitNoop();
641 Sequence.push_back(0); // NULL SUnit* -> noop
647 // Verify that all SUnits were scheduled.
648 bool AnyNotSched = false;
649 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
650 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
652 std::cerr << "*** List scheduling failed! ***\n";
653 SUnits[i].dump(&DAG);
654 std::cerr << "has not been scheduled!\n";
658 assert(!AnyNotSched);
662 //===----------------------------------------------------------------------===//
663 // RegReductionPriorityQueue Implementation
664 //===----------------------------------------------------------------------===//
666 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
667 // to reduce register pressure.
670 class RegReductionPriorityQueue;
672 /// Sorting functions for the Available queue.
673 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
674 RegReductionPriorityQueue *SPQ;
675 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
676 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
678 bool operator()(const SUnit* left, const SUnit* right) const;
680 } // end anonymous namespace
683 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
684 // SUnits - The SUnits for the current graph.
685 const std::vector<SUnit> *SUnits;
687 // SethiUllmanNumbers - The SethiUllman number for each node.
688 std::vector<int> SethiUllmanNumbers;
690 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
692 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
695 void initNodes(const std::vector<SUnit> &sunits) {
697 // Calculate node priorities.
698 CalculatePriorities();
700 void releaseState() {
702 SethiUllmanNumbers.clear();
705 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
706 assert(NodeNum < SethiUllmanNumbers.size());
707 return SethiUllmanNumbers[NodeNum];
710 bool empty() const { return Queue.empty(); }
712 void push(SUnit *U) {
715 void push_all(const std::vector<SUnit *> &Nodes) {
716 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
717 Queue.push(Nodes[i]);
721 SUnit *V = Queue.top();
726 void CalculatePriorities();
727 int CalcNodePriority(const SUnit *SU);
731 bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
732 unsigned LeftNum = left->NodeNum;
733 unsigned RightNum = right->NodeNum;
735 int LBonus = (int)left ->isDefNUseOperand;
736 int RBonus = (int)right->isDefNUseOperand;
738 // Special tie breaker: if two nodes share a operand, the one that
739 // use it as a def&use operand is preferred.
740 if (left->isTwoAddress && !right->isTwoAddress) {
741 SDNode *DUNode = left->Node->getOperand(0).Val;
742 if (DUNode->isOperand(right->Node))
745 if (!left->isTwoAddress && right->isTwoAddress) {
746 SDNode *DUNode = right->Node->getOperand(0).Val;
747 if (DUNode->isOperand(left->Node))
751 // Priority1 is just the number of live range genned.
752 int LPriority1 = left ->NumPredsLeft - LBonus;
753 int RPriority1 = right->NumPredsLeft - RBonus;
754 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
755 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
757 if (LPriority1 > RPriority1)
759 else if (LPriority1 == RPriority1)
760 if (LPriority2 < RPriority2)
762 else if (LPriority2 == RPriority2)
763 if (left->CycleBound > right->CycleBound)
770 /// CalcNodePriority - Priority is the Sethi Ullman number.
771 /// Smaller number is the higher priority.
772 int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
773 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
774 if (SethiUllmanNumber != INT_MIN)
775 return SethiUllmanNumber;
777 if (SU->Preds.size() == 0) {
778 SethiUllmanNumber = 1;
781 for (std::set<std::pair<SUnit*, bool> >::const_iterator
782 I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
783 if (I->second) continue; // ignore chain preds.
784 SUnit *PredSU = I->first;
785 int PredSethiUllman = CalcNodePriority(PredSU);
786 if (PredSethiUllman > SethiUllmanNumber) {
787 SethiUllmanNumber = PredSethiUllman;
789 } else if (PredSethiUllman == SethiUllmanNumber)
793 if (SU->Node->getOpcode() != ISD::TokenFactor)
794 SethiUllmanNumber += Extra;
796 SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
799 return SethiUllmanNumber;
802 /// CalculatePriorities - Calculate priorities of all scheduling units.
803 void RegReductionPriorityQueue::CalculatePriorities() {
804 SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
806 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
807 CalcNodePriority(&(*SUnits)[i]);
810 //===----------------------------------------------------------------------===//
811 // LatencyPriorityQueue Implementation
812 //===----------------------------------------------------------------------===//
814 // This is a SchedulingPriorityQueue that schedules using latency information to
815 // reduce the length of the critical path through the basic block.
818 class LatencyPriorityQueue;
820 /// Sorting functions for the Available queue.
821 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
822 LatencyPriorityQueue *PQ;
823 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
824 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
826 bool operator()(const SUnit* left, const SUnit* right) const;
828 } // end anonymous namespace
831 class LatencyPriorityQueue : public SchedulingPriorityQueue {
832 // SUnits - The SUnits for the current graph.
833 const std::vector<SUnit> *SUnits;
835 // Latencies - The latency (max of latency from this node to the bb exit)
837 std::vector<int> Latencies;
839 /// NumNodesSolelyBlocking - This vector contains, for every node in the
840 /// Queue, the number of nodes that the node is the sole unscheduled
841 /// predecessor for. This is used as a tie-breaker heuristic for better
843 std::vector<unsigned> NumNodesSolelyBlocking;
845 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
847 LatencyPriorityQueue() : Queue(latency_sort(this)) {
850 void initNodes(const std::vector<SUnit> &sunits) {
852 // Calculate node priorities.
853 CalculatePriorities();
855 void releaseState() {
860 unsigned getLatency(unsigned NodeNum) const {
861 assert(NodeNum < Latencies.size());
862 return Latencies[NodeNum];
865 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
866 assert(NodeNum < NumNodesSolelyBlocking.size());
867 return NumNodesSolelyBlocking[NodeNum];
870 bool empty() const { return Queue.empty(); }
872 virtual void push(SUnit *U) {
875 void push_impl(SUnit *U);
877 void push_all(const std::vector<SUnit *> &Nodes) {
878 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
883 SUnit *V = Queue.top();
888 // ScheduledNode - As nodes are scheduled, we look to see if there are any
889 // successor nodes that have a single unscheduled predecessor. If so, that
890 // single predecessor has a higher priority, since scheduling it will make
891 // the node available.
892 void ScheduledNode(SUnit *Node);
895 void CalculatePriorities();
896 int CalcLatency(const SUnit &SU);
897 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
899 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
900 /// node from a priority queue. We should roll our own heap to make this
901 /// better or something.
902 void RemoveFromPriorityQueue(SUnit *SU) {
903 std::vector<SUnit*> Temp;
905 assert(!Queue.empty() && "Not in queue!");
906 while (Queue.top() != SU) {
907 Temp.push_back(Queue.top());
909 assert(!Queue.empty() && "Not in queue!");
912 // Remove the node from the PQ.
915 // Add all the other nodes back.
916 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
922 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
923 unsigned LHSNum = LHS->NodeNum;
924 unsigned RHSNum = RHS->NodeNum;
926 // The most important heuristic is scheduling the critical path.
927 unsigned LHSLatency = PQ->getLatency(LHSNum);
928 unsigned RHSLatency = PQ->getLatency(RHSNum);
929 if (LHSLatency < RHSLatency) return true;
930 if (LHSLatency > RHSLatency) return false;
932 // After that, if two nodes have identical latencies, look to see if one will
933 // unblock more other nodes than the other.
934 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
935 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
936 if (LHSBlocked < RHSBlocked) return true;
937 if (LHSBlocked > RHSBlocked) return false;
939 // Finally, just to provide a stable ordering, use the node number as a
941 return LHSNum < RHSNum;
945 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
947 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
948 int &Latency = Latencies[SU.NodeNum];
952 int MaxSuccLatency = 0;
953 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
954 E = SU.Succs.end(); I != E; ++I)
955 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
957 return Latency = MaxSuccLatency + SU.Latency;
960 /// CalculatePriorities - Calculate priorities of all scheduling units.
961 void LatencyPriorityQueue::CalculatePriorities() {
962 Latencies.assign(SUnits->size(), -1);
963 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
965 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
966 CalcLatency((*SUnits)[i]);
969 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
970 /// of SU, return it, otherwise return null.
971 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
972 SUnit *OnlyAvailablePred = 0;
973 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
974 E = SU->Preds.end(); I != E; ++I)
975 if (!I->first->isScheduled) {
976 // We found an available, but not scheduled, predecessor. If it's the
977 // only one we have found, keep track of it... otherwise give up.
978 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
980 OnlyAvailablePred = I->first;
983 return OnlyAvailablePred;
986 void LatencyPriorityQueue::push_impl(SUnit *SU) {
987 // Look at all of the successors of this node. Count the number of nodes that
988 // this node is the sole unscheduled node for.
989 unsigned NumNodesBlocking = 0;
990 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
991 E = SU->Succs.end(); I != E; ++I)
992 if (getSingleUnscheduledPred(I->first) == SU)
994 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
1000 // ScheduledNode - As nodes are scheduled, we look to see if there are any
1001 // successor nodes that have a single unscheduled predecessor. If so, that
1002 // single predecessor has a higher priority, since scheduling it will make
1003 // the node available.
1004 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
1005 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
1006 E = SU->Succs.end(); I != E; ++I)
1007 AdjustPriorityOfUnscheduledPreds(I->first);
1010 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1011 /// scheduled. If SU is not itself available, then there is at least one
1012 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
1013 /// unscheduled predecessor, we want to increase its priority: it getting
1014 /// scheduled will make this node available, so it is better than some other
1015 /// node of the same priority that will not make a node available.
1016 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1017 if (SU->isAvailable) return; // All preds scheduled.
1019 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1020 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1022 // Okay, we found a single predecessor that is available, but not scheduled.
1023 // Since it is available, it must be in the priority queue. First remove it.
1024 RemoveFromPriorityQueue(OnlyAvailablePred);
1026 // Reinsert the node into the priority queue, which recomputes its
1027 // NumNodesSolelyBlocking value.
1028 push(OnlyAvailablePred);
1032 //===----------------------------------------------------------------------===//
1033 // Public Constructor Functions
1034 //===----------------------------------------------------------------------===//
1036 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1037 MachineBasicBlock *BB) {
1038 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
1039 new RegReductionPriorityQueue(),
1040 new HazardRecognizer());
1043 /// createTDListDAGScheduler - This creates a top-down list scheduler with the
1044 /// specified hazard recognizer.
1045 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1046 MachineBasicBlock *BB,
1047 HazardRecognizer *HR) {
1048 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
1049 new LatencyPriorityQueue(),