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();
208 DOUT << "*** Final schedule ***\n";
209 DEBUG(dumpSchedule());
212 // Emit in scheduled order
216 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
217 /// it is not the last use of its first operand, add it to the CommuteSet if
218 /// possible. It will be commuted when it is translated to a MI.
219 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
220 SmallPtrSet<SUnit*, 4> OperandSeen;
221 for (unsigned i = Sequence.size(); i != 0; ) {
223 SUnit *SU = Sequence[i];
224 if (!SU || !SU->Node) continue;
225 if (SU->isCommutable) {
226 unsigned Opc = SU->Node->getTargetOpcode();
227 const TargetInstrDesc &TID = TII->get(Opc);
228 unsigned NumRes = TID.getNumDefs();
229 unsigned NumOps = TID.getNumOperands() - NumRes;
230 for (unsigned j = 0; j != NumOps; ++j) {
231 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
234 SDNode *OpN = SU->Node->getOperand(j).Val;
235 SUnit *OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
236 if (OpSU && OperandSeen.count(OpSU) == 1) {
237 // Ok, so SU is not the last use of OpSU, but SU is two-address so
238 // it will clobber OpSU. Try to commute SU if no other source operands
240 bool DoCommute = true;
241 for (unsigned k = 0; k < NumOps; ++k) {
243 OpN = SU->Node->getOperand(k).Val;
244 OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
245 if (OpSU && OperandSeen.count(OpSU) == 1) {
252 CommuteSet.insert(SU->Node);
255 // Only look at the first use&def node for now.
260 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
263 OperandSeen.insert(I->Dep->OrigNode);
268 //===----------------------------------------------------------------------===//
269 // Bottom-Up Scheduling
270 //===----------------------------------------------------------------------===//
272 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
273 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
274 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
276 // FIXME: the distance between two nodes is not always == the predecessor's
277 // latency. For example, the reader can very well read the register written
278 // by the predecessor later than the issue cycle. It also depends on the
279 // interrupt model (drain vs. freeze).
280 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
282 --PredSU->NumSuccsLeft;
285 if (PredSU->NumSuccsLeft < 0) {
286 cerr << "*** List scheduling failed! ***\n";
288 cerr << " has been released too many times!\n";
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(&DAG));
305 SU->Cycle = CurCycle;
307 AvailableQueue->ScheduledNode(SU);
309 // Bottom up: release predecessors
310 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
312 ReleasePred(I->Dep, I->isCtrl, CurCycle);
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 (LiveRegs.insert(I->Reg)) {
319 LiveRegDefs[I->Reg] = I->Dep;
320 LiveRegCycles[I->Reg] = CurCycle;
325 // Release all the implicit physical register defs that are live.
326 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
329 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
330 LiveRegs.erase(I->Reg);
331 assert(LiveRegDefs[I->Reg] == SU &&
332 "Physical register dependency violated?");
333 LiveRegDefs[I->Reg] = NULL;
334 LiveRegCycles[I->Reg] = 0;
339 SU->isScheduled = true;
342 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
343 /// unscheduled, incrcease the succ left count of its predecessors. Remove
344 /// them from AvailableQueue if necessary.
345 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
346 unsigned CycleBound = 0;
347 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
351 CycleBound = std::max(CycleBound,
352 I->Dep->Cycle + PredSU->Latency);
355 if (PredSU->isAvailable) {
356 PredSU->isAvailable = false;
357 if (!PredSU->isPending)
358 AvailableQueue->remove(PredSU);
361 PredSU->CycleBound = CycleBound;
362 ++PredSU->NumSuccsLeft;
365 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
366 /// its predecessor states to reflect the change.
367 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
368 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
369 DEBUG(SU->dump(&DAG));
371 AvailableQueue->UnscheduledNode(SU);
373 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
375 CapturePred(I->Dep, SU, I->isCtrl);
376 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
377 LiveRegs.erase(I->Reg);
378 assert(LiveRegDefs[I->Reg] == I->Dep &&
379 "Physical register dependency violated?");
380 LiveRegDefs[I->Reg] = NULL;
381 LiveRegCycles[I->Reg] = 0;
385 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
388 if (LiveRegs.insert(I->Reg)) {
389 assert(!LiveRegDefs[I->Reg] &&
390 "Physical register dependency violated?");
391 LiveRegDefs[I->Reg] = SU;
393 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
394 LiveRegCycles[I->Reg] = I->Dep->Cycle;
399 SU->isScheduled = false;
400 SU->isAvailable = true;
401 AvailableQueue->push(SU);
404 /// IsReachable - Checks if SU is reachable from TargetSU.
405 bool ScheduleDAGRRList::IsReachable(SUnit *SU, SUnit *TargetSU) {
406 // If insertion of the edge SU->TargetSU would create a cycle
407 // then there is a path from TargetSU to SU.
408 int UpperBound, LowerBound;
409 LowerBound = Node2Index[TargetSU->NodeNum];
410 UpperBound = Node2Index[SU->NodeNum];
411 bool HasLoop = false;
412 // Is Ord(TargetSU) < Ord(SU) ?
413 if (LowerBound < UpperBound) {
415 // There may be a path from TargetSU to SU. Check for it.
416 DFS(TargetSU, UpperBound, HasLoop);
421 /// Allocate - assign the topological index to the node n.
422 inline void ScheduleDAGRRList::Allocate(int n, int index) {
423 Node2Index[n] = index;
424 Index2Node[index] = n;
427 /// InitDAGTopologicalSorting - create the initial topological
428 /// ordering from the DAG to be scheduled.
430 /// The idea of the algorithm is taken from
431 /// "Online algorithms for managing the topological order of
432 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
433 /// This is the MNR algorithm, which was first introduced by
434 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
435 /// "Maintaining a topological order under edge insertions".
437 /// Short description of the algorithm:
439 /// Topological ordering, ord, of a DAG maps each node to a topological
440 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
442 /// This means that if there is a path from the node X to the node Z,
443 /// then ord(X) < ord(Z).
445 /// This property can be used to check for reachability of nodes:
446 /// if Z is reachable from X, then an insertion of the edge Z->X would
449 /// The algorithm first computes a topological ordering for the DAG by
450 /// initializing the Index2Node and Node2Index arrays and then tries to keep
451 /// the ordering up-to-date after edge insertions by reordering the DAG.
453 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
454 /// the nodes reachable from Y, and then shifts them using Shift to lie
455 /// immediately after X in Index2Node.
456 void ScheduleDAGRRList::InitDAGTopologicalSorting() {
457 unsigned DAGSize = SUnits.size();
458 std::vector<unsigned> InDegree(DAGSize);
459 std::vector<SUnit*> WorkList;
460 WorkList.reserve(DAGSize);
461 std::vector<SUnit*> TopOrder;
462 TopOrder.reserve(DAGSize);
464 // Initialize the data structures.
465 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
466 SUnit *SU = &SUnits[i];
467 int NodeNum = SU->NodeNum;
468 unsigned Degree = SU->Succs.size();
469 InDegree[NodeNum] = Degree;
471 // Is it a node without dependencies?
473 assert(SU->Succs.empty() && "SUnit should have no successors");
474 // Collect leaf nodes.
475 WorkList.push_back(SU);
479 while (!WorkList.empty()) {
480 SUnit *SU = WorkList.back();
482 TopOrder.push_back(SU);
483 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
486 if (!--InDegree[SU->NodeNum])
487 // If all dependencies of the node are processed already,
488 // then the node can be computed now.
489 WorkList.push_back(SU);
493 // Second pass, assign the actual topological order as node ids.
498 Index2Node.resize(DAGSize);
499 Node2Index.resize(DAGSize);
500 Visited.resize(DAGSize);
502 for (std::vector<SUnit*>::reverse_iterator TI = TopOrder.rbegin(),
503 TE = TopOrder.rend();TI != TE; ++TI) {
504 Allocate((*TI)->NodeNum, Id);
509 // Check correctness of the ordering
510 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
511 SUnit *SU = &SUnits[i];
512 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
514 assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] &&
515 "Wrong topological sorting");
521 /// AddPred - adds an edge from SUnit X to SUnit Y.
522 /// Updates the topological ordering if required.
523 bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
524 unsigned PhyReg, int Cost) {
525 int UpperBound, LowerBound;
526 LowerBound = Node2Index[Y->NodeNum];
527 UpperBound = Node2Index[X->NodeNum];
528 bool HasLoop = false;
529 // Is Ord(X) < Ord(Y) ?
530 if (LowerBound < UpperBound) {
531 // Update the topological order.
533 DFS(Y, UpperBound, HasLoop);
534 assert(!HasLoop && "Inserted edge creates a loop!");
535 // Recompute topological indexes.
536 Shift(Visited, LowerBound, UpperBound);
538 // Now really insert the edge.
539 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
542 /// RemovePred - This removes the specified node N from the predecessors of
543 /// the current node M. Updates the topological ordering if required.
544 bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N,
545 bool isCtrl, bool isSpecial) {
546 // InitDAGTopologicalSorting();
547 return M->removePred(N, isCtrl, isSpecial);
550 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
551 /// all nodes affected by the edge insertion. These nodes will later get new
552 /// topological indexes by means of the Shift method.
553 void ScheduleDAGRRList::DFS(SUnit *SU, int UpperBound, bool& HasLoop) {
554 std::vector<SUnit*> WorkList;
555 WorkList.reserve(SUnits.size());
557 WorkList.push_back(SU);
558 while (!WorkList.empty()) {
559 SU = WorkList.back();
561 Visited.set(SU->NodeNum);
562 for (int I = SU->Succs.size()-1; I >= 0; --I) {
563 int s = SU->Succs[I].Dep->NodeNum;
564 if (Node2Index[s] == UpperBound) {
568 // Visit successors if not already and in affected region.
569 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
570 WorkList.push_back(SU->Succs[I].Dep);
576 /// Shift - Renumber the nodes so that the topological ordering is
578 void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound,
584 for (i = LowerBound; i <= UpperBound; ++i) {
585 // w is node at topological index i.
586 int w = Index2Node[i];
587 if (Visited.test(w)) {
593 Allocate(w, i - shift);
597 for (unsigned j = 0; j < L.size(); ++j) {
598 Allocate(L[j], i - shift);
604 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
606 bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
607 if (IsReachable(TargetSU, SU))
609 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
611 if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
616 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
617 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
618 /// SUnit. Also returns if a successor is unscheduled in the process.
619 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
620 unsigned &CurCycle) {
622 while (CurCycle > BtCycle) {
623 OldSU = Sequence.back();
625 if (SU->isSucc(OldSU))
626 // Don't try to remove SU from AvailableQueue.
627 SU->isAvailable = false;
628 UnscheduleNodeBottomUp(OldSU);
633 if (SU->isSucc(OldSU)) {
634 assert(false && "Something is wrong!");
641 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
642 /// successors to the newly created node.
643 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
644 if (SU->FlaggedNodes.size())
647 SDNode *N = SU->Node;
652 bool TryUnfold = false;
653 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
654 MVT VT = N->getValueType(i);
657 else if (VT == MVT::Other)
660 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
661 const SDOperand &Op = N->getOperand(i);
662 MVT VT = Op.Val->getValueType(Op.ResNo);
668 SmallVector<SDNode*, 2> NewNodes;
669 if (!TII->unfoldMemoryOperand(DAG, N, NewNodes))
672 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
673 assert(NewNodes.size() == 2 && "Expected a load folding node!");
676 SDNode *LoadNode = NewNodes[0];
677 unsigned NumVals = N->getNumValues();
678 unsigned OldNumVals = SU->Node->getNumValues();
679 for (unsigned i = 0; i != NumVals; ++i)
680 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i), SDOperand(N, i));
681 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
682 SDOperand(LoadNode, 1));
684 SUnit *NewSU = CreateNewSUnit(N);
685 assert(N->getNodeId() == -1 && "Node already inserted!");
686 N->setNodeId(NewSU->NodeNum);
688 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
689 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
690 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
691 NewSU->isTwoAddress = true;
695 if (TID.isCommutable())
696 NewSU->isCommutable = true;
697 // FIXME: Calculate height / depth and propagate the changes?
698 NewSU->Depth = SU->Depth;
699 NewSU->Height = SU->Height;
700 ComputeLatency(NewSU);
702 // LoadNode may already exist. This can happen when there is another
703 // load from the same location and producing the same type of value
704 // but it has different alignment or volatileness.
705 bool isNewLoad = true;
707 if (LoadNode->getNodeId() != -1) {
708 LoadSU = &SUnits[LoadNode->getNodeId()];
711 LoadSU = CreateNewSUnit(LoadNode);
712 LoadNode->setNodeId(LoadSU->NodeNum);
714 LoadSU->Depth = SU->Depth;
715 LoadSU->Height = SU->Height;
716 ComputeLatency(LoadSU);
719 SUnit *ChainPred = NULL;
720 SmallVector<SDep, 4> ChainSuccs;
721 SmallVector<SDep, 4> LoadPreds;
722 SmallVector<SDep, 4> NodePreds;
723 SmallVector<SDep, 4> NodeSuccs;
724 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
728 else if (I->Dep->Node && I->Dep->Node->isOperandOf(LoadNode))
729 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
731 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
733 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
736 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
737 I->isCtrl, I->isSpecial));
739 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
740 I->isCtrl, I->isSpecial));
744 RemovePred(SU, ChainPred, true, false);
746 AddPred(LoadSU, ChainPred, true, false);
748 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
749 SDep *Pred = &LoadPreds[i];
750 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
752 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
753 Pred->Reg, Pred->Cost);
756 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
757 SDep *Pred = &NodePreds[i];
758 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
759 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
760 Pred->Reg, Pred->Cost);
762 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
763 SDep *Succ = &NodeSuccs[i];
764 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
765 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
766 Succ->Reg, Succ->Cost);
768 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
769 SDep *Succ = &ChainSuccs[i];
770 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
772 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
773 Succ->Reg, Succ->Cost);
777 AddPred(NewSU, LoadSU, false, false);
781 AvailableQueue->addNode(LoadSU);
782 AvailableQueue->addNode(NewSU);
786 if (NewSU->NumSuccsLeft == 0) {
787 NewSU->isAvailable = true;
793 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
794 NewSU = CreateClone(SU);
796 // New SUnit has the exact same predecessors.
797 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
800 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
801 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
804 // Only copy scheduled successors. Cut them from old node's successor
805 // list and move them over.
806 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
807 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
811 if (I->Dep->isScheduled) {
812 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
813 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
814 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
817 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
818 SUnit *Succ = DelDeps[i].first;
819 bool isCtrl = DelDeps[i].second;
820 RemovePred(Succ, SU, isCtrl, false);
823 AvailableQueue->updateNode(SU);
824 AvailableQueue->addNode(NewSU);
830 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
831 /// and move all scheduled successors of the given SUnit to the last copy.
832 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
833 const TargetRegisterClass *DestRC,
834 const TargetRegisterClass *SrcRC,
835 SmallVector<SUnit*, 2> &Copies) {
836 SUnit *CopyFromSU = CreateNewSUnit(NULL);
837 CopyFromSU->CopySrcRC = SrcRC;
838 CopyFromSU->CopyDstRC = DestRC;
839 CopyFromSU->Depth = SU->Depth;
840 CopyFromSU->Height = SU->Height;
842 SUnit *CopyToSU = CreateNewSUnit(NULL);
843 CopyToSU->CopySrcRC = DestRC;
844 CopyToSU->CopyDstRC = SrcRC;
846 // Only copy scheduled successors. Cut them from old node's successor
847 // list and move them over.
848 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
849 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
853 if (I->Dep->isScheduled) {
854 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
855 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
856 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
859 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
860 SUnit *Succ = DelDeps[i].first;
861 bool isCtrl = DelDeps[i].second;
862 RemovePred(Succ, SU, isCtrl, false);
865 AddPred(CopyFromSU, SU, false, false, Reg, -1);
866 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
868 AvailableQueue->updateNode(SU);
869 AvailableQueue->addNode(CopyFromSU);
870 AvailableQueue->addNode(CopyToSU);
871 Copies.push_back(CopyFromSU);
872 Copies.push_back(CopyToSU);
877 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
878 /// definition of the specified node.
879 /// FIXME: Move to SelectionDAG?
880 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
881 const TargetInstrInfo *TII) {
882 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
883 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
884 unsigned NumRes = TID.getNumDefs();
885 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
890 return N->getValueType(NumRes);
893 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
894 /// scheduling of the given node to satisfy live physical register dependencies.
895 /// If the specific node is the last one that's available to schedule, do
896 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
897 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
898 SmallVector<unsigned, 4> &LRegs){
899 if (LiveRegs.empty())
902 SmallSet<unsigned, 4> RegAdded;
903 // If this node would clobber any "live" register, then it's not ready.
904 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
907 unsigned Reg = I->Reg;
908 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
909 if (RegAdded.insert(Reg))
910 LRegs.push_back(Reg);
912 for (const unsigned *Alias = TRI->getAliasSet(Reg);
914 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
915 if (RegAdded.insert(*Alias))
916 LRegs.push_back(*Alias);
921 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
922 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
923 if (!Node || !Node->isTargetOpcode())
925 const TargetInstrDesc &TID = TII->get(Node->getTargetOpcode());
926 if (!TID.ImplicitDefs)
928 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
929 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
930 if (RegAdded.insert(*Reg))
931 LRegs.push_back(*Reg);
933 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
935 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
936 if (RegAdded.insert(*Alias))
937 LRegs.push_back(*Alias);
941 return !LRegs.empty();
945 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
947 void ScheduleDAGRRList::ListScheduleBottomUp() {
948 unsigned CurCycle = 0;
949 // Add root to Available queue.
950 if (!SUnits.empty()) {
951 SUnit *RootSU = &SUnits[DAG.getRoot().Val->getNodeId()];
952 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
953 RootSU->isAvailable = true;
954 AvailableQueue->push(RootSU);
957 // While Available queue is not empty, grab the node with the highest
958 // priority. If it is not ready put it back. Schedule the node.
959 SmallVector<SUnit*, 4> NotReady;
960 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
961 Sequence.reserve(SUnits.size());
962 while (!AvailableQueue->empty()) {
963 bool Delayed = false;
965 SUnit *CurSU = AvailableQueue->pop();
967 if (CurSU->CycleBound <= CurCycle) {
968 SmallVector<unsigned, 4> LRegs;
969 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
972 LRegsMap.insert(std::make_pair(CurSU, LRegs));
975 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
976 NotReady.push_back(CurSU);
977 CurSU = AvailableQueue->pop();
980 // All candidates are delayed due to live physical reg dependencies.
981 // Try backtracking, code duplication, or inserting cross class copies
983 if (Delayed && !CurSU) {
984 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
985 SUnit *TrySU = NotReady[i];
986 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
988 // Try unscheduling up to the point where it's safe to schedule
990 unsigned LiveCycle = CurCycle;
991 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
992 unsigned Reg = LRegs[j];
993 unsigned LCycle = LiveRegCycles[Reg];
994 LiveCycle = std::min(LiveCycle, LCycle);
996 SUnit *OldSU = Sequence[LiveCycle];
997 if (!WillCreateCycle(TrySU, OldSU)) {
998 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
999 // Force the current node to be scheduled before the node that
1000 // requires the physical reg dep.
1001 if (OldSU->isAvailable) {
1002 OldSU->isAvailable = false;
1003 AvailableQueue->remove(OldSU);
1005 AddPred(TrySU, OldSU, true, true);
1006 // If one or more successors has been unscheduled, then the current
1007 // node is no longer avaialable. Schedule a successor that's now
1008 // available instead.
1009 if (!TrySU->isAvailable)
1010 CurSU = AvailableQueue->pop();
1013 TrySU->isPending = false;
1014 NotReady.erase(NotReady.begin()+i);
1021 // Can't backtrack. Try duplicating the nodes that produces these
1022 // "expensive to copy" values to break the dependency. In case even
1023 // that doesn't work, insert cross class copies.
1024 SUnit *TrySU = NotReady[0];
1025 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1026 assert(LRegs.size() == 1 && "Can't handle this yet!");
1027 unsigned Reg = LRegs[0];
1028 SUnit *LRDef = LiveRegDefs[Reg];
1029 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1031 // Issue expensive cross register class copies.
1032 MVT VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
1033 const TargetRegisterClass *RC =
1034 TRI->getPhysicalRegisterRegClass(Reg, VT);
1035 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1037 assert(false && "Don't know how to copy this physical register!");
1040 SmallVector<SUnit*, 2> Copies;
1041 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1042 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1043 << " to SU #" << Copies.front()->NodeNum << "\n";
1044 AddPred(TrySU, Copies.front(), true, true);
1045 NewDef = Copies.back();
1048 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1049 << " to SU #" << TrySU->NodeNum << "\n";
1050 LiveRegDefs[Reg] = NewDef;
1051 AddPred(NewDef, TrySU, true, true);
1052 TrySU->isAvailable = false;
1057 assert(false && "Unable to resolve live physical register dependencies!");
1062 // Add the nodes that aren't ready back onto the available list.
1063 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1064 NotReady[i]->isPending = false;
1065 // May no longer be available due to backtracking.
1066 if (NotReady[i]->isAvailable)
1067 AvailableQueue->push(NotReady[i]);
1072 Sequence.push_back(0);
1074 ScheduleNodeBottomUp(CurSU, CurCycle);
1075 Sequence.push_back(CurSU);
1080 // Reverse the order if it is bottom up.
1081 std::reverse(Sequence.begin(), Sequence.end());
1085 // Verify that all SUnits were scheduled.
1086 bool AnyNotSched = false;
1087 unsigned DeadNodes = 0;
1089 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1090 if (!SUnits[i].isScheduled) {
1091 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1096 cerr << "*** List scheduling failed! ***\n";
1097 SUnits[i].dump(&DAG);
1098 cerr << "has not been scheduled!\n";
1101 if (SUnits[i].NumSuccsLeft != 0) {
1103 cerr << "*** List scheduling failed! ***\n";
1104 SUnits[i].dump(&DAG);
1105 cerr << "has successors left!\n";
1109 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1112 assert(!AnyNotSched);
1113 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1114 "The number of nodes scheduled doesn't match the expected number!");
1118 //===----------------------------------------------------------------------===//
1119 // Top-Down Scheduling
1120 //===----------------------------------------------------------------------===//
1122 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1123 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1124 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
1125 unsigned CurCycle) {
1126 // FIXME: the distance between two nodes is not always == the predecessor's
1127 // latency. For example, the reader can very well read the register written
1128 // by the predecessor later than the issue cycle. It also depends on the
1129 // interrupt model (drain vs. freeze).
1130 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
1132 --SuccSU->NumPredsLeft;
1135 if (SuccSU->NumPredsLeft < 0) {
1136 cerr << "*** List scheduling failed! ***\n";
1138 cerr << " has been released too many times!\n";
1143 if (SuccSU->NumPredsLeft == 0) {
1144 SuccSU->isAvailable = true;
1145 AvailableQueue->push(SuccSU);
1150 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1151 /// count of its successors. If a successor pending count is zero, add it to
1152 /// the Available queue.
1153 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1154 DOUT << "*** Scheduling [" << CurCycle << "]: ";
1155 DEBUG(SU->dump(&DAG));
1156 SU->Cycle = CurCycle;
1158 AvailableQueue->ScheduledNode(SU);
1160 // Top down: release successors
1161 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1163 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
1164 SU->isScheduled = true;
1167 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1169 void ScheduleDAGRRList::ListScheduleTopDown() {
1170 unsigned CurCycle = 0;
1172 // All leaves to Available queue.
1173 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1174 // It is available if it has no predecessors.
1175 if (SUnits[i].Preds.empty()) {
1176 AvailableQueue->push(&SUnits[i]);
1177 SUnits[i].isAvailable = true;
1181 // While Available queue is not empty, grab the node with the highest
1182 // priority. If it is not ready put it back. Schedule the node.
1183 std::vector<SUnit*> NotReady;
1184 Sequence.reserve(SUnits.size());
1185 while (!AvailableQueue->empty()) {
1186 SUnit *CurSU = AvailableQueue->pop();
1187 while (CurSU && CurSU->CycleBound > CurCycle) {
1188 NotReady.push_back(CurSU);
1189 CurSU = AvailableQueue->pop();
1192 // Add the nodes that aren't ready back onto the available list.
1193 AvailableQueue->push_all(NotReady);
1197 Sequence.push_back(0);
1199 ScheduleNodeTopDown(CurSU, CurCycle);
1200 Sequence.push_back(CurSU);
1207 // Verify that all SUnits were scheduled.
1208 bool AnyNotSched = false;
1209 unsigned DeadNodes = 0;
1211 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1212 if (!SUnits[i].isScheduled) {
1213 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1218 cerr << "*** List scheduling failed! ***\n";
1219 SUnits[i].dump(&DAG);
1220 cerr << "has not been scheduled!\n";
1223 if (SUnits[i].NumPredsLeft != 0) {
1225 cerr << "*** List scheduling failed! ***\n";
1226 SUnits[i].dump(&DAG);
1227 cerr << "has predecessors left!\n";
1231 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1234 assert(!AnyNotSched);
1235 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1236 "The number of nodes scheduled doesn't match the expected number!");
1242 //===----------------------------------------------------------------------===//
1243 // RegReductionPriorityQueue Implementation
1244 //===----------------------------------------------------------------------===//
1246 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1247 // to reduce register pressure.
1251 class RegReductionPriorityQueue;
1253 /// Sorting functions for the Available queue.
1254 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1255 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1256 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1257 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1259 bool operator()(const SUnit* left, const SUnit* right) const;
1262 struct bu_ls_rr_fast_sort : public std::binary_function<SUnit*, SUnit*, bool>{
1263 RegReductionPriorityQueue<bu_ls_rr_fast_sort> *SPQ;
1264 bu_ls_rr_fast_sort(RegReductionPriorityQueue<bu_ls_rr_fast_sort> *spq)
1266 bu_ls_rr_fast_sort(const bu_ls_rr_fast_sort &RHS) : SPQ(RHS.SPQ) {}
1268 bool operator()(const SUnit* left, const SUnit* right) const;
1271 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1272 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1273 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1274 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1276 bool operator()(const SUnit* left, const SUnit* right) const;
1278 } // end anonymous namespace
1280 static inline bool isCopyFromLiveIn(const SUnit *SU) {
1281 SDNode *N = SU->Node;
1282 return N && N->getOpcode() == ISD::CopyFromReg &&
1283 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1286 /// CalcNodeBUSethiUllmanNumber - Compute Sethi Ullman number for bottom up
1287 /// scheduling. Smaller number is the higher priority.
1289 CalcNodeBUSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1290 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1291 if (SethiUllmanNumber != 0)
1292 return SethiUllmanNumber;
1295 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1297 if (I->isCtrl) continue; // ignore chain preds
1298 SUnit *PredSU = I->Dep;
1299 unsigned PredSethiUllman = CalcNodeBUSethiUllmanNumber(PredSU, SUNumbers);
1300 if (PredSethiUllman > SethiUllmanNumber) {
1301 SethiUllmanNumber = PredSethiUllman;
1303 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1307 SethiUllmanNumber += Extra;
1309 if (SethiUllmanNumber == 0)
1310 SethiUllmanNumber = 1;
1312 return SethiUllmanNumber;
1315 /// CalcNodeTDSethiUllmanNumber - Compute Sethi Ullman number for top down
1316 /// scheduling. Smaller number is the higher priority.
1318 CalcNodeTDSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1319 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1320 if (SethiUllmanNumber != 0)
1321 return SethiUllmanNumber;
1323 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1324 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1325 SethiUllmanNumber = 0xffff;
1326 else if (SU->NumSuccsLeft == 0)
1327 // If SU does not have a use, i.e. it doesn't produce a value that would
1328 // be consumed (e.g. store), then it terminates a chain of computation.
1329 // Give it a small SethiUllman number so it will be scheduled right before
1330 // its predecessors that it doesn't lengthen their live ranges.
1331 SethiUllmanNumber = 0;
1332 else if (SU->NumPredsLeft == 0 &&
1333 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1334 SethiUllmanNumber = 0xffff;
1337 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1339 if (I->isCtrl) continue; // ignore chain preds
1340 SUnit *PredSU = I->Dep;
1341 unsigned PredSethiUllman = CalcNodeTDSethiUllmanNumber(PredSU, SUNumbers);
1342 if (PredSethiUllman > SethiUllmanNumber) {
1343 SethiUllmanNumber = PredSethiUllman;
1345 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1349 SethiUllmanNumber += Extra;
1352 return SethiUllmanNumber;
1358 class VISIBILITY_HIDDEN RegReductionPriorityQueue
1359 : public SchedulingPriorityQueue {
1360 PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
1361 unsigned currentQueueId;
1364 RegReductionPriorityQueue() :
1365 Queue(SF(this)), currentQueueId(0) {}
1367 virtual void initNodes(std::vector<SUnit> &sunits) {}
1369 virtual void addNode(const SUnit *SU) {}
1371 virtual void updateNode(const SUnit *SU) {}
1373 virtual void releaseState() {}
1375 virtual unsigned getNodePriority(const SUnit *SU) const {
1379 unsigned size() const { return Queue.size(); }
1381 bool empty() const { return Queue.empty(); }
1383 void push(SUnit *U) {
1384 assert(!U->NodeQueueId && "Node in the queue already");
1385 U->NodeQueueId = ++currentQueueId;
1389 void push_all(const std::vector<SUnit *> &Nodes) {
1390 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1395 if (empty()) return NULL;
1396 SUnit *V = Queue.top();
1402 void remove(SUnit *SU) {
1403 assert(!Queue.empty() && "Queue is empty!");
1404 assert(SU->NodeQueueId != 0 && "Not in queue!");
1405 Queue.erase_one(SU);
1406 SU->NodeQueueId = 0;
1410 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1411 : public RegReductionPriorityQueue<bu_ls_rr_sort> {
1412 // SUnits - The SUnits for the current graph.
1413 const std::vector<SUnit> *SUnits;
1415 // SethiUllmanNumbers - The SethiUllman number for each node.
1416 std::vector<unsigned> SethiUllmanNumbers;
1418 const TargetInstrInfo *TII;
1419 const TargetRegisterInfo *TRI;
1420 ScheduleDAGRRList *scheduleDAG;
1423 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii,
1424 const TargetRegisterInfo *tri)
1425 : TII(tii), TRI(tri), scheduleDAG(NULL) {}
1427 void initNodes(std::vector<SUnit> &sunits) {
1429 // Add pseudo dependency edges for two-address nodes.
1430 AddPseudoTwoAddrDeps();
1431 // Calculate node priorities.
1432 CalculateSethiUllmanNumbers();
1435 void addNode(const SUnit *SU) {
1436 unsigned SUSize = SethiUllmanNumbers.size();
1437 if (SUnits->size() > SUSize)
1438 SethiUllmanNumbers.resize(SUSize*2, 0);
1439 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1442 void updateNode(const SUnit *SU) {
1443 SethiUllmanNumbers[SU->NodeNum] = 0;
1444 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1447 void releaseState() {
1449 SethiUllmanNumbers.clear();
1452 unsigned getNodePriority(const SUnit *SU) const {
1453 assert(SU->NodeNum < SethiUllmanNumbers.size());
1454 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1455 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1456 // CopyFromReg should be close to its def because it restricts
1457 // allocation choices. But if it is a livein then perhaps we want it
1458 // closer to its uses so it can be coalesced.
1460 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1461 // CopyToReg should be close to its uses to facilitate coalescing and
1464 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1465 Opc == TargetInstrInfo::INSERT_SUBREG)
1466 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1467 // facilitate coalescing.
1469 else if (SU->NumSuccs == 0)
1470 // If SU does not have a use, i.e. it doesn't produce a value that would
1471 // be consumed (e.g. store), then it terminates a chain of computation.
1472 // Give it a large SethiUllman number so it will be scheduled right
1473 // before its predecessors that it doesn't lengthen their live ranges.
1475 else if (SU->NumPreds == 0)
1476 // If SU does not have a def, schedule it close to its uses because it
1477 // does not lengthen any live ranges.
1480 return SethiUllmanNumbers[SU->NodeNum];
1483 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1484 scheduleDAG = scheduleDag;
1488 bool canClobber(const SUnit *SU, const SUnit *Op);
1489 void AddPseudoTwoAddrDeps();
1490 void CalculateSethiUllmanNumbers();
1494 class VISIBILITY_HIDDEN BURegReductionFastPriorityQueue
1495 : public RegReductionPriorityQueue<bu_ls_rr_fast_sort> {
1496 // SUnits - The SUnits for the current graph.
1497 const std::vector<SUnit> *SUnits;
1499 // SethiUllmanNumbers - The SethiUllman number for each node.
1500 std::vector<unsigned> SethiUllmanNumbers;
1502 explicit BURegReductionFastPriorityQueue() {}
1504 void initNodes(std::vector<SUnit> &sunits) {
1506 // Calculate node priorities.
1507 CalculateSethiUllmanNumbers();
1510 void addNode(const SUnit *SU) {
1511 unsigned SUSize = SethiUllmanNumbers.size();
1512 if (SUnits->size() > SUSize)
1513 SethiUllmanNumbers.resize(SUSize*2, 0);
1514 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1517 void updateNode(const SUnit *SU) {
1518 SethiUllmanNumbers[SU->NodeNum] = 0;
1519 CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1522 void releaseState() {
1524 SethiUllmanNumbers.clear();
1527 unsigned getNodePriority(const SUnit *SU) const {
1528 return SethiUllmanNumbers[SU->NodeNum];
1532 void CalculateSethiUllmanNumbers();
1536 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1537 : public RegReductionPriorityQueue<td_ls_rr_sort> {
1538 // SUnits - The SUnits for the current graph.
1539 const std::vector<SUnit> *SUnits;
1541 // SethiUllmanNumbers - The SethiUllman number for each node.
1542 std::vector<unsigned> SethiUllmanNumbers;
1545 TDRegReductionPriorityQueue() {}
1547 void initNodes(std::vector<SUnit> &sunits) {
1549 // Calculate node priorities.
1550 CalculateSethiUllmanNumbers();
1553 void addNode(const SUnit *SU) {
1554 unsigned SUSize = SethiUllmanNumbers.size();
1555 if (SUnits->size() > SUSize)
1556 SethiUllmanNumbers.resize(SUSize*2, 0);
1557 CalcNodeTDSethiUllmanNumber(SU, SethiUllmanNumbers);
1560 void updateNode(const SUnit *SU) {
1561 SethiUllmanNumbers[SU->NodeNum] = 0;
1562 CalcNodeTDSethiUllmanNumber(SU, SethiUllmanNumbers);
1565 void releaseState() {
1567 SethiUllmanNumbers.clear();
1570 unsigned getNodePriority(const SUnit *SU) const {
1571 assert(SU->NodeNum < SethiUllmanNumbers.size());
1572 return SethiUllmanNumbers[SU->NodeNum];
1576 void CalculateSethiUllmanNumbers();
1580 /// closestSucc - Returns the scheduled cycle of the successor which is
1581 /// closet to the current cycle.
1582 static unsigned closestSucc(const SUnit *SU) {
1583 unsigned MaxCycle = 0;
1584 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1586 unsigned Cycle = I->Dep->Cycle;
1587 // If there are bunch of CopyToRegs stacked up, they should be considered
1588 // to be at the same position.
1589 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
1590 Cycle = closestSucc(I->Dep)+1;
1591 if (Cycle > MaxCycle)
1597 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1598 /// for scratch registers. Live-in operands and live-out results don't count
1599 /// since they are "fixed".
1600 static unsigned calcMaxScratches(const SUnit *SU) {
1601 unsigned Scratches = 0;
1602 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1604 if (I->isCtrl) continue; // ignore chain preds
1605 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyFromReg)
1608 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1610 if (I->isCtrl) continue; // ignore chain succs
1611 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyToReg)
1618 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1619 unsigned LPriority = SPQ->getNodePriority(left);
1620 unsigned RPriority = SPQ->getNodePriority(right);
1621 if (LPriority != RPriority)
1622 return LPriority > RPriority;
1624 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1629 // and the following instructions are both ready.
1633 // Then schedule t2 = op first.
1640 // This creates more short live intervals.
1641 unsigned LDist = closestSucc(left);
1642 unsigned RDist = closestSucc(right);
1644 return LDist < RDist;
1646 // Intuitively, it's good to push down instructions whose results are
1647 // liveout so their long live ranges won't conflict with other values
1648 // which are needed inside the BB. Further prioritize liveout instructions
1649 // by the number of operands which are calculated within the BB.
1650 unsigned LScratch = calcMaxScratches(left);
1651 unsigned RScratch = calcMaxScratches(right);
1652 if (LScratch != RScratch)
1653 return LScratch > RScratch;
1655 if (left->Height != right->Height)
1656 return left->Height > right->Height;
1658 if (left->Depth != right->Depth)
1659 return left->Depth < right->Depth;
1661 if (left->CycleBound != right->CycleBound)
1662 return left->CycleBound > right->CycleBound;
1664 assert(left->NodeQueueId && right->NodeQueueId &&
1665 "NodeQueueId cannot be zero");
1666 return (left->NodeQueueId > right->NodeQueueId);
1670 bu_ls_rr_fast_sort::operator()(const SUnit *left, const SUnit *right) const {
1671 unsigned LPriority = SPQ->getNodePriority(left);
1672 unsigned RPriority = SPQ->getNodePriority(right);
1673 if (LPriority != RPriority)
1674 return LPriority > RPriority;
1675 assert(left->NodeQueueId && right->NodeQueueId &&
1676 "NodeQueueId cannot be zero");
1677 return (left->NodeQueueId > right->NodeQueueId);
1681 BURegReductionPriorityQueue::canClobber(const SUnit *SU, const SUnit *Op) {
1682 if (SU->isTwoAddress) {
1683 unsigned Opc = SU->Node->getTargetOpcode();
1684 const TargetInstrDesc &TID = TII->get(Opc);
1685 unsigned NumRes = TID.getNumDefs();
1686 unsigned NumOps = TID.getNumOperands() - NumRes;
1687 for (unsigned i = 0; i != NumOps; ++i) {
1688 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1689 SDNode *DU = SU->Node->getOperand(i).Val;
1690 if (DU->getNodeId() != -1 &&
1691 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1700 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1702 static bool hasCopyToRegUse(SUnit *SU) {
1703 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1705 if (I->isCtrl) continue;
1706 SUnit *SuccSU = I->Dep;
1707 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1713 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1714 /// physical register defs.
1715 static bool canClobberPhysRegDefs(SUnit *SuccSU, SUnit *SU,
1716 const TargetInstrInfo *TII,
1717 const TargetRegisterInfo *TRI) {
1718 SDNode *N = SuccSU->Node;
1719 unsigned NumDefs = TII->get(N->getTargetOpcode()).getNumDefs();
1720 const unsigned *ImpDefs = TII->get(N->getTargetOpcode()).getImplicitDefs();
1721 assert(ImpDefs && "Caller should check hasPhysRegDefs");
1722 const unsigned *SUImpDefs =
1723 TII->get(SU->Node->getTargetOpcode()).getImplicitDefs();
1726 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1727 MVT VT = N->getValueType(i);
1728 if (VT == MVT::Flag || VT == MVT::Other)
1730 unsigned Reg = ImpDefs[i - NumDefs];
1731 for (;*SUImpDefs; ++SUImpDefs) {
1732 unsigned SUReg = *SUImpDefs;
1733 if (TRI->regsOverlap(Reg, SUReg))
1740 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1741 /// it as a def&use operand. Add a pseudo control edge from it to the other
1742 /// node (if it won't create a cycle) so the two-address one will be scheduled
1743 /// first (lower in the schedule). If both nodes are two-address, favor the
1744 /// one that has a CopyToReg use (more likely to be a loop induction update).
1745 /// If both are two-address, but one is commutable while the other is not
1746 /// commutable, favor the one that's not commutable.
1747 void BURegReductionPriorityQueue::AddPseudoTwoAddrDeps() {
1748 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1749 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1750 if (!SU->isTwoAddress)
1753 SDNode *Node = SU->Node;
1754 if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
1757 unsigned Opc = Node->getTargetOpcode();
1758 const TargetInstrDesc &TID = TII->get(Opc);
1759 unsigned NumRes = TID.getNumDefs();
1760 unsigned NumOps = TID.getNumOperands() - NumRes;
1761 for (unsigned j = 0; j != NumOps; ++j) {
1762 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) != -1) {
1763 SDNode *DU = SU->Node->getOperand(j).Val;
1764 if (DU->getNodeId() == -1)
1766 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1767 if (!DUSU) continue;
1768 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1769 E = DUSU->Succs.end(); I != E; ++I) {
1770 if (I->isCtrl) continue;
1771 SUnit *SuccSU = I->Dep;
1774 // Be conservative. Ignore if nodes aren't at roughly the same
1775 // depth and height.
1776 if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1778 if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1780 // Don't constrain nodes with physical register defs if the
1781 // predecessor can clobber them.
1782 if (SuccSU->hasPhysRegDefs) {
1783 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1786 // Don't constraint extract_subreg / insert_subreg these may be
1787 // coalesced away. We don't them close to their uses.
1788 unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1789 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1790 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1792 if ((!canClobber(SuccSU, DUSU) ||
1793 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1794 (!SU->isCommutable && SuccSU->isCommutable)) &&
1795 !scheduleDAG->IsReachable(SuccSU, SU)) {
1796 DOUT << "Adding an edge from SU # " << SU->NodeNum
1797 << " to SU #" << SuccSU->NodeNum << "\n";
1798 scheduleDAG->AddPred(SU, SuccSU, true, true);
1806 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1807 /// scheduling units.
1808 void BURegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1809 SethiUllmanNumbers.assign(SUnits->size(), 0);
1811 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1812 CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1814 void BURegReductionFastPriorityQueue::CalculateSethiUllmanNumbers() {
1815 SethiUllmanNumbers.assign(SUnits->size(), 0);
1817 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1818 CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1821 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1822 /// predecessors of the successors of the SUnit SU. Stop when the provided
1823 /// limit is exceeded.
1824 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
1827 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1829 SUnit *SuccSU = I->Dep;
1830 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1831 EE = SuccSU->Preds.end(); II != EE; ++II) {
1832 SUnit *PredSU = II->Dep;
1833 if (!PredSU->isScheduled)
1843 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1844 unsigned LPriority = SPQ->getNodePriority(left);
1845 unsigned RPriority = SPQ->getNodePriority(right);
1846 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1847 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
1848 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1849 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1850 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1851 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1853 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1855 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1862 if (left->NumSuccs == 1)
1864 if (right->NumSuccs == 1)
1867 if (LPriority+LBonus != RPriority+RBonus)
1868 return LPriority+LBonus < RPriority+RBonus;
1870 if (left->Depth != right->Depth)
1871 return left->Depth < right->Depth;
1873 if (left->NumSuccsLeft != right->NumSuccsLeft)
1874 return left->NumSuccsLeft > right->NumSuccsLeft;
1876 if (left->CycleBound != right->CycleBound)
1877 return left->CycleBound > right->CycleBound;
1879 assert(left->NodeQueueId && right->NodeQueueId &&
1880 "NodeQueueId cannot be zero");
1881 return (left->NodeQueueId > right->NodeQueueId);
1884 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1885 /// scheduling units.
1886 void TDRegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1887 SethiUllmanNumbers.assign(SUnits->size(), 0);
1889 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1890 CalcNodeTDSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1893 //===----------------------------------------------------------------------===//
1894 // Public Constructor Functions
1895 //===----------------------------------------------------------------------===//
1897 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1899 MachineBasicBlock *BB,
1902 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true, true,
1903 new BURegReductionFastPriorityQueue());
1905 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
1906 const TargetRegisterInfo *TRI = DAG->getTarget().getRegisterInfo();
1908 BURegReductionPriorityQueue *PQ = new BURegReductionPriorityQueue(TII, TRI);
1910 ScheduleDAGRRList *SD =
1911 new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(),true,false, PQ);
1912 PQ->setScheduleDAG(SD);
1916 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1918 MachineBasicBlock *BB,
1920 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false, Fast,
1921 new TDRegReductionPriorityQueue());