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 /// AvailableQueue - The priority queue to use for the available SUnits.
63 SchedulingPriorityQueue *AvailableQueue;
65 /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
66 /// that are "live". These nodes must be scheduled before any other nodes that
67 /// modifies the registers can be scheduled.
68 SmallSet<unsigned, 4> LiveRegs;
69 std::vector<SUnit*> LiveRegDefs;
70 std::vector<unsigned> LiveRegCycles;
73 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
74 const TargetMachine &tm, bool isbottomup,
75 SchedulingPriorityQueue *availqueue)
76 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
77 AvailableQueue(availqueue) {
80 ~ScheduleDAGRRList() {
81 delete AvailableQueue;
86 /// IsReachable - Checks if SU is reachable from TargetSU.
87 bool IsReachable(SUnit *SU, SUnit *TargetSU);
89 /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
91 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
93 /// AddPred - This adds the specified node X as a predecessor of
94 /// the current node Y if not already.
95 /// This returns true if this is a new predecessor.
96 /// Updates the topological ordering if required.
97 bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
98 unsigned PhyReg = 0, int Cost = 1);
100 /// RemovePred - This removes the specified node N from the predecessors of
101 /// the current node M. Updates the topological ordering if required.
102 bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
105 void ReleasePred(SUnit*, bool, unsigned);
106 void ReleaseSucc(SUnit*, bool isChain, unsigned);
107 void CapturePred(SUnit*, SUnit*, bool);
108 void ScheduleNodeBottomUp(SUnit*, unsigned);
109 void ScheduleNodeTopDown(SUnit*, unsigned);
110 void UnscheduleNodeBottomUp(SUnit*);
111 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
112 SUnit *CopyAndMoveSuccessors(SUnit*);
113 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
114 const TargetRegisterClass*,
115 const TargetRegisterClass*,
116 SmallVector<SUnit*, 2>&);
117 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
118 void ListScheduleTopDown();
119 void ListScheduleBottomUp();
120 void CommuteNodesToReducePressure();
123 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
124 /// Updates the topological ordering if required.
125 SUnit *CreateNewSUnit(SDNode *N) {
126 SUnit *NewNode = NewSUnit(N);
127 // Update the topological ordering.
128 if (NewNode->NodeNum >= Node2Index.size())
129 InitDAGTopologicalSorting();
133 /// CreateClone - Creates a new SUnit from an existing one.
134 /// Updates the topological ordering if required.
135 SUnit *CreateClone(SUnit *N) {
136 SUnit *NewNode = Clone(N);
137 // Update the topological ordering.
138 if (NewNode->NodeNum >= Node2Index.size())
139 InitDAGTopologicalSorting();
143 /// Functions for preserving the topological ordering
144 /// even after dynamic insertions of new edges.
145 /// This allows a very fast implementation of IsReachable.
149 The idea of the algorithm is taken from
150 "Online algorithms for managing the topological order of
151 a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
152 This is the MNR algorithm, which was first introduced by
153 A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
154 "Maintaining a topological order under edge insertions".
156 Short description of the algorithm:
158 Topological ordering, ord, of a DAG maps each node to a topological
159 index so that for all edges X->Y it is the case that ord(X) < ord(Y).
161 This means that if there is a path from the node X to the node Z,
162 then ord(X) < ord(Z).
164 This property can be used to check for reachability of nodes:
165 if Z is reachable from X, then an insertion of the edge Z->X would
168 The algorithm first computes a topological ordering for the DAG by initializing
169 the Index2Node and Node2Index arrays and then tries to keep the ordering
170 up-to-date after edge insertions by reordering the DAG.
172 On insertion of the edge X->Y, the algorithm first marks by calling DFS the
173 nodes reachable from Y, and then shifts them using Shift to lie immediately
174 after X in Index2Node.
177 /// InitDAGTopologicalSorting - create the initial topological
178 /// ordering from the DAG to be scheduled.
179 void InitDAGTopologicalSorting();
181 /// DFS - make a DFS traversal and mark all nodes affected by the
182 /// edge insertion. These nodes will later get new topological indexes
183 /// by means of the Shift method.
184 void DFS(SUnit *SU, int UpperBound, bool& HasLoop);
186 /// Shift - reassign topological indexes for the nodes in the DAG
187 /// to preserve the topological ordering.
188 void Shift(BitVector& Visited, int LowerBound, int UpperBound);
190 /// Allocate - assign the topological index to the node n.
191 void Allocate(int n, int index);
193 /// Index2Node - Maps topological index to the node number.
194 std::vector<int> Index2Node;
195 /// Node2Index - Maps the node number to its topological index.
196 std::vector<int> Node2Index;
197 /// Visited - a set of nodes visited during a DFS traversal.
200 } // end anonymous namespace
203 /// Schedule - Schedule the DAG using list scheduling.
204 void ScheduleDAGRRList::Schedule() {
205 DOUT << "********** List Scheduling **********\n";
207 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
208 LiveRegCycles.resize(TRI->getNumRegs(), 0);
210 // Build scheduling units.
213 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
214 SUnits[su].dumpAll(&DAG));
217 InitDAGTopologicalSorting();
219 AvailableQueue->initNodes(SUnitMap, SUnits);
221 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
223 ListScheduleBottomUp();
225 ListScheduleTopDown();
227 AvailableQueue->releaseState();
229 CommuteNodesToReducePressure();
231 DOUT << "*** Final schedule ***\n";
232 DEBUG(dumpSchedule());
235 // Emit in scheduled order
239 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
240 /// it is not the last use of its first operand, add it to the CommuteSet if
241 /// possible. It will be commuted when it is translated to a MI.
242 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
243 SmallPtrSet<SUnit*, 4> OperandSeen;
244 for (unsigned i = Sequence.size(); i != 0; ) {
246 SUnit *SU = Sequence[i];
247 if (!SU || !SU->Node) continue;
248 if (SU->isCommutable) {
249 unsigned Opc = SU->Node->getTargetOpcode();
250 const TargetInstrDesc &TID = TII->get(Opc);
251 unsigned NumRes = TID.getNumDefs();
252 unsigned NumOps = TID.getNumOperands() - NumRes;
253 for (unsigned j = 0; j != NumOps; ++j) {
254 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
257 SDNode *OpN = SU->Node->getOperand(j).Val;
258 SUnit *OpSU = isPassiveNode(OpN) ? NULL : SUnitMap[OpN];
259 if (OpSU && OperandSeen.count(OpSU) == 1) {
260 // Ok, so SU is not the last use of OpSU, but SU is two-address so
261 // it will clobber OpSU. Try to commute SU if no other source operands
263 bool DoCommute = true;
264 for (unsigned k = 0; k < NumOps; ++k) {
266 OpN = SU->Node->getOperand(k).Val;
267 OpSU = isPassiveNode(OpN) ? NULL : SUnitMap[OpN];
268 if (OpSU && OperandSeen.count(OpSU) == 1) {
275 CommuteSet.insert(SU->Node);
278 // Only look at the first use&def node for now.
283 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
286 OperandSeen.insert(I->Dep->OrigNode);
291 //===----------------------------------------------------------------------===//
292 // Bottom-Up Scheduling
293 //===----------------------------------------------------------------------===//
295 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
296 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
297 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
299 // FIXME: the distance between two nodes is not always == the predecessor's
300 // latency. For example, the reader can very well read the register written
301 // by the predecessor later than the issue cycle. It also depends on the
302 // interrupt model (drain vs. freeze).
303 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
305 --PredSU->NumSuccsLeft;
308 if (PredSU->NumSuccsLeft < 0) {
309 cerr << "*** List scheduling failed! ***\n";
311 cerr << " has been released too many times!\n";
316 if (PredSU->NumSuccsLeft == 0) {
317 PredSU->isAvailable = true;
318 AvailableQueue->push(PredSU);
322 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
323 /// count of its predecessors. If a predecessor pending count is zero, add it to
324 /// the Available queue.
325 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
326 DOUT << "*** Scheduling [" << CurCycle << "]: ";
327 DEBUG(SU->dump(&DAG));
328 SU->Cycle = CurCycle;
330 AvailableQueue->ScheduledNode(SU);
332 // Bottom up: release predecessors
333 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
335 ReleasePred(I->Dep, I->isCtrl, CurCycle);
337 // This is a physical register dependency and it's impossible or
338 // expensive to copy the register. Make sure nothing that can
339 // clobber the register is scheduled between the predecessor and
341 if (LiveRegs.insert(I->Reg)) {
342 LiveRegDefs[I->Reg] = I->Dep;
343 LiveRegCycles[I->Reg] = CurCycle;
348 // Release all the implicit physical register defs that are live.
349 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
352 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
353 LiveRegs.erase(I->Reg);
354 assert(LiveRegDefs[I->Reg] == SU &&
355 "Physical register dependency violated?");
356 LiveRegDefs[I->Reg] = NULL;
357 LiveRegCycles[I->Reg] = 0;
362 SU->isScheduled = true;
365 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
366 /// unscheduled, incrcease the succ left count of its predecessors. Remove
367 /// them from AvailableQueue if necessary.
368 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
369 unsigned CycleBound = 0;
370 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
374 CycleBound = std::max(CycleBound,
375 I->Dep->Cycle + PredSU->Latency);
378 if (PredSU->isAvailable) {
379 PredSU->isAvailable = false;
380 if (!PredSU->isPending)
381 AvailableQueue->remove(PredSU);
384 PredSU->CycleBound = CycleBound;
385 ++PredSU->NumSuccsLeft;
388 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
389 /// its predecessor states to reflect the change.
390 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
391 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
392 DEBUG(SU->dump(&DAG));
394 AvailableQueue->UnscheduledNode(SU);
396 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
398 CapturePred(I->Dep, SU, I->isCtrl);
399 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
400 LiveRegs.erase(I->Reg);
401 assert(LiveRegDefs[I->Reg] == I->Dep &&
402 "Physical register dependency violated?");
403 LiveRegDefs[I->Reg] = NULL;
404 LiveRegCycles[I->Reg] = 0;
408 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
411 if (LiveRegs.insert(I->Reg)) {
412 assert(!LiveRegDefs[I->Reg] &&
413 "Physical register dependency violated?");
414 LiveRegDefs[I->Reg] = SU;
416 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
417 LiveRegCycles[I->Reg] = I->Dep->Cycle;
422 SU->isScheduled = false;
423 SU->isAvailable = true;
424 AvailableQueue->push(SU);
427 /// IsReachable - Checks if SU is reachable from TargetSU.
428 bool ScheduleDAGRRList::IsReachable(SUnit *SU, SUnit *TargetSU) {
429 // If insertion of the edge SU->TargetSU would create a cycle
430 // then there is a path from TargetSU to SU.
431 int UpperBound, LowerBound;
432 LowerBound = Node2Index[TargetSU->NodeNum];
433 UpperBound = Node2Index[SU->NodeNum];
434 bool HasLoop = false;
435 // Is Ord(TargetSU) < Ord(SU) ?
436 if (LowerBound < UpperBound) {
438 // There may be a path from TargetSU to SU. Check for it.
439 DFS(TargetSU, UpperBound, HasLoop);
444 /// Allocate - assign the topological index to the node n.
445 inline void ScheduleDAGRRList::Allocate(int n, int index) {
446 Node2Index[n] = index;
447 Index2Node[index] = n;
450 /// InitDAGTopologicalSorting - create the initial topological
451 /// ordering from the DAG to be scheduled.
452 void ScheduleDAGRRList::InitDAGTopologicalSorting() {
453 unsigned DAGSize = SUnits.size();
454 std::vector<unsigned> InDegree(DAGSize);
455 std::vector<SUnit*> WorkList;
456 WorkList.reserve(DAGSize);
457 std::vector<SUnit*> TopOrder;
458 TopOrder.reserve(DAGSize);
460 // Initialize the data structures.
461 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
462 SUnit *SU = &SUnits[i];
463 int NodeNum = SU->NodeNum;
464 unsigned Degree = SU->Succs.size();
465 InDegree[NodeNum] = Degree;
467 // Is it a node without dependencies?
469 assert(SU->Succs.empty() && "SUnit should have no successors");
470 // Collect leaf nodes.
471 WorkList.push_back(SU);
475 while (!WorkList.empty()) {
476 SUnit *SU = WorkList.back();
478 TopOrder.push_back(SU);
479 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
482 if (!--InDegree[SU->NodeNum])
483 // If all dependencies of the node are processed already,
484 // then the node can be computed now.
485 WorkList.push_back(SU);
489 // Second pass, assign the actual topological order as node ids.
494 Index2Node.resize(DAGSize);
495 Node2Index.resize(DAGSize);
496 Visited.resize(DAGSize);
498 for (std::vector<SUnit*>::reverse_iterator TI = TopOrder.rbegin(),
499 TE = TopOrder.rend();TI != TE; ++TI) {
500 Allocate((*TI)->NodeNum, Id);
505 // Check correctness of the ordering
506 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
507 SUnit *SU = &SUnits[i];
508 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
510 assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] &&
511 "Wrong topological sorting");
517 /// AddPred - adds an edge from SUnit X to SUnit Y.
518 /// Updates the topological ordering if required.
519 bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
520 unsigned PhyReg, int Cost) {
521 int UpperBound, LowerBound;
522 LowerBound = Node2Index[Y->NodeNum];
523 UpperBound = Node2Index[X->NodeNum];
524 bool HasLoop = false;
525 // Is Ord(X) < Ord(Y) ?
526 if (LowerBound < UpperBound) {
527 // Update the topological order.
529 DFS(Y, UpperBound, HasLoop);
530 assert(!HasLoop && "Inserted edge creates a loop!");
531 // Recompute topological indexes.
532 Shift(Visited, LowerBound, UpperBound);
534 // Now really insert the edge.
535 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
538 /// RemovePred - This removes the specified node N from the predecessors of
539 /// the current node M. Updates the topological ordering if required.
540 bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N,
541 bool isCtrl, bool isSpecial) {
542 // InitDAGTopologicalSorting();
543 return M->removePred(N, isCtrl, isSpecial);
546 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
547 /// all nodes affected by the edge insertion. These nodes will later get new
548 /// topological indexes by means of the Shift method.
549 void ScheduleDAGRRList::DFS(SUnit *SU, int UpperBound, bool& HasLoop) {
550 std::vector<SUnit*> WorkList;
551 WorkList.reserve(SUnits.size());
553 WorkList.push_back(SU);
554 while (!WorkList.empty()) {
555 SU = WorkList.back();
557 Visited.set(SU->NodeNum);
558 for (int I = SU->Succs.size()-1; I >= 0; --I) {
559 int s = SU->Succs[I].Dep->NodeNum;
560 if (Node2Index[s] == UpperBound) {
564 // Visit successors if not already and in affected region.
565 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
566 WorkList.push_back(SU->Succs[I].Dep);
572 /// Shift - Renumber the nodes so that the topological ordering is
574 void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound,
580 for (i = LowerBound; i <= UpperBound; ++i) {
581 // w is node at topological index i.
582 int w = Index2Node[i];
583 if (Visited.test(w)) {
589 Allocate(w, i - shift);
593 for (unsigned j = 0; j < L.size(); ++j) {
594 Allocate(L[j], i - shift);
600 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
602 bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
603 if (IsReachable(TargetSU, SU))
605 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
607 if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
612 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
613 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
614 /// SUnit. Also returns if a successor is unscheduled in the process.
615 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
616 unsigned &CurCycle) {
618 while (CurCycle > BtCycle) {
619 OldSU = Sequence.back();
621 if (SU->isSucc(OldSU))
622 // Don't try to remove SU from AvailableQueue.
623 SU->isAvailable = false;
624 UnscheduleNodeBottomUp(OldSU);
629 if (SU->isSucc(OldSU)) {
630 assert(false && "Something is wrong!");
637 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
638 /// successors to the newly created node.
639 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
640 if (SU->FlaggedNodes.size())
643 SDNode *N = SU->Node;
648 bool TryUnfold = false;
649 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
650 MVT VT = N->getValueType(i);
653 else if (VT == MVT::Other)
656 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
657 const SDOperand &Op = N->getOperand(i);
658 MVT VT = Op.Val->getValueType(Op.ResNo);
664 SmallVector<SDNode*, 2> NewNodes;
665 if (!TII->unfoldMemoryOperand(DAG, N, NewNodes))
668 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
669 assert(NewNodes.size() == 2 && "Expected a load folding node!");
672 SDNode *LoadNode = NewNodes[0];
673 unsigned NumVals = N->getNumValues();
674 unsigned OldNumVals = SU->Node->getNumValues();
675 for (unsigned i = 0; i != NumVals; ++i)
676 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i), SDOperand(N, i));
677 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
678 SDOperand(LoadNode, 1));
680 SUnit *NewSU = CreateNewSUnit(N);
681 bool isNew = SUnitMap.insert(std::make_pair(N, NewSU));
683 assert(isNew && "Node already inserted!");
685 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
686 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
687 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
688 NewSU->isTwoAddress = true;
692 if (TID.isCommutable())
693 NewSU->isCommutable = true;
694 // FIXME: Calculate height / depth and propagate the changes?
695 NewSU->Depth = SU->Depth;
696 NewSU->Height = SU->Height;
697 ComputeLatency(NewSU);
699 // LoadNode may already exist. This can happen when there is another
700 // load from the same location and producing the same type of value
701 // but it has different alignment or volatileness.
702 bool isNewLoad = true;
704 DenseMap<SDNode*, SUnit*>::iterator SMI = SUnitMap.find(LoadNode);
705 if (SMI != SUnitMap.end()) {
706 LoadSU = SMI->second;
709 LoadSU = CreateNewSUnit(LoadNode);
710 bool isNew = SUnitMap.insert(std::make_pair(LoadNode, LoadSU));
712 assert(isNew && "Node already inserted!");
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 = SUnitMap[DAG.getRoot().Val];
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 Sequence.reserve(SUnits.size());
961 while (!AvailableQueue->empty()) {
962 bool Delayed = false;
963 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
964 SUnit *CurSU = AvailableQueue->pop();
966 if (CurSU->CycleBound <= CurCycle) {
967 SmallVector<unsigned, 4> LRegs;
968 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
971 LRegsMap.insert(std::make_pair(CurSU, LRegs));
974 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
975 NotReady.push_back(CurSU);
976 CurSU = AvailableQueue->pop();
979 // All candidates are delayed due to live physical reg dependencies.
980 // Try backtracking, code duplication, or inserting cross class copies
982 if (Delayed && !CurSU) {
983 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
984 SUnit *TrySU = NotReady[i];
985 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
987 // Try unscheduling up to the point where it's safe to schedule
989 unsigned LiveCycle = CurCycle;
990 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
991 unsigned Reg = LRegs[j];
992 unsigned LCycle = LiveRegCycles[Reg];
993 LiveCycle = std::min(LiveCycle, LCycle);
995 SUnit *OldSU = Sequence[LiveCycle];
996 if (!WillCreateCycle(TrySU, OldSU)) {
997 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
998 // Force the current node to be scheduled before the node that
999 // requires the physical reg dep.
1000 if (OldSU->isAvailable) {
1001 OldSU->isAvailable = false;
1002 AvailableQueue->remove(OldSU);
1004 AddPred(TrySU, OldSU, true, true);
1005 // If one or more successors has been unscheduled, then the current
1006 // node is no longer avaialable. Schedule a successor that's now
1007 // available instead.
1008 if (!TrySU->isAvailable)
1009 CurSU = AvailableQueue->pop();
1012 TrySU->isPending = false;
1013 NotReady.erase(NotReady.begin()+i);
1020 // Can't backtrack. Try duplicating the nodes that produces these
1021 // "expensive to copy" values to break the dependency. In case even
1022 // that doesn't work, insert cross class copies.
1023 SUnit *TrySU = NotReady[0];
1024 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1025 assert(LRegs.size() == 1 && "Can't handle this yet!");
1026 unsigned Reg = LRegs[0];
1027 SUnit *LRDef = LiveRegDefs[Reg];
1028 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1030 // Issue expensive cross register class copies.
1031 MVT VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
1032 const TargetRegisterClass *RC =
1033 TRI->getPhysicalRegisterRegClass(Reg, VT);
1034 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1036 assert(false && "Don't know how to copy this physical register!");
1039 SmallVector<SUnit*, 2> Copies;
1040 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1041 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1042 << " to SU #" << Copies.front()->NodeNum << "\n";
1043 AddPred(TrySU, Copies.front(), true, true);
1044 NewDef = Copies.back();
1047 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1048 << " to SU #" << TrySU->NodeNum << "\n";
1049 LiveRegDefs[Reg] = NewDef;
1050 AddPred(NewDef, TrySU, true, true);
1051 TrySU->isAvailable = false;
1056 assert(false && "Unable to resolve live physical register dependencies!");
1061 // Add the nodes that aren't ready back onto the available list.
1062 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1063 NotReady[i]->isPending = false;
1064 // May no longer be available due to backtracking.
1065 if (NotReady[i]->isAvailable)
1066 AvailableQueue->push(NotReady[i]);
1071 Sequence.push_back(0);
1073 ScheduleNodeBottomUp(CurSU, CurCycle);
1074 Sequence.push_back(CurSU);
1079 // Reverse the order if it is bottom up.
1080 std::reverse(Sequence.begin(), Sequence.end());
1084 // Verify that all SUnits were scheduled.
1085 bool AnyNotSched = false;
1086 unsigned DeadNodes = 0;
1088 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1089 if (!SUnits[i].isScheduled) {
1090 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1095 cerr << "*** List scheduling failed! ***\n";
1096 SUnits[i].dump(&DAG);
1097 cerr << "has not been scheduled!\n";
1100 if (SUnits[i].NumSuccsLeft != 0) {
1102 cerr << "*** List scheduling failed! ***\n";
1103 SUnits[i].dump(&DAG);
1104 cerr << "has successors left!\n";
1108 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1111 assert(!AnyNotSched);
1112 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1113 "The number of nodes scheduled doesn't match the expected number!");
1117 //===----------------------------------------------------------------------===//
1118 // Top-Down Scheduling
1119 //===----------------------------------------------------------------------===//
1121 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1122 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1123 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
1124 unsigned CurCycle) {
1125 // FIXME: the distance between two nodes is not always == the predecessor's
1126 // latency. For example, the reader can very well read the register written
1127 // by the predecessor later than the issue cycle. It also depends on the
1128 // interrupt model (drain vs. freeze).
1129 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
1131 --SuccSU->NumPredsLeft;
1134 if (SuccSU->NumPredsLeft < 0) {
1135 cerr << "*** List scheduling failed! ***\n";
1137 cerr << " has been released too many times!\n";
1142 if (SuccSU->NumPredsLeft == 0) {
1143 SuccSU->isAvailable = true;
1144 AvailableQueue->push(SuccSU);
1149 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1150 /// count of its successors. If a successor pending count is zero, add it to
1151 /// the Available queue.
1152 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1153 DOUT << "*** Scheduling [" << CurCycle << "]: ";
1154 DEBUG(SU->dump(&DAG));
1155 SU->Cycle = CurCycle;
1157 AvailableQueue->ScheduledNode(SU);
1159 // Top down: release successors
1160 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1162 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
1163 SU->isScheduled = true;
1166 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1168 void ScheduleDAGRRList::ListScheduleTopDown() {
1169 unsigned CurCycle = 0;
1171 // All leaves to Available queue.
1172 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1173 // It is available if it has no predecessors.
1174 if (SUnits[i].Preds.empty()) {
1175 AvailableQueue->push(&SUnits[i]);
1176 SUnits[i].isAvailable = true;
1180 // While Available queue is not empty, grab the node with the highest
1181 // priority. If it is not ready put it back. Schedule the node.
1182 std::vector<SUnit*> NotReady;
1183 Sequence.reserve(SUnits.size());
1184 while (!AvailableQueue->empty()) {
1185 SUnit *CurSU = AvailableQueue->pop();
1186 while (CurSU && CurSU->CycleBound > CurCycle) {
1187 NotReady.push_back(CurSU);
1188 CurSU = AvailableQueue->pop();
1191 // Add the nodes that aren't ready back onto the available list.
1192 AvailableQueue->push_all(NotReady);
1196 Sequence.push_back(0);
1198 ScheduleNodeTopDown(CurSU, CurCycle);
1199 Sequence.push_back(CurSU);
1206 // Verify that all SUnits were scheduled.
1207 bool AnyNotSched = false;
1208 unsigned DeadNodes = 0;
1210 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1211 if (!SUnits[i].isScheduled) {
1212 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1217 cerr << "*** List scheduling failed! ***\n";
1218 SUnits[i].dump(&DAG);
1219 cerr << "has not been scheduled!\n";
1222 if (SUnits[i].NumPredsLeft != 0) {
1224 cerr << "*** List scheduling failed! ***\n";
1225 SUnits[i].dump(&DAG);
1226 cerr << "has predecessors left!\n";
1230 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1233 assert(!AnyNotSched);
1234 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1235 "The number of nodes scheduled doesn't match the expected number!");
1241 //===----------------------------------------------------------------------===//
1242 // RegReductionPriorityQueue Implementation
1243 //===----------------------------------------------------------------------===//
1245 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1246 // to reduce register pressure.
1250 class RegReductionPriorityQueue;
1252 /// Sorting functions for the Available queue.
1253 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1254 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1255 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1256 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1258 bool operator()(const SUnit* left, const SUnit* right) const;
1261 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1262 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1263 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1264 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1266 bool operator()(const SUnit* left, const SUnit* right) const;
1268 } // end anonymous namespace
1270 static inline bool isCopyFromLiveIn(const SUnit *SU) {
1271 SDNode *N = SU->Node;
1272 return N && N->getOpcode() == ISD::CopyFromReg &&
1273 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1278 class VISIBILITY_HIDDEN RegReductionPriorityQueue
1279 : public SchedulingPriorityQueue {
1280 PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
1281 unsigned currentQueueId;
1284 RegReductionPriorityQueue() :
1285 Queue(SF(this)), currentQueueId(0) {}
1287 virtual void initNodes(DenseMap<SDNode*, SUnit*> &sumap,
1288 std::vector<SUnit> &sunits) {}
1290 virtual void addNode(const SUnit *SU) {}
1292 virtual void updateNode(const SUnit *SU) {}
1294 virtual void releaseState() {}
1296 virtual unsigned getNodePriority(const SUnit *SU) const {
1300 unsigned size() const { return Queue.size(); }
1302 bool empty() const { return Queue.empty(); }
1304 void push(SUnit *U) {
1305 assert(!U->NodeQueueId && "Node in the queue already");
1306 U->NodeQueueId = ++currentQueueId;
1310 void push_all(const std::vector<SUnit *> &Nodes) {
1311 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1316 if (empty()) return NULL;
1317 SUnit *V = Queue.top();
1323 void remove(SUnit *SU) {
1324 assert(!Queue.empty() && "Queue is empty!");
1325 assert(SU->NodeQueueId != 0 && "Not in queue!");
1326 Queue.erase_one(SU);
1327 SU->NodeQueueId = 0;
1331 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1332 : public RegReductionPriorityQueue<bu_ls_rr_sort> {
1333 // SUnitMap SDNode to SUnit mapping (n -> n).
1334 DenseMap<SDNode*, SUnit*> *SUnitMap;
1336 // SUnits - The SUnits for the current graph.
1337 const std::vector<SUnit> *SUnits;
1339 // SethiUllmanNumbers - The SethiUllman number for each node.
1340 std::vector<unsigned> SethiUllmanNumbers;
1342 const TargetInstrInfo *TII;
1343 const TargetRegisterInfo *TRI;
1344 ScheduleDAGRRList *scheduleDAG;
1346 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii,
1347 const TargetRegisterInfo *tri)
1348 : TII(tii), TRI(tri), scheduleDAG(NULL) {}
1350 void initNodes(DenseMap<SDNode*, SUnit*> &sumap,
1351 std::vector<SUnit> &sunits) {
1354 // Add pseudo dependency edges for two-address nodes.
1355 AddPseudoTwoAddrDeps();
1356 // Calculate node priorities.
1357 CalculateSethiUllmanNumbers();
1360 void addNode(const SUnit *SU) {
1361 SethiUllmanNumbers.resize(SUnits->size(), 0);
1362 CalcNodeSethiUllmanNumber(SU);
1365 void updateNode(const SUnit *SU) {
1366 SethiUllmanNumbers[SU->NodeNum] = 0;
1367 CalcNodeSethiUllmanNumber(SU);
1370 void releaseState() {
1372 SethiUllmanNumbers.clear();
1375 unsigned getNodePriority(const SUnit *SU) const {
1376 assert(SU->NodeNum < SethiUllmanNumbers.size());
1377 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1378 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1379 // CopyFromReg should be close to its def because it restricts
1380 // allocation choices. But if it is a livein then perhaps we want it
1381 // closer to its uses so it can be coalesced.
1383 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1384 // CopyToReg should be close to its uses to facilitate coalescing and
1387 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1388 Opc == TargetInstrInfo::INSERT_SUBREG)
1389 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1390 // facilitate coalescing.
1392 else if (SU->NumSuccs == 0)
1393 // If SU does not have a use, i.e. it doesn't produce a value that would
1394 // be consumed (e.g. store), then it terminates a chain of computation.
1395 // Give it a large SethiUllman number so it will be scheduled right
1396 // before its predecessors that it doesn't lengthen their live ranges.
1398 else if (SU->NumPreds == 0)
1399 // If SU does not have a def, schedule it close to its uses because it
1400 // does not lengthen any live ranges.
1403 return SethiUllmanNumbers[SU->NodeNum];
1406 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1407 scheduleDAG = scheduleDag;
1411 bool canClobber(const SUnit *SU, const SUnit *Op);
1412 void AddPseudoTwoAddrDeps();
1413 void CalculateSethiUllmanNumbers();
1414 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1418 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1419 : public RegReductionPriorityQueue<td_ls_rr_sort> {
1420 // SUnitMap SDNode to SUnit mapping (n -> n).
1421 DenseMap<SDNode*, SUnit*> *SUnitMap;
1423 // SUnits - The SUnits for the current graph.
1424 const std::vector<SUnit> *SUnits;
1426 // SethiUllmanNumbers - The SethiUllman number for each node.
1427 std::vector<unsigned> SethiUllmanNumbers;
1430 TDRegReductionPriorityQueue() {}
1432 void initNodes(DenseMap<SDNode*, SUnit*> &sumap,
1433 std::vector<SUnit> &sunits) {
1436 // Calculate node priorities.
1437 CalculateSethiUllmanNumbers();
1440 void addNode(const SUnit *SU) {
1441 SethiUllmanNumbers.resize(SUnits->size(), 0);
1442 CalcNodeSethiUllmanNumber(SU);
1445 void updateNode(const SUnit *SU) {
1446 SethiUllmanNumbers[SU->NodeNum] = 0;
1447 CalcNodeSethiUllmanNumber(SU);
1450 void releaseState() {
1452 SethiUllmanNumbers.clear();
1455 unsigned getNodePriority(const SUnit *SU) const {
1456 assert(SU->NodeNum < SethiUllmanNumbers.size());
1457 return SethiUllmanNumbers[SU->NodeNum];
1461 void CalculateSethiUllmanNumbers();
1462 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1466 /// closestSucc - Returns the scheduled cycle of the successor which is
1467 /// closet to the current cycle.
1468 static unsigned closestSucc(const SUnit *SU) {
1469 unsigned MaxCycle = 0;
1470 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1472 unsigned Cycle = I->Dep->Cycle;
1473 // If there are bunch of CopyToRegs stacked up, they should be considered
1474 // to be at the same position.
1475 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
1476 Cycle = closestSucc(I->Dep)+1;
1477 if (Cycle > MaxCycle)
1483 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1484 /// for scratch registers. Live-in operands and live-out results don't count
1485 /// since they are "fixed".
1486 static unsigned calcMaxScratches(const SUnit *SU) {
1487 unsigned Scratches = 0;
1488 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1490 if (I->isCtrl) continue; // ignore chain preds
1491 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyFromReg)
1494 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1496 if (I->isCtrl) continue; // ignore chain succs
1497 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyToReg)
1504 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1506 unsigned LPriority = SPQ->getNodePriority(left);
1507 unsigned RPriority = SPQ->getNodePriority(right);
1508 if (LPriority != RPriority)
1509 return LPriority > RPriority;
1511 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1516 // and the following instructions are both ready.
1520 // Then schedule t2 = op first.
1527 // This creates more short live intervals.
1528 unsigned LDist = closestSucc(left);
1529 unsigned RDist = closestSucc(right);
1531 return LDist < RDist;
1533 // Intuitively, it's good to push down instructions whose results are
1534 // liveout so their long live ranges won't conflict with other values
1535 // which are needed inside the BB. Further prioritize liveout instructions
1536 // by the number of operands which are calculated within the BB.
1537 unsigned LScratch = calcMaxScratches(left);
1538 unsigned RScratch = calcMaxScratches(right);
1539 if (LScratch != RScratch)
1540 return LScratch > RScratch;
1542 if (left->Height != right->Height)
1543 return left->Height > right->Height;
1545 if (left->Depth != right->Depth)
1546 return left->Depth < right->Depth;
1548 if (left->CycleBound != right->CycleBound)
1549 return left->CycleBound > right->CycleBound;
1551 assert(left->NodeQueueId && right->NodeQueueId &&
1552 "NodeQueueId cannot be zero");
1553 return (left->NodeQueueId > right->NodeQueueId);
1557 BURegReductionPriorityQueue::canClobber(const SUnit *SU, const SUnit *Op) {
1558 if (SU->isTwoAddress) {
1559 unsigned Opc = SU->Node->getTargetOpcode();
1560 const TargetInstrDesc &TID = TII->get(Opc);
1561 unsigned NumRes = TID.getNumDefs();
1562 unsigned NumOps = TID.getNumOperands() - NumRes;
1563 for (unsigned i = 0; i != NumOps; ++i) {
1564 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1565 SDNode *DU = SU->Node->getOperand(i).Val;
1566 if ((*SUnitMap).find(DU) != (*SUnitMap).end() &&
1567 Op->OrigNode == (*SUnitMap)[DU])
1576 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1578 static bool hasCopyToRegUse(SUnit *SU) {
1579 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1581 if (I->isCtrl) continue;
1582 SUnit *SuccSU = I->Dep;
1583 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1589 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1590 /// physical register def.
1591 static bool canClobberPhysRegDefs(SUnit *SuccSU, SUnit *SU,
1592 const TargetInstrInfo *TII,
1593 const TargetRegisterInfo *TRI) {
1594 SDNode *N = SuccSU->Node;
1595 unsigned NumDefs = TII->get(N->getTargetOpcode()).getNumDefs();
1596 const unsigned *ImpDefs = TII->get(N->getTargetOpcode()).getImplicitDefs();
1599 const unsigned *SUImpDefs =
1600 TII->get(SU->Node->getTargetOpcode()).getImplicitDefs();
1603 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1604 MVT VT = N->getValueType(i);
1605 if (VT == MVT::Flag || VT == MVT::Other)
1607 unsigned Reg = ImpDefs[i - NumDefs];
1608 for (;*SUImpDefs; ++SUImpDefs) {
1609 unsigned SUReg = *SUImpDefs;
1610 if (TRI->regsOverlap(Reg, SUReg))
1617 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1618 /// it as a def&use operand. Add a pseudo control edge from it to the other
1619 /// node (if it won't create a cycle) so the two-address one will be scheduled
1620 /// first (lower in the schedule). If both nodes are two-address, favor the
1621 /// one that has a CopyToReg use (more likely to be a loop induction update).
1622 /// If both are two-address, but one is commutable while the other is not
1623 /// commutable, favor the one that's not commutable.
1624 void BURegReductionPriorityQueue::AddPseudoTwoAddrDeps() {
1625 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1626 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1627 if (!SU->isTwoAddress)
1630 SDNode *Node = SU->Node;
1631 if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
1634 unsigned Opc = Node->getTargetOpcode();
1635 const TargetInstrDesc &TID = TII->get(Opc);
1636 unsigned NumRes = TID.getNumDefs();
1637 unsigned NumOps = TID.getNumOperands() - NumRes;
1638 for (unsigned j = 0; j != NumOps; ++j) {
1639 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) != -1) {
1640 SDNode *DU = SU->Node->getOperand(j).Val;
1641 if ((*SUnitMap).find(DU) == (*SUnitMap).end())
1643 SUnit *DUSU = (*SUnitMap)[DU];
1644 if (!DUSU) continue;
1645 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
1647 if (I->isCtrl) continue;
1648 SUnit *SuccSU = I->Dep;
1651 // Be conservative. Ignore if nodes aren't at roughly the same
1652 // depth and height.
1653 if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1655 if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1657 // Don't constrain nodes with physical register defs if the
1658 // predecessor can clobber them.
1659 if (SuccSU->hasPhysRegDefs) {
1660 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1663 // Don't constraint extract_subreg / insert_subreg these may be
1664 // coalesced away. We don't them close to their uses.
1665 unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1666 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1667 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1669 if ((!canClobber(SuccSU, DUSU) ||
1670 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1671 (!SU->isCommutable && SuccSU->isCommutable)) &&
1672 !scheduleDAG->IsReachable(SuccSU, SU)) {
1673 DOUT << "Adding an edge from SU # " << SU->NodeNum
1674 << " to SU #" << SuccSU->NodeNum << "\n";
1675 scheduleDAG->AddPred(SU, SuccSU, true, true);
1683 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
1684 /// Smaller number is the higher priority.
1685 unsigned BURegReductionPriorityQueue::
1686 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1687 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1688 if (SethiUllmanNumber != 0)
1689 return SethiUllmanNumber;
1692 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1694 if (I->isCtrl) continue; // ignore chain preds
1695 SUnit *PredSU = I->Dep;
1696 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1697 if (PredSethiUllman > SethiUllmanNumber) {
1698 SethiUllmanNumber = PredSethiUllman;
1700 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1704 SethiUllmanNumber += Extra;
1706 if (SethiUllmanNumber == 0)
1707 SethiUllmanNumber = 1;
1709 return SethiUllmanNumber;
1712 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1713 /// scheduling units.
1714 void BURegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1715 SethiUllmanNumbers.assign(SUnits->size(), 0);
1717 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1718 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1721 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1722 /// predecessors of the successors of the SUnit SU. Stop when the provided
1723 /// limit is exceeded.
1724 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
1727 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1729 SUnit *SuccSU = I->Dep;
1730 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1731 EE = SuccSU->Preds.end(); II != EE; ++II) {
1732 SUnit *PredSU = II->Dep;
1733 if (!PredSU->isScheduled)
1743 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1744 unsigned LPriority = SPQ->getNodePriority(left);
1745 unsigned RPriority = SPQ->getNodePriority(right);
1746 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1747 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
1748 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1749 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1750 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1751 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1753 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1755 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1762 if (left->NumSuccs == 1)
1764 if (right->NumSuccs == 1)
1767 if (LPriority+LBonus != RPriority+RBonus)
1768 return LPriority+LBonus < RPriority+RBonus;
1770 if (left->Depth != right->Depth)
1771 return left->Depth < right->Depth;
1773 if (left->NumSuccsLeft != right->NumSuccsLeft)
1774 return left->NumSuccsLeft > right->NumSuccsLeft;
1776 if (left->CycleBound != right->CycleBound)
1777 return left->CycleBound > right->CycleBound;
1779 assert(left->NodeQueueId && right->NodeQueueId &&
1780 "NodeQueueId cannot be zero");
1781 return (left->NodeQueueId > right->NodeQueueId);
1784 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
1785 /// Smaller number is the higher priority.
1786 unsigned TDRegReductionPriorityQueue::
1787 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1788 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1789 if (SethiUllmanNumber != 0)
1790 return SethiUllmanNumber;
1792 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1793 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1794 SethiUllmanNumber = 0xffff;
1795 else if (SU->NumSuccsLeft == 0)
1796 // If SU does not have a use, i.e. it doesn't produce a value that would
1797 // be consumed (e.g. store), then it terminates a chain of computation.
1798 // Give it a small SethiUllman number so it will be scheduled right before
1799 // its predecessors that it doesn't lengthen their live ranges.
1800 SethiUllmanNumber = 0;
1801 else if (SU->NumPredsLeft == 0 &&
1802 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1803 SethiUllmanNumber = 0xffff;
1806 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1808 if (I->isCtrl) continue; // ignore chain preds
1809 SUnit *PredSU = I->Dep;
1810 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1811 if (PredSethiUllman > SethiUllmanNumber) {
1812 SethiUllmanNumber = PredSethiUllman;
1814 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1818 SethiUllmanNumber += Extra;
1821 return SethiUllmanNumber;
1824 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1825 /// scheduling units.
1826 void TDRegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1827 SethiUllmanNumbers.assign(SUnits->size(), 0);
1829 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1830 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1833 //===----------------------------------------------------------------------===//
1834 // Public Constructor Functions
1835 //===----------------------------------------------------------------------===//
1837 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1839 MachineBasicBlock *BB) {
1840 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
1841 const TargetRegisterInfo *TRI = DAG->getTarget().getRegisterInfo();
1843 BURegReductionPriorityQueue *priorityQueue =
1844 new BURegReductionPriorityQueue(TII, TRI);
1846 ScheduleDAGRRList * scheduleDAG =
1847 new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true, priorityQueue);
1848 priorityQueue->setScheduleDAG(scheduleDAG);
1852 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1854 MachineBasicBlock *BB) {
1855 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
1856 new TDRegReductionPriorityQueue());