1 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements bottom-up and top-down register pressure reduction list
11 // schedulers, using standard algorithms. The basic approach uses a priority
12 // queue of available nodes to schedule. One at a time, nodes are taken from
13 // the priority queue (thus in priority order), checked for legality to
14 // schedule, and emitted if legal.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "pre-RA-sched"
19 #include "llvm/CodeGen/ScheduleDAG.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/PriorityQueue.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CommandLine.h"
37 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
38 STATISTIC(NumUnfolds, "Number of nodes unfolded");
39 STATISTIC(NumDups, "Number of duplicated nodes");
40 STATISTIC(NumCCCopies, "Number of cross class copies");
42 static RegisterScheduler
43 burrListDAGScheduler("list-burr",
44 "Bottom-up register reduction list scheduling",
45 createBURRListDAGScheduler);
46 static RegisterScheduler
47 tdrListrDAGScheduler("list-tdrr",
48 "Top-down register reduction list scheduling",
49 createTDRRListDAGScheduler);
52 //===----------------------------------------------------------------------===//
53 /// ScheduleDAGRRList - The actual register reduction list scheduler
54 /// implementation. This supports both top-down and bottom-up scheduling.
56 class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
58 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
62 /// Fast - True if we are performing fast scheduling.
66 /// AvailableQueue - The priority queue to use for the available SUnits.
67 SchedulingPriorityQueue *AvailableQueue;
69 /// LiveRegDefs - A set of physical registers and their definition
70 /// that are "live". These nodes must be scheduled before any other nodes that
71 /// modifies the registers can be scheduled.
73 std::vector<SUnit*> LiveRegDefs;
74 std::vector<unsigned> LiveRegCycles;
77 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
78 const TargetMachine &tm, bool isbottomup, bool f,
79 SchedulingPriorityQueue *availqueue)
80 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup), Fast(f),
81 AvailableQueue(availqueue) {
84 ~ScheduleDAGRRList() {
85 delete AvailableQueue;
90 /// IsReachable - Checks if SU is reachable from TargetSU.
91 bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
93 /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
95 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
97 /// AddPred - This adds the specified node X as a predecessor of
98 /// the current node Y if not already.
99 /// This returns true if this is a new predecessor.
100 /// Updates the topological ordering if required.
101 bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
102 unsigned PhyReg = 0, int Cost = 1);
104 /// RemovePred - This removes the specified node N from the predecessors of
105 /// the current node M. Updates the topological ordering if required.
106 bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
109 void ReleasePred(SUnit*, bool, unsigned);
110 void ReleaseSucc(SUnit*, bool isChain, unsigned);
111 void CapturePred(SUnit*, SUnit*, bool);
112 void ScheduleNodeBottomUp(SUnit*, unsigned);
113 void ScheduleNodeTopDown(SUnit*, unsigned);
114 void UnscheduleNodeBottomUp(SUnit*);
115 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
116 SUnit *CopyAndMoveSuccessors(SUnit*);
117 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
118 const TargetRegisterClass*,
119 const TargetRegisterClass*,
120 SmallVector<SUnit*, 2>&);
121 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
122 void ListScheduleTopDown();
123 void ListScheduleBottomUp();
124 void CommuteNodesToReducePressure();
127 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
128 /// Updates the topological ordering if required.
129 SUnit *CreateNewSUnit(SDNode *N) {
130 SUnit *NewNode = NewSUnit(N);
131 // Update the topological ordering.
132 if (NewNode->NodeNum >= Node2Index.size())
133 InitDAGTopologicalSorting();
137 /// CreateClone - Creates a new SUnit from an existing one.
138 /// Updates the topological ordering if required.
139 SUnit *CreateClone(SUnit *N) {
140 SUnit *NewNode = Clone(N);
141 // Update the topological ordering.
142 if (NewNode->NodeNum >= Node2Index.size())
143 InitDAGTopologicalSorting();
147 /// Functions for preserving the topological ordering
148 /// even after dynamic insertions of new edges.
149 /// This allows a very fast implementation of IsReachable.
151 /// InitDAGTopologicalSorting - create the initial topological
152 /// ordering from the DAG to be scheduled.
153 void InitDAGTopologicalSorting();
155 /// DFS - make a DFS traversal and mark all nodes affected by the
156 /// edge insertion. These nodes will later get new topological indexes
157 /// by means of the Shift method.
158 void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
160 /// Shift - reassign topological indexes for the nodes in the DAG
161 /// to preserve the topological ordering.
162 void Shift(BitVector& Visited, int LowerBound, int UpperBound);
164 /// Allocate - assign the topological index to the node n.
165 void Allocate(int n, int index);
167 /// Index2Node - Maps topological index to the node number.
168 std::vector<int> Index2Node;
169 /// Node2Index - Maps the node number to its topological index.
170 std::vector<int> Node2Index;
171 /// Visited - a set of nodes visited during a DFS traversal.
174 } // end anonymous namespace
177 /// Schedule - Schedule the DAG using list scheduling.
178 void ScheduleDAGRRList::Schedule() {
179 DOUT << "********** List Scheduling **********\n";
182 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
183 LiveRegCycles.resize(TRI->getNumRegs(), 0);
185 // Build scheduling units.
188 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
189 SUnits[su].dumpAll(&DAG));
194 InitDAGTopologicalSorting();
196 AvailableQueue->initNodes(SUnits);
198 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
200 ListScheduleBottomUp();
202 ListScheduleTopDown();
204 AvailableQueue->releaseState();
207 CommuteNodesToReducePressure();
210 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
211 /// it is not the last use of its first operand, add it to the CommuteSet if
212 /// possible. It will be commuted when it is translated to a MI.
213 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
214 SmallPtrSet<SUnit*, 4> OperandSeen;
215 for (unsigned i = Sequence.size(); i != 0; ) {
217 SUnit *SU = Sequence[i];
218 if (!SU || !SU->Node) continue;
219 if (SU->isCommutable) {
220 unsigned Opc = SU->Node->getMachineOpcode();
221 const TargetInstrDesc &TID = TII->get(Opc);
222 unsigned NumRes = TID.getNumDefs();
223 unsigned NumOps = TID.getNumOperands() - NumRes;
224 for (unsigned j = 0; j != NumOps; ++j) {
225 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
228 SDNode *OpN = SU->Node->getOperand(j).getNode();
229 SUnit *OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
230 if (OpSU && OperandSeen.count(OpSU) == 1) {
231 // Ok, so SU is not the last use of OpSU, but SU is two-address so
232 // it will clobber OpSU. Try to commute SU if no other source operands
234 bool DoCommute = true;
235 for (unsigned k = 0; k < NumOps; ++k) {
237 OpN = SU->Node->getOperand(k).getNode();
238 OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
239 if (OpSU && OperandSeen.count(OpSU) == 1) {
246 CommuteSet.insert(SU->Node);
249 // Only look at the first use&def node for now.
254 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
257 OperandSeen.insert(I->Dep->OrigNode);
262 //===----------------------------------------------------------------------===//
263 // Bottom-Up Scheduling
264 //===----------------------------------------------------------------------===//
266 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
267 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
268 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
270 // FIXME: the distance between two nodes is not always == the predecessor's
271 // latency. For example, the reader can very well read the register written
272 // by the predecessor later than the issue cycle. It also depends on the
273 // interrupt model (drain vs. freeze).
274 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
276 --PredSU->NumSuccsLeft;
279 if (PredSU->NumSuccsLeft < 0) {
280 cerr << "*** List scheduling failed! ***\n";
282 cerr << " has been released too many times!\n";
287 if (PredSU->NumSuccsLeft == 0) {
288 PredSU->isAvailable = true;
289 AvailableQueue->push(PredSU);
293 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
294 /// count of its predecessors. If a predecessor pending count is zero, add it to
295 /// the Available queue.
296 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
297 DOUT << "*** Scheduling [" << CurCycle << "]: ";
298 DEBUG(SU->dump(&DAG));
299 SU->Cycle = CurCycle;
301 AvailableQueue->ScheduledNode(SU);
303 // Bottom up: release predecessors
304 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
306 ReleasePred(I->Dep, I->isCtrl, CurCycle);
308 // This is a physical register dependency and it's impossible or
309 // expensive to copy the register. Make sure nothing that can
310 // clobber the register is scheduled between the predecessor and
312 if (!LiveRegDefs[I->Reg]) {
314 LiveRegDefs[I->Reg] = I->Dep;
315 LiveRegCycles[I->Reg] = CurCycle;
320 // Release all the implicit physical register defs that are live.
321 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
324 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
325 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
326 assert(LiveRegDefs[I->Reg] == SU &&
327 "Physical register dependency violated?");
329 LiveRegDefs[I->Reg] = NULL;
330 LiveRegCycles[I->Reg] = 0;
335 SU->isScheduled = true;
338 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
339 /// unscheduled, incrcease the succ left count of its predecessors. Remove
340 /// them from AvailableQueue if necessary.
341 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
342 unsigned CycleBound = 0;
343 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
347 CycleBound = std::max(CycleBound,
348 I->Dep->Cycle + PredSU->Latency);
351 if (PredSU->isAvailable) {
352 PredSU->isAvailable = false;
353 if (!PredSU->isPending)
354 AvailableQueue->remove(PredSU);
357 PredSU->CycleBound = CycleBound;
358 ++PredSU->NumSuccsLeft;
361 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
362 /// its predecessor states to reflect the change.
363 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
364 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
365 DEBUG(SU->dump(&DAG));
367 AvailableQueue->UnscheduledNode(SU);
369 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
371 CapturePred(I->Dep, SU, I->isCtrl);
372 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
373 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
374 assert(LiveRegDefs[I->Reg] == I->Dep &&
375 "Physical register dependency violated?");
377 LiveRegDefs[I->Reg] = NULL;
378 LiveRegCycles[I->Reg] = 0;
382 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
385 if (!LiveRegDefs[I->Reg]) {
386 LiveRegDefs[I->Reg] = SU;
389 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
390 LiveRegCycles[I->Reg] = I->Dep->Cycle;
395 SU->isScheduled = false;
396 SU->isAvailable = true;
397 AvailableQueue->push(SU);
400 /// IsReachable - Checks if SU is reachable from TargetSU.
401 bool ScheduleDAGRRList::IsReachable(const SUnit *SU, const SUnit *TargetSU) {
402 // If insertion of the edge SU->TargetSU would create a cycle
403 // then there is a path from TargetSU to SU.
404 int UpperBound, LowerBound;
405 LowerBound = Node2Index[TargetSU->NodeNum];
406 UpperBound = Node2Index[SU->NodeNum];
407 bool HasLoop = false;
408 // Is Ord(TargetSU) < Ord(SU) ?
409 if (LowerBound < UpperBound) {
411 // There may be a path from TargetSU to SU. Check for it.
412 DFS(TargetSU, UpperBound, HasLoop);
417 /// Allocate - assign the topological index to the node n.
418 inline void ScheduleDAGRRList::Allocate(int n, int index) {
419 Node2Index[n] = index;
420 Index2Node[index] = n;
423 /// InitDAGTopologicalSorting - create the initial topological
424 /// ordering from the DAG to be scheduled.
426 /// The idea of the algorithm is taken from
427 /// "Online algorithms for managing the topological order of
428 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
429 /// This is the MNR algorithm, which was first introduced by
430 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
431 /// "Maintaining a topological order under edge insertions".
433 /// Short description of the algorithm:
435 /// Topological ordering, ord, of a DAG maps each node to a topological
436 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
438 /// This means that if there is a path from the node X to the node Z,
439 /// then ord(X) < ord(Z).
441 /// This property can be used to check for reachability of nodes:
442 /// if Z is reachable from X, then an insertion of the edge Z->X would
445 /// The algorithm first computes a topological ordering for the DAG by
446 /// initializing the Index2Node and Node2Index arrays and then tries to keep
447 /// the ordering up-to-date after edge insertions by reordering the DAG.
449 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
450 /// the nodes reachable from Y, and then shifts them using Shift to lie
451 /// immediately after X in Index2Node.
452 void ScheduleDAGRRList::InitDAGTopologicalSorting() {
453 unsigned DAGSize = SUnits.size();
454 std::vector<SUnit*> WorkList;
455 WorkList.reserve(DAGSize);
457 Index2Node.resize(DAGSize);
458 Node2Index.resize(DAGSize);
460 // Initialize the data structures.
461 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
462 SUnit *SU = &SUnits[i];
463 int NodeNum = SU->NodeNum;
464 unsigned Degree = SU->Succs.size();
465 // Temporarily use the Node2Index array as scratch space for degree counts.
466 Node2Index[NodeNum] = Degree;
468 // Is it a node without dependencies?
470 assert(SU->Succs.empty() && "SUnit should have no successors");
471 // Collect leaf nodes.
472 WorkList.push_back(SU);
477 while (!WorkList.empty()) {
478 SUnit *SU = WorkList.back();
480 Allocate(SU->NodeNum, --Id);
481 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
484 if (!--Node2Index[SU->NodeNum])
485 // If all dependencies of the node are processed already,
486 // then the node can be computed now.
487 WorkList.push_back(SU);
491 Visited.resize(DAGSize);
494 // Check correctness of the ordering
495 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
496 SUnit *SU = &SUnits[i];
497 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
499 assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] &&
500 "Wrong topological sorting");
506 /// AddPred - adds an edge from SUnit X to SUnit Y.
507 /// Updates the topological ordering if required.
508 bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
509 unsigned PhyReg, int Cost) {
510 int UpperBound, LowerBound;
511 LowerBound = Node2Index[Y->NodeNum];
512 UpperBound = Node2Index[X->NodeNum];
513 bool HasLoop = false;
514 // Is Ord(X) < Ord(Y) ?
515 if (LowerBound < UpperBound) {
516 // Update the topological order.
518 DFS(Y, UpperBound, HasLoop);
519 assert(!HasLoop && "Inserted edge creates a loop!");
520 // Recompute topological indexes.
521 Shift(Visited, LowerBound, UpperBound);
523 // Now really insert the edge.
524 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
527 /// RemovePred - This removes the specified node N from the predecessors of
528 /// the current node M. Updates the topological ordering if required.
529 bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N,
530 bool isCtrl, bool isSpecial) {
531 // InitDAGTopologicalSorting();
532 return M->removePred(N, isCtrl, isSpecial);
535 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
536 /// all nodes affected by the edge insertion. These nodes will later get new
537 /// topological indexes by means of the Shift method.
538 void ScheduleDAGRRList::DFS(const SUnit *SU, int UpperBound, bool& HasLoop) {
539 std::vector<const SUnit*> WorkList;
540 WorkList.reserve(SUnits.size());
542 WorkList.push_back(SU);
543 while (!WorkList.empty()) {
544 SU = WorkList.back();
546 Visited.set(SU->NodeNum);
547 for (int I = SU->Succs.size()-1; I >= 0; --I) {
548 int s = SU->Succs[I].Dep->NodeNum;
549 if (Node2Index[s] == UpperBound) {
553 // Visit successors if not already and in affected region.
554 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
555 WorkList.push_back(SU->Succs[I].Dep);
561 /// Shift - Renumber the nodes so that the topological ordering is
563 void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound,
569 for (i = LowerBound; i <= UpperBound; ++i) {
570 // w is node at topological index i.
571 int w = Index2Node[i];
572 if (Visited.test(w)) {
578 Allocate(w, i - shift);
582 for (unsigned j = 0; j < L.size(); ++j) {
583 Allocate(L[j], i - shift);
589 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
591 bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
592 if (IsReachable(TargetSU, SU))
594 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
596 if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
601 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
602 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
603 /// SUnit. Also returns if a successor is unscheduled in the process.
604 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
605 unsigned &CurCycle) {
607 while (CurCycle > BtCycle) {
608 OldSU = Sequence.back();
610 if (SU->isSucc(OldSU))
611 // Don't try to remove SU from AvailableQueue.
612 SU->isAvailable = false;
613 UnscheduleNodeBottomUp(OldSU);
618 if (SU->isSucc(OldSU)) {
619 assert(false && "Something is wrong!");
626 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
627 /// successors to the newly created node.
628 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
629 if (SU->FlaggedNodes.size())
632 SDNode *N = SU->Node;
637 bool TryUnfold = false;
638 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
639 MVT VT = N->getValueType(i);
642 else if (VT == MVT::Other)
645 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
646 const SDValue &Op = N->getOperand(i);
647 MVT VT = Op.getNode()->getValueType(Op.getResNo());
653 SmallVector<SDNode*, 2> NewNodes;
654 if (!TII->unfoldMemoryOperand(DAG, N, NewNodes))
657 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
658 assert(NewNodes.size() == 2 && "Expected a load folding node!");
661 SDNode *LoadNode = NewNodes[0];
662 unsigned NumVals = N->getNumValues();
663 unsigned OldNumVals = SU->Node->getNumValues();
664 for (unsigned i = 0; i != NumVals; ++i)
665 DAG.ReplaceAllUsesOfValueWith(SDValue(SU->Node, i), SDValue(N, i));
666 DAG.ReplaceAllUsesOfValueWith(SDValue(SU->Node, OldNumVals-1),
667 SDValue(LoadNode, 1));
669 SUnit *NewSU = CreateNewSUnit(N);
670 assert(N->getNodeId() == -1 && "Node already inserted!");
671 N->setNodeId(NewSU->NodeNum);
673 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
674 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
675 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
676 NewSU->isTwoAddress = true;
680 if (TID.isCommutable())
681 NewSU->isCommutable = true;
682 // FIXME: Calculate height / depth and propagate the changes?
683 NewSU->Depth = SU->Depth;
684 NewSU->Height = SU->Height;
685 ComputeLatency(NewSU);
687 // LoadNode may already exist. This can happen when there is another
688 // load from the same location and producing the same type of value
689 // but it has different alignment or volatileness.
690 bool isNewLoad = true;
692 if (LoadNode->getNodeId() != -1) {
693 LoadSU = &SUnits[LoadNode->getNodeId()];
696 LoadSU = CreateNewSUnit(LoadNode);
697 LoadNode->setNodeId(LoadSU->NodeNum);
699 LoadSU->Depth = SU->Depth;
700 LoadSU->Height = SU->Height;
701 ComputeLatency(LoadSU);
704 SUnit *ChainPred = NULL;
705 SmallVector<SDep, 4> ChainSuccs;
706 SmallVector<SDep, 4> LoadPreds;
707 SmallVector<SDep, 4> NodePreds;
708 SmallVector<SDep, 4> NodeSuccs;
709 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
713 else if (I->Dep->Node && I->Dep->Node->isOperandOf(LoadNode))
714 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
716 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
718 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
721 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
722 I->isCtrl, I->isSpecial));
724 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
725 I->isCtrl, I->isSpecial));
729 RemovePred(SU, ChainPred, true, false);
731 AddPred(LoadSU, ChainPred, true, false);
733 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
734 SDep *Pred = &LoadPreds[i];
735 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
737 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
738 Pred->Reg, Pred->Cost);
741 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
742 SDep *Pred = &NodePreds[i];
743 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
744 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
745 Pred->Reg, Pred->Cost);
747 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
748 SDep *Succ = &NodeSuccs[i];
749 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
750 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
751 Succ->Reg, Succ->Cost);
753 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
754 SDep *Succ = &ChainSuccs[i];
755 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
757 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
758 Succ->Reg, Succ->Cost);
762 AddPred(NewSU, LoadSU, false, false);
766 AvailableQueue->addNode(LoadSU);
767 AvailableQueue->addNode(NewSU);
771 if (NewSU->NumSuccsLeft == 0) {
772 NewSU->isAvailable = true;
778 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
779 NewSU = CreateClone(SU);
781 // New SUnit has the exact same predecessors.
782 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
785 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
786 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
789 // Only copy scheduled successors. Cut them from old node's successor
790 // list and move them over.
791 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
792 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
796 if (I->Dep->isScheduled) {
797 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
798 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
799 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
802 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
803 SUnit *Succ = DelDeps[i].first;
804 bool isCtrl = DelDeps[i].second;
805 RemovePred(Succ, SU, isCtrl, false);
808 AvailableQueue->updateNode(SU);
809 AvailableQueue->addNode(NewSU);
815 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
816 /// and move all scheduled successors of the given SUnit to the last copy.
817 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
818 const TargetRegisterClass *DestRC,
819 const TargetRegisterClass *SrcRC,
820 SmallVector<SUnit*, 2> &Copies) {
821 SUnit *CopyFromSU = CreateNewSUnit(NULL);
822 CopyFromSU->CopySrcRC = SrcRC;
823 CopyFromSU->CopyDstRC = DestRC;
824 CopyFromSU->Depth = SU->Depth;
825 CopyFromSU->Height = SU->Height;
827 SUnit *CopyToSU = CreateNewSUnit(NULL);
828 CopyToSU->CopySrcRC = DestRC;
829 CopyToSU->CopyDstRC = SrcRC;
831 // Only copy scheduled successors. Cut them from old node's successor
832 // list and move them over.
833 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
834 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
838 if (I->Dep->isScheduled) {
839 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
840 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
841 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
844 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
845 SUnit *Succ = DelDeps[i].first;
846 bool isCtrl = DelDeps[i].second;
847 RemovePred(Succ, SU, isCtrl, false);
850 AddPred(CopyFromSU, SU, false, false, Reg, -1);
851 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
853 AvailableQueue->updateNode(SU);
854 AvailableQueue->addNode(CopyFromSU);
855 AvailableQueue->addNode(CopyToSU);
856 Copies.push_back(CopyFromSU);
857 Copies.push_back(CopyToSU);
862 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
863 /// definition of the specified node.
864 /// FIXME: Move to SelectionDAG?
865 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
866 const TargetInstrInfo *TII) {
867 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
868 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
869 unsigned NumRes = TID.getNumDefs();
870 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
875 return N->getValueType(NumRes);
878 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
879 /// scheduling of the given node to satisfy live physical register dependencies.
880 /// If the specific node is the last one that's available to schedule, do
881 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
882 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
883 SmallVector<unsigned, 4> &LRegs){
884 if (NumLiveRegs == 0)
887 SmallSet<unsigned, 4> RegAdded;
888 // If this node would clobber any "live" register, then it's not ready.
889 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
892 unsigned Reg = I->Reg;
893 if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->Dep) {
894 if (RegAdded.insert(Reg))
895 LRegs.push_back(Reg);
897 for (const unsigned *Alias = TRI->getAliasSet(Reg);
899 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->Dep) {
900 if (RegAdded.insert(*Alias))
901 LRegs.push_back(*Alias);
906 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
907 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
908 if (!Node || !Node->isMachineOpcode())
910 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
911 if (!TID.ImplicitDefs)
913 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
914 if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
915 if (RegAdded.insert(*Reg))
916 LRegs.push_back(*Reg);
918 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
920 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
921 if (RegAdded.insert(*Alias))
922 LRegs.push_back(*Alias);
926 return !LRegs.empty();
930 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
932 void ScheduleDAGRRList::ListScheduleBottomUp() {
933 unsigned CurCycle = 0;
934 // Add root to Available queue.
935 if (!SUnits.empty()) {
936 SUnit *RootSU = &SUnits[DAG.getRoot().getNode()->getNodeId()];
937 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
938 RootSU->isAvailable = true;
939 AvailableQueue->push(RootSU);
942 // While Available queue is not empty, grab the node with the highest
943 // priority. If it is not ready put it back. Schedule the node.
944 SmallVector<SUnit*, 4> NotReady;
945 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
946 Sequence.reserve(SUnits.size());
947 while (!AvailableQueue->empty()) {
948 bool Delayed = false;
950 SUnit *CurSU = AvailableQueue->pop();
952 if (CurSU->CycleBound <= CurCycle) {
953 SmallVector<unsigned, 4> LRegs;
954 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
957 LRegsMap.insert(std::make_pair(CurSU, LRegs));
960 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
961 NotReady.push_back(CurSU);
962 CurSU = AvailableQueue->pop();
965 // All candidates are delayed due to live physical reg dependencies.
966 // Try backtracking, code duplication, or inserting cross class copies
968 if (Delayed && !CurSU) {
969 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
970 SUnit *TrySU = NotReady[i];
971 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
973 // Try unscheduling up to the point where it's safe to schedule
975 unsigned LiveCycle = CurCycle;
976 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
977 unsigned Reg = LRegs[j];
978 unsigned LCycle = LiveRegCycles[Reg];
979 LiveCycle = std::min(LiveCycle, LCycle);
981 SUnit *OldSU = Sequence[LiveCycle];
982 if (!WillCreateCycle(TrySU, OldSU)) {
983 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
984 // Force the current node to be scheduled before the node that
985 // requires the physical reg dep.
986 if (OldSU->isAvailable) {
987 OldSU->isAvailable = false;
988 AvailableQueue->remove(OldSU);
990 AddPred(TrySU, OldSU, true, true);
991 // If one or more successors has been unscheduled, then the current
992 // node is no longer avaialable. Schedule a successor that's now
993 // available instead.
994 if (!TrySU->isAvailable)
995 CurSU = AvailableQueue->pop();
998 TrySU->isPending = false;
999 NotReady.erase(NotReady.begin()+i);
1006 // Can't backtrack. Try duplicating the nodes that produces these
1007 // "expensive to copy" values to break the dependency. In case even
1008 // that doesn't work, insert cross class copies.
1009 SUnit *TrySU = NotReady[0];
1010 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1011 assert(LRegs.size() == 1 && "Can't handle this yet!");
1012 unsigned Reg = LRegs[0];
1013 SUnit *LRDef = LiveRegDefs[Reg];
1014 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1016 // Issue expensive cross register class copies.
1017 MVT VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
1018 const TargetRegisterClass *RC =
1019 TRI->getPhysicalRegisterRegClass(Reg, VT);
1020 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1022 assert(false && "Don't know how to copy this physical register!");
1025 SmallVector<SUnit*, 2> Copies;
1026 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1027 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1028 << " to SU #" << Copies.front()->NodeNum << "\n";
1029 AddPred(TrySU, Copies.front(), true, true);
1030 NewDef = Copies.back();
1033 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1034 << " to SU #" << TrySU->NodeNum << "\n";
1035 LiveRegDefs[Reg] = NewDef;
1036 AddPred(NewDef, TrySU, true, true);
1037 TrySU->isAvailable = false;
1042 assert(false && "Unable to resolve live physical register dependencies!");
1047 // Add the nodes that aren't ready back onto the available list.
1048 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1049 NotReady[i]->isPending = false;
1050 // May no longer be available due to backtracking.
1051 if (NotReady[i]->isAvailable)
1052 AvailableQueue->push(NotReady[i]);
1057 Sequence.push_back(0);
1059 ScheduleNodeBottomUp(CurSU, CurCycle);
1060 Sequence.push_back(CurSU);
1065 // Reverse the order if it is bottom up.
1066 std::reverse(Sequence.begin(), Sequence.end());
1070 // Verify that all SUnits were scheduled.
1071 bool AnyNotSched = false;
1072 unsigned DeadNodes = 0;
1074 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1075 if (!SUnits[i].isScheduled) {
1076 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1081 cerr << "*** List scheduling failed! ***\n";
1082 SUnits[i].dump(&DAG);
1083 cerr << "has not been scheduled!\n";
1086 if (SUnits[i].NumSuccsLeft != 0) {
1088 cerr << "*** List scheduling failed! ***\n";
1089 SUnits[i].dump(&DAG);
1090 cerr << "has successors left!\n";
1094 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1097 assert(!AnyNotSched);
1098 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1099 "The number of nodes scheduled doesn't match the expected number!");
1103 //===----------------------------------------------------------------------===//
1104 // Top-Down Scheduling
1105 //===----------------------------------------------------------------------===//
1107 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1108 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1109 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
1110 unsigned CurCycle) {
1111 // FIXME: the distance between two nodes is not always == the predecessor's
1112 // latency. For example, the reader can very well read the register written
1113 // by the predecessor later than the issue cycle. It also depends on the
1114 // interrupt model (drain vs. freeze).
1115 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
1117 --SuccSU->NumPredsLeft;
1120 if (SuccSU->NumPredsLeft < 0) {
1121 cerr << "*** List scheduling failed! ***\n";
1123 cerr << " has been released too many times!\n";
1128 if (SuccSU->NumPredsLeft == 0) {
1129 SuccSU->isAvailable = true;
1130 AvailableQueue->push(SuccSU);
1135 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1136 /// count of its successors. If a successor pending count is zero, add it to
1137 /// the Available queue.
1138 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1139 DOUT << "*** Scheduling [" << CurCycle << "]: ";
1140 DEBUG(SU->dump(&DAG));
1141 SU->Cycle = CurCycle;
1143 AvailableQueue->ScheduledNode(SU);
1145 // Top down: release successors
1146 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1148 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
1149 SU->isScheduled = true;
1152 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1154 void ScheduleDAGRRList::ListScheduleTopDown() {
1155 unsigned CurCycle = 0;
1157 // All leaves to Available queue.
1158 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1159 // It is available if it has no predecessors.
1160 if (SUnits[i].Preds.empty()) {
1161 AvailableQueue->push(&SUnits[i]);
1162 SUnits[i].isAvailable = true;
1166 // While Available queue is not empty, grab the node with the highest
1167 // priority. If it is not ready put it back. Schedule the node.
1168 std::vector<SUnit*> NotReady;
1169 Sequence.reserve(SUnits.size());
1170 while (!AvailableQueue->empty()) {
1171 SUnit *CurSU = AvailableQueue->pop();
1172 while (CurSU && CurSU->CycleBound > CurCycle) {
1173 NotReady.push_back(CurSU);
1174 CurSU = AvailableQueue->pop();
1177 // Add the nodes that aren't ready back onto the available list.
1178 AvailableQueue->push_all(NotReady);
1182 Sequence.push_back(0);
1184 ScheduleNodeTopDown(CurSU, CurCycle);
1185 Sequence.push_back(CurSU);
1192 // Verify that all SUnits were scheduled.
1193 bool AnyNotSched = false;
1194 unsigned DeadNodes = 0;
1196 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1197 if (!SUnits[i].isScheduled) {
1198 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1203 cerr << "*** List scheduling failed! ***\n";
1204 SUnits[i].dump(&DAG);
1205 cerr << "has not been scheduled!\n";
1208 if (SUnits[i].NumPredsLeft != 0) {
1210 cerr << "*** List scheduling failed! ***\n";
1211 SUnits[i].dump(&DAG);
1212 cerr << "has predecessors left!\n";
1216 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1219 assert(!AnyNotSched);
1220 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1221 "The number of nodes scheduled doesn't match the expected number!");
1227 //===----------------------------------------------------------------------===//
1228 // RegReductionPriorityQueue Implementation
1229 //===----------------------------------------------------------------------===//
1231 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1232 // to reduce register pressure.
1236 class RegReductionPriorityQueue;
1238 /// Sorting functions for the Available queue.
1239 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1240 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1241 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1242 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1244 bool operator()(const SUnit* left, const SUnit* right) const;
1247 struct bu_ls_rr_fast_sort : public std::binary_function<SUnit*, SUnit*, bool>{
1248 RegReductionPriorityQueue<bu_ls_rr_fast_sort> *SPQ;
1249 bu_ls_rr_fast_sort(RegReductionPriorityQueue<bu_ls_rr_fast_sort> *spq)
1251 bu_ls_rr_fast_sort(const bu_ls_rr_fast_sort &RHS) : SPQ(RHS.SPQ) {}
1253 bool operator()(const SUnit* left, const SUnit* right) const;
1256 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1257 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1258 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1259 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1261 bool operator()(const SUnit* left, const SUnit* right) const;
1263 } // end anonymous namespace
1265 static inline bool isCopyFromLiveIn(const SUnit *SU) {
1266 SDNode *N = SU->Node;
1267 return N && N->getOpcode() == ISD::CopyFromReg &&
1268 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1271 /// CalcNodeBUSethiUllmanNumber - Compute Sethi Ullman number for bottom up
1272 /// scheduling. Smaller number is the higher priority.
1274 CalcNodeBUSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1275 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1276 if (SethiUllmanNumber != 0)
1277 return SethiUllmanNumber;
1280 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1282 if (I->isCtrl) continue; // ignore chain preds
1283 SUnit *PredSU = I->Dep;
1284 unsigned PredSethiUllman = CalcNodeBUSethiUllmanNumber(PredSU, SUNumbers);
1285 if (PredSethiUllman > SethiUllmanNumber) {
1286 SethiUllmanNumber = PredSethiUllman;
1288 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1292 SethiUllmanNumber += Extra;
1294 if (SethiUllmanNumber == 0)
1295 SethiUllmanNumber = 1;
1297 return SethiUllmanNumber;
1300 /// CalcNodeTDSethiUllmanNumber - Compute Sethi Ullman number for top down
1301 /// scheduling. Smaller number is the higher priority.
1303 CalcNodeTDSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1304 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1305 if (SethiUllmanNumber != 0)
1306 return SethiUllmanNumber;
1308 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1309 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1310 SethiUllmanNumber = 0xffff;
1311 else if (SU->NumSuccsLeft == 0)
1312 // If SU does not have a use, i.e. it doesn't produce a value that would
1313 // be consumed (e.g. store), then it terminates a chain of computation.
1314 // Give it a small SethiUllman number so it will be scheduled right before
1315 // its predecessors that it doesn't lengthen their live ranges.
1316 SethiUllmanNumber = 0;
1317 else if (SU->NumPredsLeft == 0 &&
1318 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1319 SethiUllmanNumber = 0xffff;
1322 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1324 if (I->isCtrl) continue; // ignore chain preds
1325 SUnit *PredSU = I->Dep;
1326 unsigned PredSethiUllman = CalcNodeTDSethiUllmanNumber(PredSU, SUNumbers);
1327 if (PredSethiUllman > SethiUllmanNumber) {
1328 SethiUllmanNumber = PredSethiUllman;
1330 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1334 SethiUllmanNumber += Extra;
1337 return SethiUllmanNumber;
1343 class VISIBILITY_HIDDEN RegReductionPriorityQueue
1344 : public SchedulingPriorityQueue {
1345 PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
1346 unsigned currentQueueId;
1349 RegReductionPriorityQueue() :
1350 Queue(SF(this)), currentQueueId(0) {}
1352 virtual void initNodes(std::vector<SUnit> &sunits) = 0;
1354 virtual void addNode(const SUnit *SU) = 0;
1356 virtual void updateNode(const SUnit *SU) = 0;
1358 virtual void releaseState() = 0;
1360 virtual unsigned getNodePriority(const SUnit *SU) const = 0;
1362 unsigned size() const { return Queue.size(); }
1364 bool empty() const { return Queue.empty(); }
1366 void push(SUnit *U) {
1367 assert(!U->NodeQueueId && "Node in the queue already");
1368 U->NodeQueueId = ++currentQueueId;
1372 void push_all(const std::vector<SUnit *> &Nodes) {
1373 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1378 if (empty()) return NULL;
1379 SUnit *V = Queue.top();
1385 void remove(SUnit *SU) {
1386 assert(!Queue.empty() && "Queue is empty!");
1387 assert(SU->NodeQueueId != 0 && "Not in queue!");
1388 Queue.erase_one(SU);
1389 SU->NodeQueueId = 0;
1393 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1394 : public RegReductionPriorityQueue<bu_ls_rr_sort> {
1395 // SUnits - The SUnits for the current graph.
1396 std::vector<SUnit> *SUnits;
1398 // SethiUllmanNumbers - The SethiUllman number for each node.
1399 std::vector<unsigned> SethiUllmanNumbers;
1401 const TargetInstrInfo *TII;
1402 const TargetRegisterInfo *TRI;
1403 ScheduleDAGRRList *scheduleDAG;
1406 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii,
1407 const TargetRegisterInfo *tri)
1408 : TII(tii), TRI(tri), scheduleDAG(NULL) {}
1410 void initNodes(std::vector<SUnit> &sunits) {
1412 // Add pseudo dependency edges for two-address nodes.
1413 AddPseudoTwoAddrDeps();
1414 // Calculate node priorities.
1415 CalculateSethiUllmanNumbers();
1418 void addNode(const SUnit *SU) {
1419 unsigned SUSize = SethiUllmanNumbers.size();
1420 if (SUnits->size() > SUSize)
1421 SethiUllmanNumbers.resize(SUSize*2, 0);
1422 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1425 void updateNode(const SUnit *SU) {
1426 SethiUllmanNumbers[SU->NodeNum] = 0;
1427 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1430 void releaseState() {
1432 SethiUllmanNumbers.clear();
1435 unsigned getNodePriority(const SUnit *SU) const {
1436 assert(SU->NodeNum < SethiUllmanNumbers.size());
1437 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1438 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1439 // CopyFromReg should be close to its def because it restricts
1440 // allocation choices. But if it is a livein then perhaps we want it
1441 // closer to its uses so it can be coalesced.
1443 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1444 // CopyToReg should be close to its uses to facilitate coalescing and
1447 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1448 Opc == TargetInstrInfo::INSERT_SUBREG)
1449 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1450 // facilitate coalescing.
1452 else if (SU->NumSuccs == 0)
1453 // If SU does not have a use, i.e. it doesn't produce a value that would
1454 // be consumed (e.g. store), then it terminates a chain of computation.
1455 // Give it a large SethiUllman number so it will be scheduled right
1456 // before its predecessors that it doesn't lengthen their live ranges.
1458 else if (SU->NumPreds == 0)
1459 // If SU does not have a def, schedule it close to its uses because it
1460 // does not lengthen any live ranges.
1463 return SethiUllmanNumbers[SU->NodeNum];
1466 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1467 scheduleDAG = scheduleDag;
1471 bool canClobber(const SUnit *SU, const SUnit *Op);
1472 void AddPseudoTwoAddrDeps();
1473 void CalculateSethiUllmanNumbers();
1477 class VISIBILITY_HIDDEN BURegReductionFastPriorityQueue
1478 : public RegReductionPriorityQueue<bu_ls_rr_fast_sort> {
1479 // SUnits - The SUnits for the current graph.
1480 const std::vector<SUnit> *SUnits;
1482 // SethiUllmanNumbers - The SethiUllman number for each node.
1483 std::vector<unsigned> SethiUllmanNumbers;
1485 explicit BURegReductionFastPriorityQueue() {}
1487 void initNodes(std::vector<SUnit> &sunits) {
1489 // Calculate node priorities.
1490 CalculateSethiUllmanNumbers();
1493 void addNode(const SUnit *SU) {
1494 unsigned SUSize = SethiUllmanNumbers.size();
1495 if (SUnits->size() > SUSize)
1496 SethiUllmanNumbers.resize(SUSize*2, 0);
1497 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1500 void updateNode(const SUnit *SU) {
1501 SethiUllmanNumbers[SU->NodeNum] = 0;
1502 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1505 void releaseState() {
1507 SethiUllmanNumbers.clear();
1510 unsigned getNodePriority(const SUnit *SU) const {
1511 return SethiUllmanNumbers[SU->NodeNum];
1515 void CalculateSethiUllmanNumbers();
1519 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1520 : public RegReductionPriorityQueue<td_ls_rr_sort> {
1521 // SUnits - The SUnits for the current graph.
1522 const std::vector<SUnit> *SUnits;
1524 // SethiUllmanNumbers - The SethiUllman number for each node.
1525 std::vector<unsigned> SethiUllmanNumbers;
1528 TDRegReductionPriorityQueue() {}
1530 void initNodes(std::vector<SUnit> &sunits) {
1532 // Calculate node priorities.
1533 CalculateSethiUllmanNumbers();
1536 void addNode(const SUnit *SU) {
1537 unsigned SUSize = SethiUllmanNumbers.size();
1538 if (SUnits->size() > SUSize)
1539 SethiUllmanNumbers.resize(SUSize*2, 0);
1540 CalcNodeTDSethiUllmanNumber(SU, SethiUllmanNumbers);
1543 void updateNode(const SUnit *SU) {
1544 SethiUllmanNumbers[SU->NodeNum] = 0;
1545 CalcNodeTDSethiUllmanNumber(SU, SethiUllmanNumbers);
1548 void releaseState() {
1550 SethiUllmanNumbers.clear();
1553 unsigned getNodePriority(const SUnit *SU) const {
1554 assert(SU->NodeNum < SethiUllmanNumbers.size());
1555 return SethiUllmanNumbers[SU->NodeNum];
1559 void CalculateSethiUllmanNumbers();
1563 /// closestSucc - Returns the scheduled cycle of the successor which is
1564 /// closet to the current cycle.
1565 static unsigned closestSucc(const SUnit *SU) {
1566 unsigned MaxCycle = 0;
1567 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1569 unsigned Cycle = I->Dep->Cycle;
1570 // If there are bunch of CopyToRegs stacked up, they should be considered
1571 // to be at the same position.
1572 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
1573 Cycle = closestSucc(I->Dep)+1;
1574 if (Cycle > MaxCycle)
1580 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1581 /// for scratch registers. Live-in operands and live-out results don't count
1582 /// since they are "fixed".
1583 static unsigned calcMaxScratches(const SUnit *SU) {
1584 unsigned Scratches = 0;
1585 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1587 if (I->isCtrl) continue; // ignore chain preds
1588 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyFromReg)
1591 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1593 if (I->isCtrl) continue; // ignore chain succs
1594 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyToReg)
1601 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1602 unsigned LPriority = SPQ->getNodePriority(left);
1603 unsigned RPriority = SPQ->getNodePriority(right);
1604 if (LPriority != RPriority)
1605 return LPriority > RPriority;
1607 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1612 // and the following instructions are both ready.
1616 // Then schedule t2 = op first.
1623 // This creates more short live intervals.
1624 unsigned LDist = closestSucc(left);
1625 unsigned RDist = closestSucc(right);
1627 return LDist < RDist;
1629 // Intuitively, it's good to push down instructions whose results are
1630 // liveout so their long live ranges won't conflict with other values
1631 // which are needed inside the BB. Further prioritize liveout instructions
1632 // by the number of operands which are calculated within the BB.
1633 unsigned LScratch = calcMaxScratches(left);
1634 unsigned RScratch = calcMaxScratches(right);
1635 if (LScratch != RScratch)
1636 return LScratch > RScratch;
1638 if (left->Height != right->Height)
1639 return left->Height > right->Height;
1641 if (left->Depth != right->Depth)
1642 return left->Depth < right->Depth;
1644 if (left->CycleBound != right->CycleBound)
1645 return left->CycleBound > right->CycleBound;
1647 assert(left->NodeQueueId && right->NodeQueueId &&
1648 "NodeQueueId cannot be zero");
1649 return (left->NodeQueueId > right->NodeQueueId);
1653 bu_ls_rr_fast_sort::operator()(const SUnit *left, const SUnit *right) const {
1654 unsigned LPriority = SPQ->getNodePriority(left);
1655 unsigned RPriority = SPQ->getNodePriority(right);
1656 if (LPriority != RPriority)
1657 return LPriority > RPriority;
1658 assert(left->NodeQueueId && right->NodeQueueId &&
1659 "NodeQueueId cannot be zero");
1660 return (left->NodeQueueId > right->NodeQueueId);
1664 BURegReductionPriorityQueue::canClobber(const SUnit *SU, const SUnit *Op) {
1665 if (SU->isTwoAddress) {
1666 unsigned Opc = SU->Node->getMachineOpcode();
1667 const TargetInstrDesc &TID = TII->get(Opc);
1668 unsigned NumRes = TID.getNumDefs();
1669 unsigned NumOps = TID.getNumOperands() - NumRes;
1670 for (unsigned i = 0; i != NumOps; ++i) {
1671 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1672 SDNode *DU = SU->Node->getOperand(i).getNode();
1673 if (DU->getNodeId() != -1 &&
1674 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1683 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1685 static bool hasCopyToRegUse(const SUnit *SU) {
1686 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1688 if (I->isCtrl) continue;
1689 const SUnit *SuccSU = I->Dep;
1690 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1696 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1697 /// physical register defs.
1698 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
1699 const TargetInstrInfo *TII,
1700 const TargetRegisterInfo *TRI) {
1701 SDNode *N = SuccSU->Node;
1702 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1703 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
1704 assert(ImpDefs && "Caller should check hasPhysRegDefs");
1705 const unsigned *SUImpDefs =
1706 TII->get(SU->Node->getMachineOpcode()).getImplicitDefs();
1709 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1710 MVT VT = N->getValueType(i);
1711 if (VT == MVT::Flag || VT == MVT::Other)
1713 if (!N->hasAnyUseOfValue(i))
1715 unsigned Reg = ImpDefs[i - NumDefs];
1716 for (;*SUImpDefs; ++SUImpDefs) {
1717 unsigned SUReg = *SUImpDefs;
1718 if (TRI->regsOverlap(Reg, SUReg))
1725 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1726 /// it as a def&use operand. Add a pseudo control edge from it to the other
1727 /// node (if it won't create a cycle) so the two-address one will be scheduled
1728 /// first (lower in the schedule). If both nodes are two-address, favor the
1729 /// one that has a CopyToReg use (more likely to be a loop induction update).
1730 /// If both are two-address, but one is commutable while the other is not
1731 /// commutable, favor the one that's not commutable.
1732 void BURegReductionPriorityQueue::AddPseudoTwoAddrDeps() {
1733 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1734 SUnit *SU = &(*SUnits)[i];
1735 if (!SU->isTwoAddress)
1738 SDNode *Node = SU->Node;
1739 if (!Node || !Node->isMachineOpcode() || SU->FlaggedNodes.size() > 0)
1742 unsigned Opc = Node->getMachineOpcode();
1743 const TargetInstrDesc &TID = TII->get(Opc);
1744 unsigned NumRes = TID.getNumDefs();
1745 unsigned NumOps = TID.getNumOperands() - NumRes;
1746 for (unsigned j = 0; j != NumOps; ++j) {
1747 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) != -1) {
1748 SDNode *DU = SU->Node->getOperand(j).getNode();
1749 if (DU->getNodeId() == -1)
1751 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1752 if (!DUSU) continue;
1753 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1754 E = DUSU->Succs.end(); I != E; ++I) {
1755 if (I->isCtrl) continue;
1756 SUnit *SuccSU = I->Dep;
1759 // Be conservative. Ignore if nodes aren't at roughly the same
1760 // depth and height.
1761 if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1763 if (!SuccSU->Node || !SuccSU->Node->isMachineOpcode())
1765 // Don't constrain nodes with physical register defs if the
1766 // predecessor can clobber them.
1767 if (SuccSU->hasPhysRegDefs) {
1768 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1771 // Don't constraint extract_subreg / insert_subreg these may be
1772 // coalesced away. We don't them close to their uses.
1773 unsigned SuccOpc = SuccSU->Node->getMachineOpcode();
1774 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1775 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1777 if ((!canClobber(SuccSU, DUSU) ||
1778 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1779 (!SU->isCommutable && SuccSU->isCommutable)) &&
1780 !scheduleDAG->IsReachable(SuccSU, SU)) {
1781 DOUT << "Adding an edge from SU # " << SU->NodeNum
1782 << " to SU #" << SuccSU->NodeNum << "\n";
1783 scheduleDAG->AddPred(SU, SuccSU, true, true);
1791 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1792 /// scheduling units.
1793 void BURegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1794 SethiUllmanNumbers.assign(SUnits->size(), 0);
1796 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1797 CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1799 void BURegReductionFastPriorityQueue::CalculateSethiUllmanNumbers() {
1800 SethiUllmanNumbers.assign(SUnits->size(), 0);
1802 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1803 CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1806 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1807 /// predecessors of the successors of the SUnit SU. Stop when the provided
1808 /// limit is exceeded.
1809 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
1812 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1814 const SUnit *SuccSU = I->Dep;
1815 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1816 EE = SuccSU->Preds.end(); II != EE; ++II) {
1817 SUnit *PredSU = II->Dep;
1818 if (!PredSU->isScheduled)
1828 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1829 unsigned LPriority = SPQ->getNodePriority(left);
1830 unsigned RPriority = SPQ->getNodePriority(right);
1831 bool LIsTarget = left->Node && left->Node->isMachineOpcode();
1832 bool RIsTarget = right->Node && right->Node->isMachineOpcode();
1833 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1834 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1835 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1836 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1838 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1840 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1847 if (left->NumSuccs == 1)
1849 if (right->NumSuccs == 1)
1852 if (LPriority+LBonus != RPriority+RBonus)
1853 return LPriority+LBonus < RPriority+RBonus;
1855 if (left->Depth != right->Depth)
1856 return left->Depth < right->Depth;
1858 if (left->NumSuccsLeft != right->NumSuccsLeft)
1859 return left->NumSuccsLeft > right->NumSuccsLeft;
1861 if (left->CycleBound != right->CycleBound)
1862 return left->CycleBound > right->CycleBound;
1864 assert(left->NodeQueueId && right->NodeQueueId &&
1865 "NodeQueueId cannot be zero");
1866 return (left->NodeQueueId > right->NodeQueueId);
1869 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1870 /// scheduling units.
1871 void TDRegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1872 SethiUllmanNumbers.assign(SUnits->size(), 0);
1874 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1875 CalcNodeTDSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1878 //===----------------------------------------------------------------------===//
1879 // Public Constructor Functions
1880 //===----------------------------------------------------------------------===//
1882 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1884 MachineBasicBlock *BB,
1887 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true, true,
1888 new BURegReductionFastPriorityQueue());
1890 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
1891 const TargetRegisterInfo *TRI = DAG->getTarget().getRegisterInfo();
1893 BURegReductionPriorityQueue *PQ = new BURegReductionPriorityQueue(TII, TRI);
1895 ScheduleDAGRRList *SD =
1896 new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(),true,false, PQ);
1897 PQ->setScheduleDAG(SD);
1901 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1903 MachineBasicBlock *BB,
1905 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false, Fast,
1906 new TDRegReductionPriorityQueue());