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 *SU, SUnit *PredSU, bool isChain);
110 void ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain);
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(this));
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->getNode()) continue;
219 if (SU->isCommutable) {
220 unsigned Opc = SU->getNode()->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->getNode()->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->getNode()->getOperand(k).getNode();
238 OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
239 if (OpSU && OperandSeen.count(OpSU) == 1) {
246 CommuteSet.insert(SU->getNode());
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 *SU, SUnit *PredSU, bool isChain) {
269 --PredSU->NumSuccsLeft;
272 if (PredSU->NumSuccsLeft < 0) {
273 cerr << "*** Scheduling failed! ***\n";
275 cerr << " has been released too many times!\n";
280 // Compute how many cycles it will be before this actually becomes
281 // available. This is the max of the start time of all predecessors plus
283 // If this is a token edge, we don't need to wait for the latency of the
284 // preceeding instruction (e.g. a long-latency load) unless there is also
285 // some other data dependence.
286 unsigned PredDoneCycle = SU->Cycle;
288 PredDoneCycle += PredSU->Latency;
289 else if (SU->Latency)
291 PredSU->CycleBound = std::max(PredSU->CycleBound, PredDoneCycle);
293 if (PredSU->NumSuccsLeft == 0) {
294 PredSU->isAvailable = true;
295 AvailableQueue->push(PredSU);
299 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
300 /// count of its predecessors. If a predecessor pending count is zero, add it to
301 /// the Available queue.
302 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
303 DOUT << "*** Scheduling [" << CurCycle << "]: ";
304 DEBUG(SU->dump(this));
306 SU->Cycle = CurCycle;
307 Sequence.push_back(SU);
309 // Bottom up: release predecessors
310 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
312 ReleasePred(SU, I->Dep, I->isCtrl);
314 // This is a physical register dependency and it's impossible or
315 // expensive to copy the register. Make sure nothing that can
316 // clobber the register is scheduled between the predecessor and
318 if (!LiveRegDefs[I->Reg]) {
320 LiveRegDefs[I->Reg] = I->Dep;
321 LiveRegCycles[I->Reg] = CurCycle;
326 // Release all the implicit physical register defs that are live.
327 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
330 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
331 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
332 assert(LiveRegDefs[I->Reg] == SU &&
333 "Physical register dependency violated?");
335 LiveRegDefs[I->Reg] = NULL;
336 LiveRegCycles[I->Reg] = 0;
341 SU->isScheduled = true;
342 AvailableQueue->ScheduledNode(SU);
345 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
346 /// unscheduled, incrcease the succ left count of its predecessors. Remove
347 /// them from AvailableQueue if necessary.
348 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
349 unsigned CycleBound = 0;
350 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
354 CycleBound = std::max(CycleBound,
355 I->Dep->Cycle + PredSU->Latency);
358 if (PredSU->isAvailable) {
359 PredSU->isAvailable = false;
360 if (!PredSU->isPending)
361 AvailableQueue->remove(PredSU);
364 PredSU->CycleBound = CycleBound;
365 ++PredSU->NumSuccsLeft;
368 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
369 /// its predecessor states to reflect the change.
370 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
371 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
372 DEBUG(SU->dump(this));
374 AvailableQueue->UnscheduledNode(SU);
376 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
378 CapturePred(I->Dep, SU, I->isCtrl);
379 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
380 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
381 assert(LiveRegDefs[I->Reg] == I->Dep &&
382 "Physical register dependency violated?");
384 LiveRegDefs[I->Reg] = NULL;
385 LiveRegCycles[I->Reg] = 0;
389 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
392 if (!LiveRegDefs[I->Reg]) {
393 LiveRegDefs[I->Reg] = SU;
396 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
397 LiveRegCycles[I->Reg] = I->Dep->Cycle;
402 SU->isScheduled = false;
403 SU->isAvailable = true;
404 AvailableQueue->push(SU);
407 /// IsReachable - Checks if SU is reachable from TargetSU.
408 bool ScheduleDAGRRList::IsReachable(const SUnit *SU, const SUnit *TargetSU) {
409 // If insertion of the edge SU->TargetSU would create a cycle
410 // then there is a path from TargetSU to SU.
411 int UpperBound, LowerBound;
412 LowerBound = Node2Index[TargetSU->NodeNum];
413 UpperBound = Node2Index[SU->NodeNum];
414 bool HasLoop = false;
415 // Is Ord(TargetSU) < Ord(SU) ?
416 if (LowerBound < UpperBound) {
418 // There may be a path from TargetSU to SU. Check for it.
419 DFS(TargetSU, UpperBound, HasLoop);
424 /// Allocate - assign the topological index to the node n.
425 inline void ScheduleDAGRRList::Allocate(int n, int index) {
426 Node2Index[n] = index;
427 Index2Node[index] = n;
430 /// InitDAGTopologicalSorting - create the initial topological
431 /// ordering from the DAG to be scheduled.
433 /// The idea of the algorithm is taken from
434 /// "Online algorithms for managing the topological order of
435 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
436 /// This is the MNR algorithm, which was first introduced by
437 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
438 /// "Maintaining a topological order under edge insertions".
440 /// Short description of the algorithm:
442 /// Topological ordering, ord, of a DAG maps each node to a topological
443 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
445 /// This means that if there is a path from the node X to the node Z,
446 /// then ord(X) < ord(Z).
448 /// This property can be used to check for reachability of nodes:
449 /// if Z is reachable from X, then an insertion of the edge Z->X would
452 /// The algorithm first computes a topological ordering for the DAG by
453 /// initializing the Index2Node and Node2Index arrays and then tries to keep
454 /// the ordering up-to-date after edge insertions by reordering the DAG.
456 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
457 /// the nodes reachable from Y, and then shifts them using Shift to lie
458 /// immediately after X in Index2Node.
459 void ScheduleDAGRRList::InitDAGTopologicalSorting() {
460 unsigned DAGSize = SUnits.size();
461 std::vector<SUnit*> WorkList;
462 WorkList.reserve(DAGSize);
464 Index2Node.resize(DAGSize);
465 Node2Index.resize(DAGSize);
467 // Initialize the data structures.
468 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
469 SUnit *SU = &SUnits[i];
470 int NodeNum = SU->NodeNum;
471 unsigned Degree = SU->Succs.size();
472 // Temporarily use the Node2Index array as scratch space for degree counts.
473 Node2Index[NodeNum] = Degree;
475 // Is it a node without dependencies?
477 assert(SU->Succs.empty() && "SUnit should have no successors");
478 // Collect leaf nodes.
479 WorkList.push_back(SU);
484 while (!WorkList.empty()) {
485 SUnit *SU = WorkList.back();
487 Allocate(SU->NodeNum, --Id);
488 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
491 if (!--Node2Index[SU->NodeNum])
492 // If all dependencies of the node are processed already,
493 // then the node can be computed now.
494 WorkList.push_back(SU);
498 Visited.resize(DAGSize);
501 // Check correctness of the ordering
502 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
503 SUnit *SU = &SUnits[i];
504 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
506 assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] &&
507 "Wrong topological sorting");
513 /// AddPred - adds an edge from SUnit X to SUnit Y.
514 /// Updates the topological ordering if required.
515 bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
516 unsigned PhyReg, int Cost) {
517 int UpperBound, LowerBound;
518 LowerBound = Node2Index[Y->NodeNum];
519 UpperBound = Node2Index[X->NodeNum];
520 bool HasLoop = false;
521 // Is Ord(X) < Ord(Y) ?
522 if (LowerBound < UpperBound) {
523 // Update the topological order.
525 DFS(Y, UpperBound, HasLoop);
526 assert(!HasLoop && "Inserted edge creates a loop!");
527 // Recompute topological indexes.
528 Shift(Visited, LowerBound, UpperBound);
530 // Now really insert the edge.
531 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
534 /// RemovePred - This removes the specified node N from the predecessors of
535 /// the current node M. Updates the topological ordering if required.
536 bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N,
537 bool isCtrl, bool isSpecial) {
538 // InitDAGTopologicalSorting();
539 return M->removePred(N, isCtrl, isSpecial);
542 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
543 /// all nodes affected by the edge insertion. These nodes will later get new
544 /// topological indexes by means of the Shift method.
545 void ScheduleDAGRRList::DFS(const SUnit *SU, int UpperBound, bool& HasLoop) {
546 std::vector<const SUnit*> WorkList;
547 WorkList.reserve(SUnits.size());
549 WorkList.push_back(SU);
550 while (!WorkList.empty()) {
551 SU = WorkList.back();
553 Visited.set(SU->NodeNum);
554 for (int I = SU->Succs.size()-1; I >= 0; --I) {
555 int s = SU->Succs[I].Dep->NodeNum;
556 if (Node2Index[s] == UpperBound) {
560 // Visit successors if not already and in affected region.
561 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
562 WorkList.push_back(SU->Succs[I].Dep);
568 /// Shift - Renumber the nodes so that the topological ordering is
570 void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound,
576 for (i = LowerBound; i <= UpperBound; ++i) {
577 // w is node at topological index i.
578 int w = Index2Node[i];
579 if (Visited.test(w)) {
585 Allocate(w, i - shift);
589 for (unsigned j = 0; j < L.size(); ++j) {
590 Allocate(L[j], i - shift);
596 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
598 bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
599 if (IsReachable(TargetSU, SU))
601 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
603 if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
608 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
609 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
610 /// SUnit. Also returns if a successor is unscheduled in the process.
611 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
612 unsigned &CurCycle) {
614 while (CurCycle > BtCycle) {
615 OldSU = Sequence.back();
617 if (SU->isSucc(OldSU))
618 // Don't try to remove SU from AvailableQueue.
619 SU->isAvailable = false;
620 UnscheduleNodeBottomUp(OldSU);
625 if (SU->isSucc(OldSU)) {
626 assert(false && "Something is wrong!");
633 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
634 /// successors to the newly created node.
635 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
636 if (SU->getNode()->getFlaggedNode())
639 SDNode *N = SU->getNode();
644 bool TryUnfold = false;
645 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
646 MVT VT = N->getValueType(i);
649 else if (VT == MVT::Other)
652 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
653 const SDValue &Op = N->getOperand(i);
654 MVT VT = Op.getNode()->getValueType(Op.getResNo());
660 SmallVector<SDNode*, 2> NewNodes;
661 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
664 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
665 assert(NewNodes.size() == 2 && "Expected a load folding node!");
668 SDNode *LoadNode = NewNodes[0];
669 unsigned NumVals = N->getNumValues();
670 unsigned OldNumVals = SU->getNode()->getNumValues();
671 for (unsigned i = 0; i != NumVals; ++i)
672 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
673 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
674 SDValue(LoadNode, 1));
676 // LoadNode may already exist. This can happen when there is another
677 // load from the same location and producing the same type of value
678 // but it has different alignment or volatileness.
679 bool isNewLoad = true;
681 if (LoadNode->getNodeId() != -1) {
682 LoadSU = &SUnits[LoadNode->getNodeId()];
685 LoadSU = CreateNewSUnit(LoadNode);
686 LoadNode->setNodeId(LoadSU->NodeNum);
688 LoadSU->Depth = SU->Depth;
689 LoadSU->Height = SU->Height;
690 ComputeLatency(LoadSU);
693 SUnit *NewSU = CreateNewSUnit(N);
694 assert(N->getNodeId() == -1 && "Node already inserted!");
695 N->setNodeId(NewSU->NodeNum);
697 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
698 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
699 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
700 NewSU->isTwoAddress = true;
704 if (TID.isCommutable())
705 NewSU->isCommutable = true;
706 // FIXME: Calculate height / depth and propagate the changes?
707 NewSU->Depth = SU->Depth;
708 NewSU->Height = SU->Height;
709 ComputeLatency(NewSU);
711 SUnit *ChainPred = NULL;
712 SmallVector<SDep, 4> ChainSuccs;
713 SmallVector<SDep, 4> LoadPreds;
714 SmallVector<SDep, 4> NodePreds;
715 SmallVector<SDep, 4> NodeSuccs;
716 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
720 else if (I->Dep->getNode() && I->Dep->getNode()->isOperandOf(LoadNode))
721 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
723 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
725 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
728 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
729 I->isCtrl, I->isSpecial));
731 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
732 I->isCtrl, I->isSpecial));
736 RemovePred(SU, ChainPred, true, false);
738 AddPred(LoadSU, ChainPred, true, false);
740 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
741 SDep *Pred = &LoadPreds[i];
742 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
744 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
745 Pred->Reg, Pred->Cost);
748 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
749 SDep *Pred = &NodePreds[i];
750 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
751 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
752 Pred->Reg, Pred->Cost);
754 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
755 SDep *Succ = &NodeSuccs[i];
756 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
757 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
758 Succ->Reg, Succ->Cost);
760 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
761 SDep *Succ = &ChainSuccs[i];
762 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
764 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
765 Succ->Reg, Succ->Cost);
769 AddPred(NewSU, LoadSU, false, false);
773 AvailableQueue->addNode(LoadSU);
774 AvailableQueue->addNode(NewSU);
778 if (NewSU->NumSuccsLeft == 0) {
779 NewSU->isAvailable = true;
785 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
786 NewSU = CreateClone(SU);
788 // New SUnit has the exact same predecessors.
789 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
792 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
793 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
796 // Only copy scheduled successors. Cut them from old node's successor
797 // list and move them over.
798 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
799 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
803 if (I->Dep->isScheduled) {
804 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
805 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
806 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
809 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
810 SUnit *Succ = DelDeps[i].first;
811 bool isCtrl = DelDeps[i].second;
812 RemovePred(Succ, SU, isCtrl, false);
815 AvailableQueue->updateNode(SU);
816 AvailableQueue->addNode(NewSU);
822 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
823 /// and move all scheduled successors of the given SUnit to the last copy.
824 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
825 const TargetRegisterClass *DestRC,
826 const TargetRegisterClass *SrcRC,
827 SmallVector<SUnit*, 2> &Copies) {
828 SUnit *CopyFromSU = CreateNewSUnit(NULL);
829 CopyFromSU->CopySrcRC = SrcRC;
830 CopyFromSU->CopyDstRC = DestRC;
831 CopyFromSU->Depth = SU->Depth;
832 CopyFromSU->Height = SU->Height;
834 SUnit *CopyToSU = CreateNewSUnit(NULL);
835 CopyToSU->CopySrcRC = DestRC;
836 CopyToSU->CopyDstRC = SrcRC;
838 // Only copy scheduled successors. Cut them from old node's successor
839 // list and move them over.
840 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
841 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
845 if (I->Dep->isScheduled) {
846 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
847 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
848 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
851 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
852 SUnit *Succ = DelDeps[i].first;
853 bool isCtrl = DelDeps[i].second;
854 RemovePred(Succ, SU, isCtrl, false);
857 AddPred(CopyFromSU, SU, false, false, Reg, -1);
858 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
860 AvailableQueue->updateNode(SU);
861 AvailableQueue->addNode(CopyFromSU);
862 AvailableQueue->addNode(CopyToSU);
863 Copies.push_back(CopyFromSU);
864 Copies.push_back(CopyToSU);
869 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
870 /// definition of the specified node.
871 /// FIXME: Move to SelectionDAG?
872 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
873 const TargetInstrInfo *TII) {
874 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
875 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
876 unsigned NumRes = TID.getNumDefs();
877 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
882 return N->getValueType(NumRes);
885 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
886 /// scheduling of the given node to satisfy live physical register dependencies.
887 /// If the specific node is the last one that's available to schedule, do
888 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
889 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
890 SmallVector<unsigned, 4> &LRegs){
891 if (NumLiveRegs == 0)
894 SmallSet<unsigned, 4> RegAdded;
895 // If this node would clobber any "live" register, then it's not ready.
896 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
899 unsigned Reg = I->Reg;
900 if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->Dep) {
901 if (RegAdded.insert(Reg))
902 LRegs.push_back(Reg);
904 for (const unsigned *Alias = TRI->getAliasSet(Reg);
906 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->Dep) {
907 if (RegAdded.insert(*Alias))
908 LRegs.push_back(*Alias);
913 for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
914 if (!Node->isMachineOpcode())
916 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
917 if (!TID.ImplicitDefs)
919 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
920 if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
921 if (RegAdded.insert(*Reg))
922 LRegs.push_back(*Reg);
924 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
926 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
927 if (RegAdded.insert(*Alias))
928 LRegs.push_back(*Alias);
932 return !LRegs.empty();
936 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
938 void ScheduleDAGRRList::ListScheduleBottomUp() {
939 unsigned CurCycle = 0;
940 // Add root to Available queue.
941 if (!SUnits.empty()) {
942 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
943 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
944 RootSU->isAvailable = true;
945 AvailableQueue->push(RootSU);
948 // While Available queue is not empty, grab the node with the highest
949 // priority. If it is not ready put it back. Schedule the node.
950 SmallVector<SUnit*, 4> NotReady;
951 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
952 Sequence.reserve(SUnits.size());
953 while (!AvailableQueue->empty()) {
954 bool Delayed = false;
956 SUnit *CurSU = AvailableQueue->pop();
958 if (CurSU->CycleBound <= CurCycle) {
959 SmallVector<unsigned, 4> LRegs;
960 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
963 LRegsMap.insert(std::make_pair(CurSU, LRegs));
966 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
967 NotReady.push_back(CurSU);
968 CurSU = AvailableQueue->pop();
971 // All candidates are delayed due to live physical reg dependencies.
972 // Try backtracking, code duplication, or inserting cross class copies
974 if (Delayed && !CurSU) {
975 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
976 SUnit *TrySU = NotReady[i];
977 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
979 // Try unscheduling up to the point where it's safe to schedule
981 unsigned LiveCycle = CurCycle;
982 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
983 unsigned Reg = LRegs[j];
984 unsigned LCycle = LiveRegCycles[Reg];
985 LiveCycle = std::min(LiveCycle, LCycle);
987 SUnit *OldSU = Sequence[LiveCycle];
988 if (!WillCreateCycle(TrySU, OldSU)) {
989 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
990 // Force the current node to be scheduled before the node that
991 // requires the physical reg dep.
992 if (OldSU->isAvailable) {
993 OldSU->isAvailable = false;
994 AvailableQueue->remove(OldSU);
996 AddPred(TrySU, OldSU, true, true);
997 // If one or more successors has been unscheduled, then the current
998 // node is no longer avaialable. Schedule a successor that's now
999 // available instead.
1000 if (!TrySU->isAvailable)
1001 CurSU = AvailableQueue->pop();
1004 TrySU->isPending = false;
1005 NotReady.erase(NotReady.begin()+i);
1012 // Can't backtrack. Try duplicating the nodes that produces these
1013 // "expensive to copy" values to break the dependency. In case even
1014 // that doesn't work, insert cross class copies.
1015 SUnit *TrySU = NotReady[0];
1016 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1017 assert(LRegs.size() == 1 && "Can't handle this yet!");
1018 unsigned Reg = LRegs[0];
1019 SUnit *LRDef = LiveRegDefs[Reg];
1020 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1022 // Issue expensive cross register class copies.
1023 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1024 const TargetRegisterClass *RC =
1025 TRI->getPhysicalRegisterRegClass(Reg, VT);
1026 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1028 assert(false && "Don't know how to copy this physical register!");
1031 SmallVector<SUnit*, 2> Copies;
1032 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1033 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1034 << " to SU #" << Copies.front()->NodeNum << "\n";
1035 AddPred(TrySU, Copies.front(), true, true);
1036 NewDef = Copies.back();
1039 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1040 << " to SU #" << TrySU->NodeNum << "\n";
1041 LiveRegDefs[Reg] = NewDef;
1042 AddPred(NewDef, TrySU, true, true);
1043 TrySU->isAvailable = false;
1048 assert(false && "Unable to resolve live physical register dependencies!");
1053 // Add the nodes that aren't ready back onto the available list.
1054 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1055 NotReady[i]->isPending = false;
1056 // May no longer be available due to backtracking.
1057 if (NotReady[i]->isAvailable)
1058 AvailableQueue->push(NotReady[i]);
1063 Sequence.push_back(0);
1065 ScheduleNodeBottomUp(CurSU, CurCycle);
1069 // Reverse the order if it is bottom up.
1070 std::reverse(Sequence.begin(), Sequence.end());
1074 // Verify that all SUnits were scheduled.
1075 bool AnyNotSched = false;
1076 unsigned DeadNodes = 0;
1078 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1079 if (!SUnits[i].isScheduled) {
1080 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1085 cerr << "*** List scheduling failed! ***\n";
1086 SUnits[i].dump(this);
1087 cerr << "has not been scheduled!\n";
1090 if (SUnits[i].NumSuccsLeft != 0) {
1092 cerr << "*** List scheduling failed! ***\n";
1093 SUnits[i].dump(this);
1094 cerr << "has successors left!\n";
1098 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1101 assert(!AnyNotSched);
1102 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1103 "The number of nodes scheduled doesn't match the expected number!");
1107 //===----------------------------------------------------------------------===//
1108 // Top-Down Scheduling
1109 //===----------------------------------------------------------------------===//
1111 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1112 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1113 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain) {
1114 --SuccSU->NumPredsLeft;
1117 if (SuccSU->NumPredsLeft < 0) {
1118 cerr << "*** Scheduling failed! ***\n";
1120 cerr << " has been released too many times!\n";
1125 // Compute how many cycles it will be before this actually becomes
1126 // available. This is the max of the start time of all predecessors plus
1128 // If this is a token edge, we don't need to wait for the latency of the
1129 // preceeding instruction (e.g. a long-latency load) unless there is also
1130 // some other data dependence.
1131 unsigned PredDoneCycle = SU->Cycle;
1133 PredDoneCycle += SU->Latency;
1134 else if (SU->Latency)
1136 SuccSU->CycleBound = std::max(SuccSU->CycleBound, PredDoneCycle);
1138 if (SuccSU->NumPredsLeft == 0) {
1139 SuccSU->isAvailable = true;
1140 AvailableQueue->push(SuccSU);
1145 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1146 /// count of its successors. If a successor pending count is zero, add it to
1147 /// the Available queue.
1148 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1149 DOUT << "*** Scheduling [" << CurCycle << "]: ";
1150 DEBUG(SU->dump(this));
1152 SU->Cycle = CurCycle;
1153 Sequence.push_back(SU);
1155 // Top down: release successors
1156 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1158 ReleaseSucc(SU, I->Dep, I->isCtrl);
1160 SU->isScheduled = true;
1161 AvailableQueue->ScheduledNode(SU);
1164 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1166 void ScheduleDAGRRList::ListScheduleTopDown() {
1167 unsigned CurCycle = 0;
1169 // All leaves to Available queue.
1170 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1171 // It is available if it has no predecessors.
1172 if (SUnits[i].Preds.empty()) {
1173 AvailableQueue->push(&SUnits[i]);
1174 SUnits[i].isAvailable = true;
1178 // While Available queue is not empty, grab the node with the highest
1179 // priority. If it is not ready put it back. Schedule the node.
1180 std::vector<SUnit*> NotReady;
1181 Sequence.reserve(SUnits.size());
1182 while (!AvailableQueue->empty()) {
1183 SUnit *CurSU = AvailableQueue->pop();
1184 while (CurSU && CurSU->CycleBound > CurCycle) {
1185 NotReady.push_back(CurSU);
1186 CurSU = AvailableQueue->pop();
1189 // Add the nodes that aren't ready back onto the available list.
1190 AvailableQueue->push_all(NotReady);
1194 Sequence.push_back(0);
1196 ScheduleNodeTopDown(CurSU, CurCycle);
1202 // Verify that all SUnits were scheduled.
1203 bool AnyNotSched = false;
1204 unsigned DeadNodes = 0;
1206 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1207 if (!SUnits[i].isScheduled) {
1208 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1213 cerr << "*** List scheduling failed! ***\n";
1214 SUnits[i].dump(this);
1215 cerr << "has not been scheduled!\n";
1218 if (SUnits[i].NumPredsLeft != 0) {
1220 cerr << "*** List scheduling failed! ***\n";
1221 SUnits[i].dump(this);
1222 cerr << "has predecessors left!\n";
1226 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1229 assert(!AnyNotSched);
1230 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1231 "The number of nodes scheduled doesn't match the expected number!");
1237 //===----------------------------------------------------------------------===//
1238 // RegReductionPriorityQueue Implementation
1239 //===----------------------------------------------------------------------===//
1241 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1242 // to reduce register pressure.
1246 class RegReductionPriorityQueue;
1248 /// Sorting functions for the Available queue.
1249 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1250 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1251 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1252 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1254 bool operator()(const SUnit* left, const SUnit* right) const;
1257 struct bu_ls_rr_fast_sort : public std::binary_function<SUnit*, SUnit*, bool>{
1258 RegReductionPriorityQueue<bu_ls_rr_fast_sort> *SPQ;
1259 bu_ls_rr_fast_sort(RegReductionPriorityQueue<bu_ls_rr_fast_sort> *spq)
1261 bu_ls_rr_fast_sort(const bu_ls_rr_fast_sort &RHS) : SPQ(RHS.SPQ) {}
1263 bool operator()(const SUnit* left, const SUnit* right) const;
1266 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1267 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1268 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1269 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1271 bool operator()(const SUnit* left, const SUnit* right) const;
1273 } // end anonymous namespace
1275 static inline bool isCopyFromLiveIn(const SUnit *SU) {
1276 SDNode *N = SU->getNode();
1277 return N && N->getOpcode() == ISD::CopyFromReg &&
1278 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1281 /// CalcNodeBUSethiUllmanNumber - Compute Sethi Ullman number for bottom up
1282 /// scheduling. Smaller number is the higher priority.
1284 CalcNodeBUSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1285 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1286 if (SethiUllmanNumber != 0)
1287 return SethiUllmanNumber;
1290 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1292 if (I->isCtrl) continue; // ignore chain preds
1293 SUnit *PredSU = I->Dep;
1294 unsigned PredSethiUllman = CalcNodeBUSethiUllmanNumber(PredSU, SUNumbers);
1295 if (PredSethiUllman > SethiUllmanNumber) {
1296 SethiUllmanNumber = PredSethiUllman;
1298 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1302 SethiUllmanNumber += Extra;
1304 if (SethiUllmanNumber == 0)
1305 SethiUllmanNumber = 1;
1307 return SethiUllmanNumber;
1310 /// CalcNodeTDSethiUllmanNumber - Compute Sethi Ullman number for top down
1311 /// scheduling. Smaller number is the higher priority.
1313 CalcNodeTDSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1314 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1315 if (SethiUllmanNumber != 0)
1316 return SethiUllmanNumber;
1318 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1319 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1320 SethiUllmanNumber = 0xffff;
1321 else if (SU->NumSuccsLeft == 0)
1322 // If SU does not have a use, i.e. it doesn't produce a value that would
1323 // be consumed (e.g. store), then it terminates a chain of computation.
1324 // Give it a small SethiUllman number so it will be scheduled right before
1325 // its predecessors that it doesn't lengthen their live ranges.
1326 SethiUllmanNumber = 0;
1327 else if (SU->NumPredsLeft == 0 &&
1328 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1329 SethiUllmanNumber = 0xffff;
1332 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1334 if (I->isCtrl) continue; // ignore chain preds
1335 SUnit *PredSU = I->Dep;
1336 unsigned PredSethiUllman = CalcNodeTDSethiUllmanNumber(PredSU, SUNumbers);
1337 if (PredSethiUllman > SethiUllmanNumber) {
1338 SethiUllmanNumber = PredSethiUllman;
1340 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1344 SethiUllmanNumber += Extra;
1347 return SethiUllmanNumber;
1353 class VISIBILITY_HIDDEN RegReductionPriorityQueue
1354 : public SchedulingPriorityQueue {
1355 PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
1356 unsigned currentQueueId;
1359 RegReductionPriorityQueue() :
1360 Queue(SF(this)), currentQueueId(0) {}
1362 virtual void initNodes(std::vector<SUnit> &sunits) = 0;
1364 virtual void addNode(const SUnit *SU) = 0;
1366 virtual void updateNode(const SUnit *SU) = 0;
1368 virtual void releaseState() = 0;
1370 virtual unsigned getNodePriority(const SUnit *SU) const = 0;
1372 unsigned size() const { return Queue.size(); }
1374 bool empty() const { return Queue.empty(); }
1376 void push(SUnit *U) {
1377 assert(!U->NodeQueueId && "Node in the queue already");
1378 U->NodeQueueId = ++currentQueueId;
1382 void push_all(const std::vector<SUnit *> &Nodes) {
1383 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1388 if (empty()) return NULL;
1389 SUnit *V = Queue.top();
1395 void remove(SUnit *SU) {
1396 assert(!Queue.empty() && "Queue is empty!");
1397 assert(SU->NodeQueueId != 0 && "Not in queue!");
1398 Queue.erase_one(SU);
1399 SU->NodeQueueId = 0;
1403 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1404 : public RegReductionPriorityQueue<bu_ls_rr_sort> {
1405 // SUnits - The SUnits for the current graph.
1406 std::vector<SUnit> *SUnits;
1408 // SethiUllmanNumbers - The SethiUllman number for each node.
1409 std::vector<unsigned> SethiUllmanNumbers;
1411 const TargetInstrInfo *TII;
1412 const TargetRegisterInfo *TRI;
1413 ScheduleDAGRRList *scheduleDAG;
1416 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii,
1417 const TargetRegisterInfo *tri)
1418 : TII(tii), TRI(tri), scheduleDAG(NULL) {}
1420 void initNodes(std::vector<SUnit> &sunits) {
1422 // Add pseudo dependency edges for two-address nodes.
1423 AddPseudoTwoAddrDeps();
1424 // Calculate node priorities.
1425 CalculateSethiUllmanNumbers();
1428 void addNode(const SUnit *SU) {
1429 unsigned SUSize = SethiUllmanNumbers.size();
1430 if (SUnits->size() > SUSize)
1431 SethiUllmanNumbers.resize(SUSize*2, 0);
1432 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1435 void updateNode(const SUnit *SU) {
1436 SethiUllmanNumbers[SU->NodeNum] = 0;
1437 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1440 void releaseState() {
1442 SethiUllmanNumbers.clear();
1445 unsigned getNodePriority(const SUnit *SU) const {
1446 assert(SU->NodeNum < SethiUllmanNumbers.size());
1447 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1448 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1449 // CopyFromReg should be close to its def because it restricts
1450 // allocation choices. But if it is a livein then perhaps we want it
1451 // closer to its uses so it can be coalesced.
1453 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1454 // CopyToReg should be close to its uses to facilitate coalescing and
1457 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1458 Opc == TargetInstrInfo::INSERT_SUBREG)
1459 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1460 // facilitate coalescing.
1462 else if (SU->NumSuccs == 0)
1463 // If SU does not have a use, i.e. it doesn't produce a value that would
1464 // be consumed (e.g. store), then it terminates a chain of computation.
1465 // Give it a large SethiUllman number so it will be scheduled right
1466 // before its predecessors that it doesn't lengthen their live ranges.
1468 else if (SU->NumPreds == 0)
1469 // If SU does not have a def, schedule it close to its uses because it
1470 // does not lengthen any live ranges.
1473 return SethiUllmanNumbers[SU->NodeNum];
1476 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1477 scheduleDAG = scheduleDag;
1481 bool canClobber(const SUnit *SU, const SUnit *Op);
1482 void AddPseudoTwoAddrDeps();
1483 void CalculateSethiUllmanNumbers();
1487 class VISIBILITY_HIDDEN BURegReductionFastPriorityQueue
1488 : public RegReductionPriorityQueue<bu_ls_rr_fast_sort> {
1489 // SUnits - The SUnits for the current graph.
1490 const std::vector<SUnit> *SUnits;
1492 // SethiUllmanNumbers - The SethiUllman number for each node.
1493 std::vector<unsigned> SethiUllmanNumbers;
1495 explicit BURegReductionFastPriorityQueue() {}
1497 void initNodes(std::vector<SUnit> &sunits) {
1499 // Calculate node priorities.
1500 CalculateSethiUllmanNumbers();
1503 void addNode(const SUnit *SU) {
1504 unsigned SUSize = SethiUllmanNumbers.size();
1505 if (SUnits->size() > SUSize)
1506 SethiUllmanNumbers.resize(SUSize*2, 0);
1507 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1510 void updateNode(const SUnit *SU) {
1511 SethiUllmanNumbers[SU->NodeNum] = 0;
1512 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1515 void releaseState() {
1517 SethiUllmanNumbers.clear();
1520 unsigned getNodePriority(const SUnit *SU) const {
1521 return SethiUllmanNumbers[SU->NodeNum];
1525 void CalculateSethiUllmanNumbers();
1529 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1530 : public RegReductionPriorityQueue<td_ls_rr_sort> {
1531 // SUnits - The SUnits for the current graph.
1532 const std::vector<SUnit> *SUnits;
1534 // SethiUllmanNumbers - The SethiUllman number for each node.
1535 std::vector<unsigned> SethiUllmanNumbers;
1538 TDRegReductionPriorityQueue() {}
1540 void initNodes(std::vector<SUnit> &sunits) {
1542 // Calculate node priorities.
1543 CalculateSethiUllmanNumbers();
1546 void addNode(const SUnit *SU) {
1547 unsigned SUSize = SethiUllmanNumbers.size();
1548 if (SUnits->size() > SUSize)
1549 SethiUllmanNumbers.resize(SUSize*2, 0);
1550 CalcNodeTDSethiUllmanNumber(SU, SethiUllmanNumbers);
1553 void updateNode(const SUnit *SU) {
1554 SethiUllmanNumbers[SU->NodeNum] = 0;
1555 CalcNodeTDSethiUllmanNumber(SU, SethiUllmanNumbers);
1558 void releaseState() {
1560 SethiUllmanNumbers.clear();
1563 unsigned getNodePriority(const SUnit *SU) const {
1564 assert(SU->NodeNum < SethiUllmanNumbers.size());
1565 return SethiUllmanNumbers[SU->NodeNum];
1569 void CalculateSethiUllmanNumbers();
1573 /// closestSucc - Returns the scheduled cycle of the successor which is
1574 /// closet to the current cycle.
1575 static unsigned closestSucc(const SUnit *SU) {
1576 unsigned MaxCycle = 0;
1577 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1579 unsigned Cycle = I->Dep->Cycle;
1580 // If there are bunch of CopyToRegs stacked up, they should be considered
1581 // to be at the same position.
1582 if (I->Dep->getNode() && I->Dep->getNode()->getOpcode() == ISD::CopyToReg)
1583 Cycle = closestSucc(I->Dep)+1;
1584 if (Cycle > MaxCycle)
1590 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1591 /// for scratch registers. Live-in operands and live-out results don't count
1592 /// since they are "fixed".
1593 static unsigned calcMaxScratches(const SUnit *SU) {
1594 unsigned Scratches = 0;
1595 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1597 if (I->isCtrl) continue; // ignore chain preds
1598 if (!I->Dep->getNode() || I->Dep->getNode()->getOpcode() != ISD::CopyFromReg)
1601 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1603 if (I->isCtrl) continue; // ignore chain succs
1604 if (!I->Dep->getNode() || I->Dep->getNode()->getOpcode() != ISD::CopyToReg)
1611 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1612 unsigned LPriority = SPQ->getNodePriority(left);
1613 unsigned RPriority = SPQ->getNodePriority(right);
1614 if (LPriority != RPriority)
1615 return LPriority > RPriority;
1617 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1622 // and the following instructions are both ready.
1626 // Then schedule t2 = op first.
1633 // This creates more short live intervals.
1634 unsigned LDist = closestSucc(left);
1635 unsigned RDist = closestSucc(right);
1637 return LDist < RDist;
1639 // Intuitively, it's good to push down instructions whose results are
1640 // liveout so their long live ranges won't conflict with other values
1641 // which are needed inside the BB. Further prioritize liveout instructions
1642 // by the number of operands which are calculated within the BB.
1643 unsigned LScratch = calcMaxScratches(left);
1644 unsigned RScratch = calcMaxScratches(right);
1645 if (LScratch != RScratch)
1646 return LScratch > RScratch;
1648 if (left->Height != right->Height)
1649 return left->Height > right->Height;
1651 if (left->Depth != right->Depth)
1652 return left->Depth < right->Depth;
1654 if (left->CycleBound != right->CycleBound)
1655 return left->CycleBound > right->CycleBound;
1657 assert(left->NodeQueueId && right->NodeQueueId &&
1658 "NodeQueueId cannot be zero");
1659 return (left->NodeQueueId > right->NodeQueueId);
1663 bu_ls_rr_fast_sort::operator()(const SUnit *left, const SUnit *right) const {
1664 unsigned LPriority = SPQ->getNodePriority(left);
1665 unsigned RPriority = SPQ->getNodePriority(right);
1666 if (LPriority != RPriority)
1667 return LPriority > RPriority;
1668 assert(left->NodeQueueId && right->NodeQueueId &&
1669 "NodeQueueId cannot be zero");
1670 return (left->NodeQueueId > right->NodeQueueId);
1674 BURegReductionPriorityQueue::canClobber(const SUnit *SU, const SUnit *Op) {
1675 if (SU->isTwoAddress) {
1676 unsigned Opc = SU->getNode()->getMachineOpcode();
1677 const TargetInstrDesc &TID = TII->get(Opc);
1678 unsigned NumRes = TID.getNumDefs();
1679 unsigned NumOps = TID.getNumOperands() - NumRes;
1680 for (unsigned i = 0; i != NumOps; ++i) {
1681 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1682 SDNode *DU = SU->getNode()->getOperand(i).getNode();
1683 if (DU->getNodeId() != -1 &&
1684 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1693 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1695 static bool hasCopyToRegUse(const SUnit *SU) {
1696 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1698 if (I->isCtrl) continue;
1699 const SUnit *SuccSU = I->Dep;
1700 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg)
1706 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1707 /// physical register defs.
1708 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
1709 const TargetInstrInfo *TII,
1710 const TargetRegisterInfo *TRI) {
1711 SDNode *N = SuccSU->getNode();
1712 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1713 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
1714 assert(ImpDefs && "Caller should check hasPhysRegDefs");
1715 const unsigned *SUImpDefs =
1716 TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
1719 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1720 MVT VT = N->getValueType(i);
1721 if (VT == MVT::Flag || VT == MVT::Other)
1723 if (!N->hasAnyUseOfValue(i))
1725 unsigned Reg = ImpDefs[i - NumDefs];
1726 for (;*SUImpDefs; ++SUImpDefs) {
1727 unsigned SUReg = *SUImpDefs;
1728 if (TRI->regsOverlap(Reg, SUReg))
1735 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1736 /// it as a def&use operand. Add a pseudo control edge from it to the other
1737 /// node (if it won't create a cycle) so the two-address one will be scheduled
1738 /// first (lower in the schedule). If both nodes are two-address, favor the
1739 /// one that has a CopyToReg use (more likely to be a loop induction update).
1740 /// If both are two-address, but one is commutable while the other is not
1741 /// commutable, favor the one that's not commutable.
1742 void BURegReductionPriorityQueue::AddPseudoTwoAddrDeps() {
1743 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1744 SUnit *SU = &(*SUnits)[i];
1745 if (!SU->isTwoAddress)
1748 SDNode *Node = SU->getNode();
1749 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getFlaggedNode())
1752 unsigned Opc = Node->getMachineOpcode();
1753 const TargetInstrDesc &TID = TII->get(Opc);
1754 unsigned NumRes = TID.getNumDefs();
1755 unsigned NumOps = TID.getNumOperands() - NumRes;
1756 for (unsigned j = 0; j != NumOps; ++j) {
1757 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
1759 SDNode *DU = SU->getNode()->getOperand(j).getNode();
1760 if (DU->getNodeId() == -1)
1762 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1763 if (!DUSU) continue;
1764 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1765 E = DUSU->Succs.end(); I != E; ++I) {
1766 if (I->isCtrl) continue;
1767 SUnit *SuccSU = I->Dep;
1770 // Be conservative. Ignore if nodes aren't at roughly the same
1771 // depth and height.
1772 if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1774 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
1776 // Don't constrain nodes with physical register defs if the
1777 // predecessor can clobber them.
1778 if (SuccSU->hasPhysRegDefs) {
1779 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1782 // Don't constraint extract_subreg / insert_subreg these may be
1783 // coalesced away. We don't them close to their uses.
1784 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
1785 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1786 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1788 if ((!canClobber(SuccSU, DUSU) ||
1789 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1790 (!SU->isCommutable && SuccSU->isCommutable)) &&
1791 !scheduleDAG->IsReachable(SuccSU, SU)) {
1792 DOUT << "Adding an edge from SU # " << SU->NodeNum
1793 << " to SU #" << SuccSU->NodeNum << "\n";
1794 scheduleDAG->AddPred(SU, SuccSU, true, true);
1801 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1802 /// scheduling units.
1803 void BURegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1804 SethiUllmanNumbers.assign(SUnits->size(), 0);
1806 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1807 CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1809 void BURegReductionFastPriorityQueue::CalculateSethiUllmanNumbers() {
1810 SethiUllmanNumbers.assign(SUnits->size(), 0);
1812 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1813 CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1816 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1817 /// predecessors of the successors of the SUnit SU. Stop when the provided
1818 /// limit is exceeded.
1819 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
1822 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1824 const SUnit *SuccSU = I->Dep;
1825 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1826 EE = SuccSU->Preds.end(); II != EE; ++II) {
1827 SUnit *PredSU = II->Dep;
1828 if (!PredSU->isScheduled)
1838 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1839 unsigned LPriority = SPQ->getNodePriority(left);
1840 unsigned RPriority = SPQ->getNodePriority(right);
1841 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
1842 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
1843 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1844 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1845 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1846 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1848 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1850 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1857 if (left->NumSuccs == 1)
1859 if (right->NumSuccs == 1)
1862 if (LPriority+LBonus != RPriority+RBonus)
1863 return LPriority+LBonus < RPriority+RBonus;
1865 if (left->Depth != right->Depth)
1866 return left->Depth < right->Depth;
1868 if (left->NumSuccsLeft != right->NumSuccsLeft)
1869 return left->NumSuccsLeft > right->NumSuccsLeft;
1871 if (left->CycleBound != right->CycleBound)
1872 return left->CycleBound > right->CycleBound;
1874 assert(left->NodeQueueId && right->NodeQueueId &&
1875 "NodeQueueId cannot be zero");
1876 return (left->NodeQueueId > right->NodeQueueId);
1879 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1880 /// scheduling units.
1881 void TDRegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1882 SethiUllmanNumbers.assign(SUnits->size(), 0);
1884 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1885 CalcNodeTDSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1888 //===----------------------------------------------------------------------===//
1889 // Public Constructor Functions
1890 //===----------------------------------------------------------------------===//
1892 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1894 const TargetMachine *TM,
1895 MachineBasicBlock *BB,
1898 return new ScheduleDAGRRList(DAG, BB, *TM, true, true,
1899 new BURegReductionFastPriorityQueue());
1901 const TargetInstrInfo *TII = TM->getInstrInfo();
1902 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
1904 BURegReductionPriorityQueue *PQ = new BURegReductionPriorityQueue(TII, TRI);
1906 ScheduleDAGRRList *SD =
1907 new ScheduleDAGRRList(DAG, BB, *TM, true, false, PQ);
1908 PQ->setScheduleDAG(SD);
1912 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1914 const TargetMachine *TM,
1915 MachineBasicBlock *BB,
1917 return new ScheduleDAGRRList(DAG, BB, *TM, false, Fast,
1918 new TDRegReductionPriorityQueue());