1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
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 the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
18 #include "llvm/CodeGen/SelectionDAGNodes.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
29 static cl::opt<bool> StressSchedOpt(
30 "stress-sched", cl::Hidden, cl::init(false),
31 cl::desc("Stress test instruction scheduling"));
34 void SchedulingPriorityQueue::anchor() { }
36 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
38 TII(TM.getInstrInfo()),
39 TRI(TM.getRegisterInfo()),
40 MF(mf), MRI(mf.getRegInfo()),
43 StressSched = StressSchedOpt;
47 ScheduleDAG::~ScheduleDAG() {}
49 /// Clear the DAG state (e.g. between scheduling regions).
50 void ScheduleDAG::clearDAG() {
56 /// getInstrDesc helper to handle SDNodes.
57 const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
58 if (!Node || !Node->isMachineOpcode()) return NULL;
59 return &TII->get(Node->getMachineOpcode());
62 /// addPred - This adds the specified edge as a pred of the current node if
63 /// not already. It also adds the current node as a successor of the
65 bool SUnit::addPred(const SDep &D) {
66 // If this node already has this depenence, don't add a redundant one.
67 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
71 // Now add a corresponding succ to N.
74 SUnit *N = D.getSUnit();
75 // Update the bookkeeping.
76 if (D.getKind() == SDep::Data) {
77 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
78 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
82 if (!N->isScheduled) {
83 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
87 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
91 N->Succs.push_back(P);
92 if (P.getLatency() != 0) {
93 this->setDepthDirty();
99 /// removePred - This removes the specified edge as a pred of the current
100 /// node if it exists. It also removes the current node as a successor of
101 /// the specified node.
102 void SUnit::removePred(const SDep &D) {
103 // Find the matching predecessor.
104 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
107 bool FoundSucc = false;
108 // Find the corresponding successor in N.
111 SUnit *N = D.getSUnit();
112 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
113 EE = N->Succs.end(); II != EE; ++II)
119 assert(FoundSucc && "Mismatching preds / succs lists!");
122 // Update the bookkeeping.
123 if (P.getKind() == SDep::Data) {
124 assert(NumPreds > 0 && "NumPreds will underflow!");
125 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
129 if (!N->isScheduled) {
130 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
134 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
137 if (P.getLatency() != 0) {
138 this->setDepthDirty();
145 void SUnit::setDepthDirty() {
146 if (!isDepthCurrent) return;
147 SmallVector<SUnit*, 8> WorkList;
148 WorkList.push_back(this);
150 SUnit *SU = WorkList.pop_back_val();
151 SU->isDepthCurrent = false;
152 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
153 E = SU->Succs.end(); I != E; ++I) {
154 SUnit *SuccSU = I->getSUnit();
155 if (SuccSU->isDepthCurrent)
156 WorkList.push_back(SuccSU);
158 } while (!WorkList.empty());
161 void SUnit::setHeightDirty() {
162 if (!isHeightCurrent) return;
163 SmallVector<SUnit*, 8> WorkList;
164 WorkList.push_back(this);
166 SUnit *SU = WorkList.pop_back_val();
167 SU->isHeightCurrent = false;
168 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
169 E = SU->Preds.end(); I != E; ++I) {
170 SUnit *PredSU = I->getSUnit();
171 if (PredSU->isHeightCurrent)
172 WorkList.push_back(PredSU);
174 } while (!WorkList.empty());
177 /// setDepthToAtLeast - Update this node's successors to reflect the
178 /// fact that this node's depth just increased.
180 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
181 if (NewDepth <= getDepth())
185 isDepthCurrent = true;
188 /// setHeightToAtLeast - Update this node's predecessors to reflect the
189 /// fact that this node's height just increased.
191 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
192 if (NewHeight <= getHeight())
196 isHeightCurrent = true;
199 /// ComputeDepth - Calculate the maximal path from the node to the exit.
201 void SUnit::ComputeDepth() {
202 SmallVector<SUnit*, 8> WorkList;
203 WorkList.push_back(this);
205 SUnit *Cur = WorkList.back();
208 unsigned MaxPredDepth = 0;
209 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
210 E = Cur->Preds.end(); I != E; ++I) {
211 SUnit *PredSU = I->getSUnit();
212 if (PredSU->isDepthCurrent)
213 MaxPredDepth = std::max(MaxPredDepth,
214 PredSU->Depth + I->getLatency());
217 WorkList.push_back(PredSU);
223 if (MaxPredDepth != Cur->Depth) {
224 Cur->setDepthDirty();
225 Cur->Depth = MaxPredDepth;
227 Cur->isDepthCurrent = true;
229 } while (!WorkList.empty());
232 /// ComputeHeight - Calculate the maximal path from the node to the entry.
234 void SUnit::ComputeHeight() {
235 SmallVector<SUnit*, 8> WorkList;
236 WorkList.push_back(this);
238 SUnit *Cur = WorkList.back();
241 unsigned MaxSuccHeight = 0;
242 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
243 E = Cur->Succs.end(); I != E; ++I) {
244 SUnit *SuccSU = I->getSUnit();
245 if (SuccSU->isHeightCurrent)
246 MaxSuccHeight = std::max(MaxSuccHeight,
247 SuccSU->Height + I->getLatency());
250 WorkList.push_back(SuccSU);
256 if (MaxSuccHeight != Cur->Height) {
257 Cur->setHeightDirty();
258 Cur->Height = MaxSuccHeight;
260 Cur->isHeightCurrent = true;
262 } while (!WorkList.empty());
265 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
266 /// a group of nodes flagged together.
267 void SUnit::dump(const ScheduleDAG *G) const {
268 dbgs() << "SU(" << NodeNum << "): ";
272 void SUnit::dumpAll(const ScheduleDAG *G) const {
275 dbgs() << " # preds left : " << NumPredsLeft << "\n";
276 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
277 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
278 dbgs() << " Latency : " << Latency << "\n";
279 dbgs() << " Depth : " << Depth << "\n";
280 dbgs() << " Height : " << Height << "\n";
282 if (Preds.size() != 0) {
283 dbgs() << " Predecessors:\n";
284 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
287 switch (I->getKind()) {
288 case SDep::Data: dbgs() << "val "; break;
289 case SDep::Anti: dbgs() << "anti"; break;
290 case SDep::Output: dbgs() << "out "; break;
291 case SDep::Order: dbgs() << "ch "; break;
293 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
294 if (I->isArtificial())
296 dbgs() << ": Latency=" << I->getLatency();
297 if (I->isAssignedRegDep())
298 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
302 if (Succs.size() != 0) {
303 dbgs() << " Successors:\n";
304 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
307 switch (I->getKind()) {
308 case SDep::Data: dbgs() << "val "; break;
309 case SDep::Anti: dbgs() << "anti"; break;
310 case SDep::Output: dbgs() << "out "; break;
311 case SDep::Order: dbgs() << "ch "; break;
313 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
314 if (I->isArtificial())
316 dbgs() << ": Latency=" << I->getLatency();
324 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
325 /// their state is consistent. Return the number of scheduled nodes.
327 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
328 bool AnyNotSched = false;
329 unsigned DeadNodes = 0;
330 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
331 if (!SUnits[i].isScheduled) {
332 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
337 dbgs() << "*** Scheduling failed! ***\n";
338 SUnits[i].dump(this);
339 dbgs() << "has not been scheduled!\n";
342 if (SUnits[i].isScheduled &&
343 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
346 dbgs() << "*** Scheduling failed! ***\n";
347 SUnits[i].dump(this);
348 dbgs() << "has an unexpected "
349 << (isBottomUp ? "Height" : "Depth") << " value!\n";
353 if (SUnits[i].NumSuccsLeft != 0) {
355 dbgs() << "*** Scheduling failed! ***\n";
356 SUnits[i].dump(this);
357 dbgs() << "has successors left!\n";
361 if (SUnits[i].NumPredsLeft != 0) {
363 dbgs() << "*** Scheduling failed! ***\n";
364 SUnits[i].dump(this);
365 dbgs() << "has predecessors left!\n";
370 assert(!AnyNotSched);
371 return SUnits.size() - DeadNodes;
375 /// InitDAGTopologicalSorting - create the initial topological
376 /// ordering from the DAG to be scheduled.
378 /// The idea of the algorithm is taken from
379 /// "Online algorithms for managing the topological order of
380 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
381 /// This is the MNR algorithm, which was first introduced by
382 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
383 /// "Maintaining a topological order under edge insertions".
385 /// Short description of the algorithm:
387 /// Topological ordering, ord, of a DAG maps each node to a topological
388 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
390 /// This means that if there is a path from the node X to the node Z,
391 /// then ord(X) < ord(Z).
393 /// This property can be used to check for reachability of nodes:
394 /// if Z is reachable from X, then an insertion of the edge Z->X would
397 /// The algorithm first computes a topological ordering for the DAG by
398 /// initializing the Index2Node and Node2Index arrays and then tries to keep
399 /// the ordering up-to-date after edge insertions by reordering the DAG.
401 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
402 /// the nodes reachable from Y, and then shifts them using Shift to lie
403 /// immediately after X in Index2Node.
404 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
405 unsigned DAGSize = SUnits.size();
406 std::vector<SUnit*> WorkList;
407 WorkList.reserve(DAGSize);
409 Index2Node.resize(DAGSize);
410 Node2Index.resize(DAGSize);
412 // Initialize the data structures.
413 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
414 SUnit *SU = &SUnits[i];
415 int NodeNum = SU->NodeNum;
416 unsigned Degree = SU->Succs.size();
417 // Temporarily use the Node2Index array as scratch space for degree counts.
418 Node2Index[NodeNum] = Degree;
420 // Is it a node without dependencies?
422 assert(SU->Succs.empty() && "SUnit should have no successors");
423 // Collect leaf nodes.
424 WorkList.push_back(SU);
429 while (!WorkList.empty()) {
430 SUnit *SU = WorkList.back();
432 Allocate(SU->NodeNum, --Id);
433 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
435 SUnit *SU = I->getSUnit();
436 if (!--Node2Index[SU->NodeNum])
437 // If all dependencies of the node are processed already,
438 // then the node can be computed now.
439 WorkList.push_back(SU);
443 Visited.resize(DAGSize);
446 // Check correctness of the ordering
447 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
448 SUnit *SU = &SUnits[i];
449 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
451 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
452 "Wrong topological sorting");
458 /// AddPred - Updates the topological ordering to accommodate an edge
459 /// to be added from SUnit X to SUnit Y.
460 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
461 int UpperBound, LowerBound;
462 LowerBound = Node2Index[Y->NodeNum];
463 UpperBound = Node2Index[X->NodeNum];
464 bool HasLoop = false;
465 // Is Ord(X) < Ord(Y) ?
466 if (LowerBound < UpperBound) {
467 // Update the topological order.
469 DFS(Y, UpperBound, HasLoop);
470 assert(!HasLoop && "Inserted edge creates a loop!");
471 // Recompute topological indexes.
472 Shift(Visited, LowerBound, UpperBound);
476 /// RemovePred - Updates the topological ordering to accommodate an
477 /// an edge to be removed from the specified node N from the predecessors
478 /// of the current node M.
479 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
480 // InitDAGTopologicalSorting();
483 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
484 /// all nodes affected by the edge insertion. These nodes will later get new
485 /// topological indexes by means of the Shift method.
486 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
488 std::vector<const SUnit*> WorkList;
489 WorkList.reserve(SUnits.size());
491 WorkList.push_back(SU);
493 SU = WorkList.back();
495 Visited.set(SU->NodeNum);
496 for (int I = SU->Succs.size()-1; I >= 0; --I) {
497 int s = SU->Succs[I].getSUnit()->NodeNum;
498 if (Node2Index[s] == UpperBound) {
502 // Visit successors if not already and in affected region.
503 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
504 WorkList.push_back(SU->Succs[I].getSUnit());
507 } while (!WorkList.empty());
510 /// Shift - Renumber the nodes so that the topological ordering is
512 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
518 for (i = LowerBound; i <= UpperBound; ++i) {
519 // w is node at topological index i.
520 int w = Index2Node[i];
521 if (Visited.test(w)) {
527 Allocate(w, i - shift);
531 for (unsigned j = 0; j < L.size(); ++j) {
532 Allocate(L[j], i - shift);
538 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
540 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
541 if (IsReachable(TargetSU, SU))
543 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
545 if (I->isAssignedRegDep() &&
546 IsReachable(TargetSU, I->getSUnit()))
551 /// IsReachable - Checks if SU is reachable from TargetSU.
552 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
553 const SUnit *TargetSU) {
554 // If insertion of the edge SU->TargetSU would create a cycle
555 // then there is a path from TargetSU to SU.
556 int UpperBound, LowerBound;
557 LowerBound = Node2Index[TargetSU->NodeNum];
558 UpperBound = Node2Index[SU->NodeNum];
559 bool HasLoop = false;
560 // Is Ord(TargetSU) < Ord(SU) ?
561 if (LowerBound < UpperBound) {
563 // There may be a path from TargetSU to SU. Check for it.
564 DFS(TargetSU, UpperBound, HasLoop);
569 /// Allocate - assign the topological index to the node n.
570 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
571 Node2Index[n] = index;
572 Index2Node[index] = n;
575 ScheduleDAGTopologicalSort::
576 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits) : SUnits(sunits) {}
578 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}