1 //===----- ScheduleDAGList.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 /// LiveRegs / 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.
72 SmallSet<unsigned, 4> LiveRegs;
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(SUnit *SU, 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(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";
181 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
182 LiveRegCycles.resize(TRI->getNumRegs(), 0);
184 // Build scheduling units.
187 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
188 SUnits[su].dumpAll(&DAG));
193 InitDAGTopologicalSorting();
195 AvailableQueue->initNodes(SUnits);
197 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
199 ListScheduleBottomUp();
201 ListScheduleTopDown();
203 AvailableQueue->releaseState();
206 CommuteNodesToReducePressure();
209 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
210 /// it is not the last use of its first operand, add it to the CommuteSet if
211 /// possible. It will be commuted when it is translated to a MI.
212 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
213 SmallPtrSet<SUnit*, 4> OperandSeen;
214 for (unsigned i = Sequence.size(); i != 0; ) {
216 SUnit *SU = Sequence[i];
217 if (!SU || !SU->Node) continue;
218 if (SU->isCommutable) {
219 unsigned Opc = SU->Node->getTargetOpcode();
220 const TargetInstrDesc &TID = TII->get(Opc);
221 unsigned NumRes = TID.getNumDefs();
222 unsigned NumOps = TID.getNumOperands() - NumRes;
223 for (unsigned j = 0; j != NumOps; ++j) {
224 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
227 SDNode *OpN = SU->Node->getOperand(j).Val;
228 SUnit *OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
229 if (OpSU && OperandSeen.count(OpSU) == 1) {
230 // Ok, so SU is not the last use of OpSU, but SU is two-address so
231 // it will clobber OpSU. Try to commute SU if no other source operands
233 bool DoCommute = true;
234 for (unsigned k = 0; k < NumOps; ++k) {
236 OpN = SU->Node->getOperand(k).Val;
237 OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
238 if (OpSU && OperandSeen.count(OpSU) == 1) {
245 CommuteSet.insert(SU->Node);
248 // Only look at the first use&def node for now.
253 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
256 OperandSeen.insert(I->Dep->OrigNode);
261 //===----------------------------------------------------------------------===//
262 // Bottom-Up Scheduling
263 //===----------------------------------------------------------------------===//
265 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
266 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
267 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
269 // FIXME: the distance between two nodes is not always == the predecessor's
270 // latency. For example, the reader can very well read the register written
271 // by the predecessor later than the issue cycle. It also depends on the
272 // interrupt model (drain vs. freeze).
273 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
275 --PredSU->NumSuccsLeft;
278 if (PredSU->NumSuccsLeft < 0) {
279 cerr << "*** List scheduling failed! ***\n";
281 cerr << " has been released too many times!\n";
286 if (PredSU->NumSuccsLeft == 0) {
287 PredSU->isAvailable = true;
288 AvailableQueue->push(PredSU);
292 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
293 /// count of its predecessors. If a predecessor pending count is zero, add it to
294 /// the Available queue.
295 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
296 DOUT << "*** Scheduling [" << CurCycle << "]: ";
297 DEBUG(SU->dump(&DAG));
298 SU->Cycle = CurCycle;
300 AvailableQueue->ScheduledNode(SU);
302 // Bottom up: release predecessors
303 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
305 ReleasePred(I->Dep, I->isCtrl, CurCycle);
307 // This is a physical register dependency and it's impossible or
308 // expensive to copy the register. Make sure nothing that can
309 // clobber the register is scheduled between the predecessor and
311 if (LiveRegs.insert(I->Reg)) {
312 LiveRegDefs[I->Reg] = I->Dep;
313 LiveRegCycles[I->Reg] = CurCycle;
318 // Release all the implicit physical register defs that are live.
319 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
322 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
323 LiveRegs.erase(I->Reg);
324 assert(LiveRegDefs[I->Reg] == SU &&
325 "Physical register dependency violated?");
326 LiveRegDefs[I->Reg] = NULL;
327 LiveRegCycles[I->Reg] = 0;
332 SU->isScheduled = true;
335 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
336 /// unscheduled, incrcease the succ left count of its predecessors. Remove
337 /// them from AvailableQueue if necessary.
338 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
339 unsigned CycleBound = 0;
340 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
344 CycleBound = std::max(CycleBound,
345 I->Dep->Cycle + PredSU->Latency);
348 if (PredSU->isAvailable) {
349 PredSU->isAvailable = false;
350 if (!PredSU->isPending)
351 AvailableQueue->remove(PredSU);
354 PredSU->CycleBound = CycleBound;
355 ++PredSU->NumSuccsLeft;
358 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
359 /// its predecessor states to reflect the change.
360 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
361 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
362 DEBUG(SU->dump(&DAG));
364 AvailableQueue->UnscheduledNode(SU);
366 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
368 CapturePred(I->Dep, SU, I->isCtrl);
369 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
370 LiveRegs.erase(I->Reg);
371 assert(LiveRegDefs[I->Reg] == I->Dep &&
372 "Physical register dependency violated?");
373 LiveRegDefs[I->Reg] = NULL;
374 LiveRegCycles[I->Reg] = 0;
378 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
381 if (LiveRegs.insert(I->Reg)) {
382 assert(!LiveRegDefs[I->Reg] &&
383 "Physical register dependency violated?");
384 LiveRegDefs[I->Reg] = SU;
386 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
387 LiveRegCycles[I->Reg] = I->Dep->Cycle;
392 SU->isScheduled = false;
393 SU->isAvailable = true;
394 AvailableQueue->push(SU);
397 /// IsReachable - Checks if SU is reachable from TargetSU.
398 bool ScheduleDAGRRList::IsReachable(SUnit *SU, SUnit *TargetSU) {
399 // If insertion of the edge SU->TargetSU would create a cycle
400 // then there is a path from TargetSU to SU.
401 int UpperBound, LowerBound;
402 LowerBound = Node2Index[TargetSU->NodeNum];
403 UpperBound = Node2Index[SU->NodeNum];
404 bool HasLoop = false;
405 // Is Ord(TargetSU) < Ord(SU) ?
406 if (LowerBound < UpperBound) {
408 // There may be a path from TargetSU to SU. Check for it.
409 DFS(TargetSU, UpperBound, HasLoop);
414 /// Allocate - assign the topological index to the node n.
415 inline void ScheduleDAGRRList::Allocate(int n, int index) {
416 Node2Index[n] = index;
417 Index2Node[index] = n;
420 /// InitDAGTopologicalSorting - create the initial topological
421 /// ordering from the DAG to be scheduled.
423 /// The idea of the algorithm is taken from
424 /// "Online algorithms for managing the topological order of
425 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
426 /// This is the MNR algorithm, which was first introduced by
427 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
428 /// "Maintaining a topological order under edge insertions".
430 /// Short description of the algorithm:
432 /// Topological ordering, ord, of a DAG maps each node to a topological
433 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
435 /// This means that if there is a path from the node X to the node Z,
436 /// then ord(X) < ord(Z).
438 /// This property can be used to check for reachability of nodes:
439 /// if Z is reachable from X, then an insertion of the edge Z->X would
442 /// The algorithm first computes a topological ordering for the DAG by
443 /// initializing the Index2Node and Node2Index arrays and then tries to keep
444 /// the ordering up-to-date after edge insertions by reordering the DAG.
446 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
447 /// the nodes reachable from Y, and then shifts them using Shift to lie
448 /// immediately after X in Index2Node.
449 void ScheduleDAGRRList::InitDAGTopologicalSorting() {
450 unsigned DAGSize = SUnits.size();
451 std::vector<unsigned> InDegree(DAGSize);
452 std::vector<SUnit*> WorkList;
453 WorkList.reserve(DAGSize);
454 std::vector<SUnit*> TopOrder;
455 TopOrder.reserve(DAGSize);
457 // Initialize the data structures.
458 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
459 SUnit *SU = &SUnits[i];
460 int NodeNum = SU->NodeNum;
461 unsigned Degree = SU->Succs.size();
462 InDegree[NodeNum] = Degree;
464 // Is it a node without dependencies?
466 assert(SU->Succs.empty() && "SUnit should have no successors");
467 // Collect leaf nodes.
468 WorkList.push_back(SU);
472 while (!WorkList.empty()) {
473 SUnit *SU = WorkList.back();
475 TopOrder.push_back(SU);
476 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
479 if (!--InDegree[SU->NodeNum])
480 // If all dependencies of the node are processed already,
481 // then the node can be computed now.
482 WorkList.push_back(SU);
486 // Second pass, assign the actual topological order as node ids.
491 Index2Node.resize(DAGSize);
492 Node2Index.resize(DAGSize);
493 Visited.resize(DAGSize);
495 for (std::vector<SUnit*>::reverse_iterator TI = TopOrder.rbegin(),
496 TE = TopOrder.rend();TI != TE; ++TI) {
497 Allocate((*TI)->NodeNum, Id);
502 // Check correctness of the ordering
503 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
504 SUnit *SU = &SUnits[i];
505 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
507 assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] &&
508 "Wrong topological sorting");
514 /// AddPred - adds an edge from SUnit X to SUnit Y.
515 /// Updates the topological ordering if required.
516 bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
517 unsigned PhyReg, int Cost) {
518 int UpperBound, LowerBound;
519 LowerBound = Node2Index[Y->NodeNum];
520 UpperBound = Node2Index[X->NodeNum];
521 bool HasLoop = false;
522 // Is Ord(X) < Ord(Y) ?
523 if (LowerBound < UpperBound) {
524 // Update the topological order.
526 DFS(Y, UpperBound, HasLoop);
527 assert(!HasLoop && "Inserted edge creates a loop!");
528 // Recompute topological indexes.
529 Shift(Visited, LowerBound, UpperBound);
531 // Now really insert the edge.
532 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
535 /// RemovePred - This removes the specified node N from the predecessors of
536 /// the current node M. Updates the topological ordering if required.
537 bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N,
538 bool isCtrl, bool isSpecial) {
539 // InitDAGTopologicalSorting();
540 return M->removePred(N, isCtrl, isSpecial);
543 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
544 /// all nodes affected by the edge insertion. These nodes will later get new
545 /// topological indexes by means of the Shift method.
546 void ScheduleDAGRRList::DFS(SUnit *SU, int UpperBound, bool& HasLoop) {
547 std::vector<SUnit*> WorkList;
548 WorkList.reserve(SUnits.size());
550 WorkList.push_back(SU);
551 while (!WorkList.empty()) {
552 SU = WorkList.back();
554 Visited.set(SU->NodeNum);
555 for (int I = SU->Succs.size()-1; I >= 0; --I) {
556 int s = SU->Succs[I].Dep->NodeNum;
557 if (Node2Index[s] == UpperBound) {
561 // Visit successors if not already and in affected region.
562 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
563 WorkList.push_back(SU->Succs[I].Dep);
569 /// Shift - Renumber the nodes so that the topological ordering is
571 void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound,
577 for (i = LowerBound; i <= UpperBound; ++i) {
578 // w is node at topological index i.
579 int w = Index2Node[i];
580 if (Visited.test(w)) {
586 Allocate(w, i - shift);
590 for (unsigned j = 0; j < L.size(); ++j) {
591 Allocate(L[j], i - shift);
597 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
599 bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
600 if (IsReachable(TargetSU, SU))
602 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
604 if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
609 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
610 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
611 /// SUnit. Also returns if a successor is unscheduled in the process.
612 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
613 unsigned &CurCycle) {
615 while (CurCycle > BtCycle) {
616 OldSU = Sequence.back();
618 if (SU->isSucc(OldSU))
619 // Don't try to remove SU from AvailableQueue.
620 SU->isAvailable = false;
621 UnscheduleNodeBottomUp(OldSU);
626 if (SU->isSucc(OldSU)) {
627 assert(false && "Something is wrong!");
634 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
635 /// successors to the newly created node.
636 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
637 if (SU->FlaggedNodes.size())
640 SDNode *N = SU->Node;
645 bool TryUnfold = false;
646 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
647 MVT VT = N->getValueType(i);
650 else if (VT == MVT::Other)
653 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
654 const SDOperand &Op = N->getOperand(i);
655 MVT VT = Op.Val->getValueType(Op.ResNo);
661 SmallVector<SDNode*, 2> NewNodes;
662 if (!TII->unfoldMemoryOperand(DAG, N, NewNodes))
665 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
666 assert(NewNodes.size() == 2 && "Expected a load folding node!");
669 SDNode *LoadNode = NewNodes[0];
670 unsigned NumVals = N->getNumValues();
671 unsigned OldNumVals = SU->Node->getNumValues();
672 for (unsigned i = 0; i != NumVals; ++i)
673 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i), SDOperand(N, i));
674 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
675 SDOperand(LoadNode, 1));
677 SUnit *NewSU = CreateNewSUnit(N);
678 assert(N->getNodeId() == -1 && "Node already inserted!");
679 N->setNodeId(NewSU->NodeNum);
681 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
682 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
683 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
684 NewSU->isTwoAddress = true;
688 if (TID.isCommutable())
689 NewSU->isCommutable = true;
690 // FIXME: Calculate height / depth and propagate the changes?
691 NewSU->Depth = SU->Depth;
692 NewSU->Height = SU->Height;
693 ComputeLatency(NewSU);
695 // LoadNode may already exist. This can happen when there is another
696 // load from the same location and producing the same type of value
697 // but it has different alignment or volatileness.
698 bool isNewLoad = true;
700 if (LoadNode->getNodeId() != -1) {
701 LoadSU = &SUnits[LoadNode->getNodeId()];
704 LoadSU = CreateNewSUnit(LoadNode);
705 LoadNode->setNodeId(LoadSU->NodeNum);
707 LoadSU->Depth = SU->Depth;
708 LoadSU->Height = SU->Height;
709 ComputeLatency(LoadSU);
712 SUnit *ChainPred = NULL;
713 SmallVector<SDep, 4> ChainSuccs;
714 SmallVector<SDep, 4> LoadPreds;
715 SmallVector<SDep, 4> NodePreds;
716 SmallVector<SDep, 4> NodeSuccs;
717 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
721 else if (I->Dep->Node && I->Dep->Node->isOperandOf(LoadNode))
722 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
724 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
726 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
729 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
730 I->isCtrl, I->isSpecial));
732 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
733 I->isCtrl, I->isSpecial));
737 RemovePred(SU, ChainPred, true, false);
739 AddPred(LoadSU, ChainPred, true, false);
741 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
742 SDep *Pred = &LoadPreds[i];
743 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
745 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
746 Pred->Reg, Pred->Cost);
749 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
750 SDep *Pred = &NodePreds[i];
751 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
752 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
753 Pred->Reg, Pred->Cost);
755 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
756 SDep *Succ = &NodeSuccs[i];
757 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
758 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
759 Succ->Reg, Succ->Cost);
761 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
762 SDep *Succ = &ChainSuccs[i];
763 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
765 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
766 Succ->Reg, Succ->Cost);
770 AddPred(NewSU, LoadSU, false, false);
774 AvailableQueue->addNode(LoadSU);
775 AvailableQueue->addNode(NewSU);
779 if (NewSU->NumSuccsLeft == 0) {
780 NewSU->isAvailable = true;
786 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
787 NewSU = CreateClone(SU);
789 // New SUnit has the exact same predecessors.
790 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
793 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
794 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
797 // Only copy scheduled successors. Cut them from old node's successor
798 // list and move them over.
799 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
800 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
804 if (I->Dep->isScheduled) {
805 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
806 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
807 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
810 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
811 SUnit *Succ = DelDeps[i].first;
812 bool isCtrl = DelDeps[i].second;
813 RemovePred(Succ, SU, isCtrl, false);
816 AvailableQueue->updateNode(SU);
817 AvailableQueue->addNode(NewSU);
823 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
824 /// and move all scheduled successors of the given SUnit to the last copy.
825 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
826 const TargetRegisterClass *DestRC,
827 const TargetRegisterClass *SrcRC,
828 SmallVector<SUnit*, 2> &Copies) {
829 SUnit *CopyFromSU = CreateNewSUnit(NULL);
830 CopyFromSU->CopySrcRC = SrcRC;
831 CopyFromSU->CopyDstRC = DestRC;
832 CopyFromSU->Depth = SU->Depth;
833 CopyFromSU->Height = SU->Height;
835 SUnit *CopyToSU = CreateNewSUnit(NULL);
836 CopyToSU->CopySrcRC = DestRC;
837 CopyToSU->CopyDstRC = SrcRC;
839 // Only copy scheduled successors. Cut them from old node's successor
840 // list and move them over.
841 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
842 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
846 if (I->Dep->isScheduled) {
847 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
848 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
849 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
852 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
853 SUnit *Succ = DelDeps[i].first;
854 bool isCtrl = DelDeps[i].second;
855 RemovePred(Succ, SU, isCtrl, false);
858 AddPred(CopyFromSU, SU, false, false, Reg, -1);
859 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
861 AvailableQueue->updateNode(SU);
862 AvailableQueue->addNode(CopyFromSU);
863 AvailableQueue->addNode(CopyToSU);
864 Copies.push_back(CopyFromSU);
865 Copies.push_back(CopyToSU);
870 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
871 /// definition of the specified node.
872 /// FIXME: Move to SelectionDAG?
873 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
874 const TargetInstrInfo *TII) {
875 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
876 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
877 unsigned NumRes = TID.getNumDefs();
878 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
883 return N->getValueType(NumRes);
886 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
887 /// scheduling of the given node to satisfy live physical register dependencies.
888 /// If the specific node is the last one that's available to schedule, do
889 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
890 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
891 SmallVector<unsigned, 4> &LRegs){
892 if (LiveRegs.empty())
895 SmallSet<unsigned, 4> RegAdded;
896 // If this node would clobber any "live" register, then it's not ready.
897 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
900 unsigned Reg = I->Reg;
901 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
902 if (RegAdded.insert(Reg))
903 LRegs.push_back(Reg);
905 for (const unsigned *Alias = TRI->getAliasSet(Reg);
907 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
908 if (RegAdded.insert(*Alias))
909 LRegs.push_back(*Alias);
914 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
915 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
916 if (!Node || !Node->isTargetOpcode())
918 const TargetInstrDesc &TID = TII->get(Node->getTargetOpcode());
919 if (!TID.ImplicitDefs)
921 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
922 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
923 if (RegAdded.insert(*Reg))
924 LRegs.push_back(*Reg);
926 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
928 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
929 if (RegAdded.insert(*Alias))
930 LRegs.push_back(*Alias);
934 return !LRegs.empty();
938 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
940 void ScheduleDAGRRList::ListScheduleBottomUp() {
941 unsigned CurCycle = 0;
942 // Add root to Available queue.
943 if (!SUnits.empty()) {
944 SUnit *RootSU = &SUnits[DAG.getRoot().Val->getNodeId()];
945 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
946 RootSU->isAvailable = true;
947 AvailableQueue->push(RootSU);
950 // While Available queue is not empty, grab the node with the highest
951 // priority. If it is not ready put it back. Schedule the node.
952 SmallVector<SUnit*, 4> NotReady;
953 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
954 Sequence.reserve(SUnits.size());
955 while (!AvailableQueue->empty()) {
956 bool Delayed = false;
958 SUnit *CurSU = AvailableQueue->pop();
960 if (CurSU->CycleBound <= CurCycle) {
961 SmallVector<unsigned, 4> LRegs;
962 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
965 LRegsMap.insert(std::make_pair(CurSU, LRegs));
968 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
969 NotReady.push_back(CurSU);
970 CurSU = AvailableQueue->pop();
973 // All candidates are delayed due to live physical reg dependencies.
974 // Try backtracking, code duplication, or inserting cross class copies
976 if (Delayed && !CurSU) {
977 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
978 SUnit *TrySU = NotReady[i];
979 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
981 // Try unscheduling up to the point where it's safe to schedule
983 unsigned LiveCycle = CurCycle;
984 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
985 unsigned Reg = LRegs[j];
986 unsigned LCycle = LiveRegCycles[Reg];
987 LiveCycle = std::min(LiveCycle, LCycle);
989 SUnit *OldSU = Sequence[LiveCycle];
990 if (!WillCreateCycle(TrySU, OldSU)) {
991 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
992 // Force the current node to be scheduled before the node that
993 // requires the physical reg dep.
994 if (OldSU->isAvailable) {
995 OldSU->isAvailable = false;
996 AvailableQueue->remove(OldSU);
998 AddPred(TrySU, OldSU, true, true);
999 // If one or more successors has been unscheduled, then the current
1000 // node is no longer avaialable. Schedule a successor that's now
1001 // available instead.
1002 if (!TrySU->isAvailable)
1003 CurSU = AvailableQueue->pop();
1006 TrySU->isPending = false;
1007 NotReady.erase(NotReady.begin()+i);
1014 // Can't backtrack. Try duplicating the nodes that produces these
1015 // "expensive to copy" values to break the dependency. In case even
1016 // that doesn't work, insert cross class copies.
1017 SUnit *TrySU = NotReady[0];
1018 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1019 assert(LRegs.size() == 1 && "Can't handle this yet!");
1020 unsigned Reg = LRegs[0];
1021 SUnit *LRDef = LiveRegDefs[Reg];
1022 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1024 // Issue expensive cross register class copies.
1025 MVT VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
1026 const TargetRegisterClass *RC =
1027 TRI->getPhysicalRegisterRegClass(Reg, VT);
1028 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1030 assert(false && "Don't know how to copy this physical register!");
1033 SmallVector<SUnit*, 2> Copies;
1034 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1035 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1036 << " to SU #" << Copies.front()->NodeNum << "\n";
1037 AddPred(TrySU, Copies.front(), true, true);
1038 NewDef = Copies.back();
1041 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1042 << " to SU #" << TrySU->NodeNum << "\n";
1043 LiveRegDefs[Reg] = NewDef;
1044 AddPred(NewDef, TrySU, true, true);
1045 TrySU->isAvailable = false;
1050 assert(false && "Unable to resolve live physical register dependencies!");
1055 // Add the nodes that aren't ready back onto the available list.
1056 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1057 NotReady[i]->isPending = false;
1058 // May no longer be available due to backtracking.
1059 if (NotReady[i]->isAvailable)
1060 AvailableQueue->push(NotReady[i]);
1065 Sequence.push_back(0);
1067 ScheduleNodeBottomUp(CurSU, CurCycle);
1068 Sequence.push_back(CurSU);
1073 // Reverse the order if it is bottom up.
1074 std::reverse(Sequence.begin(), Sequence.end());
1078 // Verify that all SUnits were scheduled.
1079 bool AnyNotSched = false;
1080 unsigned DeadNodes = 0;
1082 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1083 if (!SUnits[i].isScheduled) {
1084 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1089 cerr << "*** List scheduling failed! ***\n";
1090 SUnits[i].dump(&DAG);
1091 cerr << "has not been scheduled!\n";
1094 if (SUnits[i].NumSuccsLeft != 0) {
1096 cerr << "*** List scheduling failed! ***\n";
1097 SUnits[i].dump(&DAG);
1098 cerr << "has successors left!\n";
1102 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1105 assert(!AnyNotSched);
1106 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1107 "The number of nodes scheduled doesn't match the expected number!");
1111 //===----------------------------------------------------------------------===//
1112 // Top-Down Scheduling
1113 //===----------------------------------------------------------------------===//
1115 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1116 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1117 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
1118 unsigned CurCycle) {
1119 // FIXME: the distance between two nodes is not always == the predecessor's
1120 // latency. For example, the reader can very well read the register written
1121 // by the predecessor later than the issue cycle. It also depends on the
1122 // interrupt model (drain vs. freeze).
1123 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
1125 --SuccSU->NumPredsLeft;
1128 if (SuccSU->NumPredsLeft < 0) {
1129 cerr << "*** List scheduling failed! ***\n";
1131 cerr << " has been released too many times!\n";
1136 if (SuccSU->NumPredsLeft == 0) {
1137 SuccSU->isAvailable = true;
1138 AvailableQueue->push(SuccSU);
1143 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1144 /// count of its successors. If a successor pending count is zero, add it to
1145 /// the Available queue.
1146 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1147 DOUT << "*** Scheduling [" << CurCycle << "]: ";
1148 DEBUG(SU->dump(&DAG));
1149 SU->Cycle = CurCycle;
1151 AvailableQueue->ScheduledNode(SU);
1153 // Top down: release successors
1154 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1156 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
1157 SU->isScheduled = true;
1160 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1162 void ScheduleDAGRRList::ListScheduleTopDown() {
1163 unsigned CurCycle = 0;
1165 // All leaves to Available queue.
1166 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1167 // It is available if it has no predecessors.
1168 if (SUnits[i].Preds.empty()) {
1169 AvailableQueue->push(&SUnits[i]);
1170 SUnits[i].isAvailable = true;
1174 // While Available queue is not empty, grab the node with the highest
1175 // priority. If it is not ready put it back. Schedule the node.
1176 std::vector<SUnit*> NotReady;
1177 Sequence.reserve(SUnits.size());
1178 while (!AvailableQueue->empty()) {
1179 SUnit *CurSU = AvailableQueue->pop();
1180 while (CurSU && CurSU->CycleBound > CurCycle) {
1181 NotReady.push_back(CurSU);
1182 CurSU = AvailableQueue->pop();
1185 // Add the nodes that aren't ready back onto the available list.
1186 AvailableQueue->push_all(NotReady);
1190 Sequence.push_back(0);
1192 ScheduleNodeTopDown(CurSU, CurCycle);
1193 Sequence.push_back(CurSU);
1200 // Verify that all SUnits were scheduled.
1201 bool AnyNotSched = false;
1202 unsigned DeadNodes = 0;
1204 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1205 if (!SUnits[i].isScheduled) {
1206 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1211 cerr << "*** List scheduling failed! ***\n";
1212 SUnits[i].dump(&DAG);
1213 cerr << "has not been scheduled!\n";
1216 if (SUnits[i].NumPredsLeft != 0) {
1218 cerr << "*** List scheduling failed! ***\n";
1219 SUnits[i].dump(&DAG);
1220 cerr << "has predecessors left!\n";
1224 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1227 assert(!AnyNotSched);
1228 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1229 "The number of nodes scheduled doesn't match the expected number!");
1235 //===----------------------------------------------------------------------===//
1236 // RegReductionPriorityQueue Implementation
1237 //===----------------------------------------------------------------------===//
1239 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1240 // to reduce register pressure.
1244 class RegReductionPriorityQueue;
1246 /// Sorting functions for the Available queue.
1247 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1248 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1249 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1250 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1252 bool operator()(const SUnit* left, const SUnit* right) const;
1255 struct bu_ls_rr_fast_sort : public std::binary_function<SUnit*, SUnit*, bool>{
1256 RegReductionPriorityQueue<bu_ls_rr_fast_sort> *SPQ;
1257 bu_ls_rr_fast_sort(RegReductionPriorityQueue<bu_ls_rr_fast_sort> *spq)
1259 bu_ls_rr_fast_sort(const bu_ls_rr_fast_sort &RHS) : SPQ(RHS.SPQ) {}
1261 bool operator()(const SUnit* left, const SUnit* right) const;
1264 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1265 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1266 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1267 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1269 bool operator()(const SUnit* left, const SUnit* right) const;
1271 } // end anonymous namespace
1273 static inline bool isCopyFromLiveIn(const SUnit *SU) {
1274 SDNode *N = SU->Node;
1275 return N && N->getOpcode() == ISD::CopyFromReg &&
1276 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1279 /// CalcNodeBUSethiUllmanNumber - Compute Sethi Ullman number for bottom up
1280 /// scheduling. Smaller number is the higher priority.
1282 CalcNodeBUSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1283 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1284 if (SethiUllmanNumber != 0)
1285 return SethiUllmanNumber;
1288 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1290 if (I->isCtrl) continue; // ignore chain preds
1291 SUnit *PredSU = I->Dep;
1292 unsigned PredSethiUllman = CalcNodeBUSethiUllmanNumber(PredSU, SUNumbers);
1293 if (PredSethiUllman > SethiUllmanNumber) {
1294 SethiUllmanNumber = PredSethiUllman;
1296 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1300 SethiUllmanNumber += Extra;
1302 if (SethiUllmanNumber == 0)
1303 SethiUllmanNumber = 1;
1305 return SethiUllmanNumber;
1308 /// CalcNodeTDSethiUllmanNumber - Compute Sethi Ullman number for top down
1309 /// scheduling. Smaller number is the higher priority.
1311 CalcNodeTDSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1312 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1313 if (SethiUllmanNumber != 0)
1314 return SethiUllmanNumber;
1316 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1317 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1318 SethiUllmanNumber = 0xffff;
1319 else if (SU->NumSuccsLeft == 0)
1320 // If SU does not have a use, i.e. it doesn't produce a value that would
1321 // be consumed (e.g. store), then it terminates a chain of computation.
1322 // Give it a small SethiUllman number so it will be scheduled right before
1323 // its predecessors that it doesn't lengthen their live ranges.
1324 SethiUllmanNumber = 0;
1325 else if (SU->NumPredsLeft == 0 &&
1326 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1327 SethiUllmanNumber = 0xffff;
1330 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1332 if (I->isCtrl) continue; // ignore chain preds
1333 SUnit *PredSU = I->Dep;
1334 unsigned PredSethiUllman = CalcNodeTDSethiUllmanNumber(PredSU, SUNumbers);
1335 if (PredSethiUllman > SethiUllmanNumber) {
1336 SethiUllmanNumber = PredSethiUllman;
1338 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1342 SethiUllmanNumber += Extra;
1345 return SethiUllmanNumber;
1351 class VISIBILITY_HIDDEN RegReductionPriorityQueue
1352 : public SchedulingPriorityQueue {
1353 PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
1354 unsigned currentQueueId;
1357 RegReductionPriorityQueue() :
1358 Queue(SF(this)), currentQueueId(0) {}
1360 virtual void initNodes(std::vector<SUnit> &sunits) {}
1362 virtual void addNode(const SUnit *SU) {}
1364 virtual void updateNode(const SUnit *SU) {}
1366 virtual void releaseState() {}
1368 virtual unsigned getNodePriority(const SUnit *SU) const {
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 const 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->Node ? SU->Node->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->Node && I->Dep->Node->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->Node || I->Dep->Node->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->Node || I->Dep->Node->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->Node->getTargetOpcode();
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->Node->getOperand(i).Val;
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(SUnit *SU) {
1696 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1698 if (I->isCtrl) continue;
1699 SUnit *SuccSU = I->Dep;
1700 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1706 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1707 /// physical register defs.
1708 static bool canClobberPhysRegDefs(SUnit *SuccSU, SUnit *SU,
1709 const TargetInstrInfo *TII,
1710 const TargetRegisterInfo *TRI) {
1711 SDNode *N = SuccSU->Node;
1712 unsigned NumDefs = TII->get(N->getTargetOpcode()).getNumDefs();
1713 const unsigned *ImpDefs = TII->get(N->getTargetOpcode()).getImplicitDefs();
1714 assert(ImpDefs && "Caller should check hasPhysRegDefs");
1715 const unsigned *SUImpDefs =
1716 TII->get(SU->Node->getTargetOpcode()).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 unsigned Reg = ImpDefs[i - NumDefs];
1724 for (;*SUImpDefs; ++SUImpDefs) {
1725 unsigned SUReg = *SUImpDefs;
1726 if (TRI->regsOverlap(Reg, SUReg))
1733 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1734 /// it as a def&use operand. Add a pseudo control edge from it to the other
1735 /// node (if it won't create a cycle) so the two-address one will be scheduled
1736 /// first (lower in the schedule). If both nodes are two-address, favor the
1737 /// one that has a CopyToReg use (more likely to be a loop induction update).
1738 /// If both are two-address, but one is commutable while the other is not
1739 /// commutable, favor the one that's not commutable.
1740 void BURegReductionPriorityQueue::AddPseudoTwoAddrDeps() {
1741 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1742 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1743 if (!SU->isTwoAddress)
1746 SDNode *Node = SU->Node;
1747 if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
1750 unsigned Opc = Node->getTargetOpcode();
1751 const TargetInstrDesc &TID = TII->get(Opc);
1752 unsigned NumRes = TID.getNumDefs();
1753 unsigned NumOps = TID.getNumOperands() - NumRes;
1754 for (unsigned j = 0; j != NumOps; ++j) {
1755 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) != -1) {
1756 SDNode *DU = SU->Node->getOperand(j).Val;
1757 if (DU->getNodeId() == -1)
1759 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1760 if (!DUSU) continue;
1761 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1762 E = DUSU->Succs.end(); I != E; ++I) {
1763 if (I->isCtrl) continue;
1764 SUnit *SuccSU = I->Dep;
1767 // Be conservative. Ignore if nodes aren't at roughly the same
1768 // depth and height.
1769 if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1771 if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1773 // Don't constrain nodes with physical register defs if the
1774 // predecessor can clobber them.
1775 if (SuccSU->hasPhysRegDefs) {
1776 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1779 // Don't constraint extract_subreg / insert_subreg these may be
1780 // coalesced away. We don't them close to their uses.
1781 unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1782 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1783 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1785 if ((!canClobber(SuccSU, DUSU) ||
1786 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1787 (!SU->isCommutable && SuccSU->isCommutable)) &&
1788 !scheduleDAG->IsReachable(SuccSU, SU)) {
1789 DOUT << "Adding an edge from SU # " << SU->NodeNum
1790 << " to SU #" << SuccSU->NodeNum << "\n";
1791 scheduleDAG->AddPred(SU, SuccSU, true, true);
1799 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1800 /// scheduling units.
1801 void BURegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1802 SethiUllmanNumbers.assign(SUnits->size(), 0);
1804 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1805 CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1807 void BURegReductionFastPriorityQueue::CalculateSethiUllmanNumbers() {
1808 SethiUllmanNumbers.assign(SUnits->size(), 0);
1810 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1811 CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1814 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1815 /// predecessors of the successors of the SUnit SU. Stop when the provided
1816 /// limit is exceeded.
1817 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
1820 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1822 SUnit *SuccSU = I->Dep;
1823 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1824 EE = SuccSU->Preds.end(); II != EE; ++II) {
1825 SUnit *PredSU = II->Dep;
1826 if (!PredSU->isScheduled)
1836 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1837 unsigned LPriority = SPQ->getNodePriority(left);
1838 unsigned RPriority = SPQ->getNodePriority(right);
1839 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1840 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
1841 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1842 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1843 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1844 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1846 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1848 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1855 if (left->NumSuccs == 1)
1857 if (right->NumSuccs == 1)
1860 if (LPriority+LBonus != RPriority+RBonus)
1861 return LPriority+LBonus < RPriority+RBonus;
1863 if (left->Depth != right->Depth)
1864 return left->Depth < right->Depth;
1866 if (left->NumSuccsLeft != right->NumSuccsLeft)
1867 return left->NumSuccsLeft > right->NumSuccsLeft;
1869 if (left->CycleBound != right->CycleBound)
1870 return left->CycleBound > right->CycleBound;
1872 assert(left->NodeQueueId && right->NodeQueueId &&
1873 "NodeQueueId cannot be zero");
1874 return (left->NodeQueueId > right->NodeQueueId);
1877 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1878 /// scheduling units.
1879 void TDRegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1880 SethiUllmanNumbers.assign(SUnits->size(), 0);
1882 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1883 CalcNodeTDSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1886 //===----------------------------------------------------------------------===//
1887 // Public Constructor Functions
1888 //===----------------------------------------------------------------------===//
1890 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1892 MachineBasicBlock *BB,
1895 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true, true,
1896 new BURegReductionFastPriorityQueue());
1898 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
1899 const TargetRegisterInfo *TRI = DAG->getTarget().getRegisterInfo();
1901 BURegReductionPriorityQueue *PQ = new BURegReductionPriorityQueue(TII, TRI);
1903 ScheduleDAGRRList *SD =
1904 new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(),true,false, PQ);
1905 PQ->setScheduleDAG(SD);
1909 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1911 MachineBasicBlock *BB,
1913 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false, Fast,
1914 new TDRegReductionPriorityQueue());