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/Target/TargetMachine.h"
18 #include "llvm/Target/TargetInstrInfo.h"
19 #include "llvm/Target/TargetRegisterInfo.h"
20 #include "llvm/Support/Debug.h"
24 ScheduleDAG::ScheduleDAG(SelectionDAG *dag, MachineBasicBlock *bb,
25 const TargetMachine &tm)
26 : DAG(dag), BB(bb), TM(tm), MRI(BB->getParent()->getRegInfo()) {
27 TII = TM.getInstrInfo();
29 TRI = TM.getRegisterInfo();
30 TLI = TM.getTargetLowering();
31 ConstPool = MF->getConstantPool();
34 ScheduleDAG::~ScheduleDAG() {}
36 /// dump - dump the schedule.
37 void ScheduleDAG::dumpSchedule() const {
38 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
39 if (SUnit *SU = Sequence[i])
42 cerr << "**** NOOP ****\n";
47 /// Run - perform scheduling.
49 void ScheduleDAG::Run() {
52 DOUT << "*** Final schedule ***\n";
53 DEBUG(dumpSchedule());
57 /// addPred - This adds the specified edge as a pred of the current node if
58 /// not already. It also adds the current node as a successor of the
60 void SUnit::addPred(const SDep &D) {
61 // If this node already has this depenence, don't add a redundant one.
62 for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
65 // Now add a corresponding succ to N.
68 SUnit *N = D.getSUnit();
69 // Update the bookkeeping.
70 if (D.getKind() == SDep::Data) {
78 N->Succs.push_back(P);
80 this->setDepthDirty();
84 /// removePred - This removes the specified edge as a pred of the current
85 /// node if it exists. It also removes the current node as a successor of
86 /// the specified node.
87 void SUnit::removePred(const SDep &D) {
88 // Find the matching predecessor.
89 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
92 bool FoundSucc = false;
93 // Find the corresponding successor in N.
96 SUnit *N = D.getSUnit();
97 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
98 EE = N->Succs.end(); II != EE; ++II)
104 assert(FoundSucc && "Mismatching preds / succs lists!");
106 // Update the bookkeeping;
107 if (D.getKind() == SDep::Data) {
115 this->setDepthDirty();
121 void SUnit::setDepthDirty() {
122 if (!isDepthCurrent) return;
123 SmallVector<SUnit*, 8> WorkList;
124 WorkList.push_back(this);
126 SUnit *SU = WorkList.pop_back_val();
127 SU->isDepthCurrent = false;
128 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
129 E = SU->Succs.end(); I != E; ++I) {
130 SUnit *SuccSU = I->getSUnit();
131 if (SuccSU->isDepthCurrent)
132 WorkList.push_back(SuccSU);
134 } while (!WorkList.empty());
137 void SUnit::setHeightDirty() {
138 if (!isHeightCurrent) return;
139 SmallVector<SUnit*, 8> WorkList;
140 WorkList.push_back(this);
142 SUnit *SU = WorkList.pop_back_val();
143 SU->isHeightCurrent = false;
144 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
145 E = SU->Preds.end(); I != E; ++I) {
146 SUnit *PredSU = I->getSUnit();
147 if (PredSU->isHeightCurrent)
148 WorkList.push_back(PredSU);
150 } while (!WorkList.empty());
153 /// setDepthToAtLeast - Update this node's successors to reflect the
154 /// fact that this node's depth just increased.
156 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
157 if (NewDepth <= getDepth())
161 isDepthCurrent = true;
164 /// setHeightToAtLeast - Update this node's predecessors to reflect the
165 /// fact that this node's height just increased.
167 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
168 if (NewHeight <= getHeight())
172 isHeightCurrent = true;
175 /// ComputeDepth - Calculate the maximal path from the node to the exit.
177 void SUnit::ComputeDepth() {
178 SmallVector<SUnit*, 8> WorkList;
179 WorkList.push_back(this);
181 SUnit *Cur = WorkList.back();
184 unsigned MaxPredDepth = 0;
185 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
186 E = Cur->Preds.end(); I != E; ++I) {
187 SUnit *PredSU = I->getSUnit();
188 if (PredSU->isDepthCurrent)
189 MaxPredDepth = std::max(MaxPredDepth,
190 PredSU->Depth + I->getLatency());
193 WorkList.push_back(PredSU);
199 if (MaxPredDepth != Cur->Depth) {
200 Cur->setDepthDirty();
201 Cur->Depth = MaxPredDepth;
203 Cur->isDepthCurrent = true;
205 } while (!WorkList.empty());
208 /// ComputeHeight - Calculate the maximal path from the node to the entry.
210 void SUnit::ComputeHeight() {
211 SmallVector<SUnit*, 8> WorkList;
212 WorkList.push_back(this);
214 SUnit *Cur = WorkList.back();
217 unsigned MaxSuccHeight = 0;
218 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
219 E = Cur->Succs.end(); I != E; ++I) {
220 SUnit *SuccSU = I->getSUnit();
221 if (SuccSU->isHeightCurrent)
222 MaxSuccHeight = std::max(MaxSuccHeight,
223 SuccSU->Height + I->getLatency());
226 WorkList.push_back(SuccSU);
232 if (MaxSuccHeight != Cur->Height) {
233 Cur->setHeightDirty();
234 Cur->Height = MaxSuccHeight;
236 Cur->isHeightCurrent = true;
238 } while (!WorkList.empty());
241 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
242 /// a group of nodes flagged together.
243 void SUnit::dump(const ScheduleDAG *G) const {
244 cerr << "SU(" << NodeNum << "): ";
248 void SUnit::dumpAll(const ScheduleDAG *G) const {
251 cerr << " # preds left : " << NumPredsLeft << "\n";
252 cerr << " # succs left : " << NumSuccsLeft << "\n";
253 cerr << " Latency : " << Latency << "\n";
254 cerr << " Depth : " << Depth << "\n";
255 cerr << " Height : " << Height << "\n";
257 if (Preds.size() != 0) {
258 cerr << " Predecessors:\n";
259 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
262 switch (I->getKind()) {
263 case SDep::Data: cerr << "val "; break;
264 case SDep::Anti: cerr << "anti"; break;
265 case SDep::Output: cerr << "out "; break;
266 case SDep::Order: cerr << "ch "; break;
269 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
270 if (I->isArtificial())
275 if (Succs.size() != 0) {
276 cerr << " Successors:\n";
277 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
280 switch (I->getKind()) {
281 case SDep::Data: cerr << "val "; break;
282 case SDep::Anti: cerr << "anti"; break;
283 case SDep::Output: cerr << "out "; break;
284 case SDep::Order: cerr << "ch "; break;
287 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
288 if (I->isArtificial())
297 /// VerifySchedule - Verify that all SUnits were scheduled and that
298 /// their state is consistent.
300 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
301 bool AnyNotSched = false;
302 unsigned DeadNodes = 0;
304 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
305 if (!SUnits[i].isScheduled) {
306 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
311 cerr << "*** Scheduling failed! ***\n";
312 SUnits[i].dump(this);
313 cerr << "has not been scheduled!\n";
316 if (SUnits[i].isScheduled &&
317 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
320 cerr << "*** Scheduling failed! ***\n";
321 SUnits[i].dump(this);
322 cerr << "has an unexpected "
323 << (isBottomUp ? "Height" : "Depth") << " value!\n";
327 if (SUnits[i].NumSuccsLeft != 0) {
329 cerr << "*** Scheduling failed! ***\n";
330 SUnits[i].dump(this);
331 cerr << "has successors left!\n";
335 if (SUnits[i].NumPredsLeft != 0) {
337 cerr << "*** Scheduling failed! ***\n";
338 SUnits[i].dump(this);
339 cerr << "has predecessors left!\n";
344 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
347 assert(!AnyNotSched);
348 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
349 "The number of nodes scheduled doesn't match the expected number!");
353 /// InitDAGTopologicalSorting - create the initial topological
354 /// ordering from the DAG to be scheduled.
356 /// The idea of the algorithm is taken from
357 /// "Online algorithms for managing the topological order of
358 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
359 /// This is the MNR algorithm, which was first introduced by
360 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
361 /// "Maintaining a topological order under edge insertions".
363 /// Short description of the algorithm:
365 /// Topological ordering, ord, of a DAG maps each node to a topological
366 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
368 /// This means that if there is a path from the node X to the node Z,
369 /// then ord(X) < ord(Z).
371 /// This property can be used to check for reachability of nodes:
372 /// if Z is reachable from X, then an insertion of the edge Z->X would
375 /// The algorithm first computes a topological ordering for the DAG by
376 /// initializing the Index2Node and Node2Index arrays and then tries to keep
377 /// the ordering up-to-date after edge insertions by reordering the DAG.
379 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
380 /// the nodes reachable from Y, and then shifts them using Shift to lie
381 /// immediately after X in Index2Node.
382 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
383 unsigned DAGSize = SUnits.size();
384 std::vector<SUnit*> WorkList;
385 WorkList.reserve(DAGSize);
387 Index2Node.resize(DAGSize);
388 Node2Index.resize(DAGSize);
390 // Initialize the data structures.
391 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
392 SUnit *SU = &SUnits[i];
393 int NodeNum = SU->NodeNum;
394 unsigned Degree = SU->Succs.size();
395 // Temporarily use the Node2Index array as scratch space for degree counts.
396 Node2Index[NodeNum] = Degree;
398 // Is it a node without dependencies?
400 assert(SU->Succs.empty() && "SUnit should have no successors");
401 // Collect leaf nodes.
402 WorkList.push_back(SU);
407 while (!WorkList.empty()) {
408 SUnit *SU = WorkList.back();
410 Allocate(SU->NodeNum, --Id);
411 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
413 SUnit *SU = I->getSUnit();
414 if (!--Node2Index[SU->NodeNum])
415 // If all dependencies of the node are processed already,
416 // then the node can be computed now.
417 WorkList.push_back(SU);
421 Visited.resize(DAGSize);
424 // Check correctness of the ordering
425 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
426 SUnit *SU = &SUnits[i];
427 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
429 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
430 "Wrong topological sorting");
436 /// AddPred - Updates the topological ordering to accomodate an edge
437 /// to be added from SUnit X to SUnit Y.
438 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
439 int UpperBound, LowerBound;
440 LowerBound = Node2Index[Y->NodeNum];
441 UpperBound = Node2Index[X->NodeNum];
442 bool HasLoop = false;
443 // Is Ord(X) < Ord(Y) ?
444 if (LowerBound < UpperBound) {
445 // Update the topological order.
447 DFS(Y, UpperBound, HasLoop);
448 assert(!HasLoop && "Inserted edge creates a loop!");
449 // Recompute topological indexes.
450 Shift(Visited, LowerBound, UpperBound);
454 /// RemovePred - Updates the topological ordering to accomodate an
455 /// an edge to be removed from the specified node N from the predecessors
456 /// of the current node M.
457 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
458 // InitDAGTopologicalSorting();
461 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
462 /// all nodes affected by the edge insertion. These nodes will later get new
463 /// topological indexes by means of the Shift method.
464 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
466 std::vector<const SUnit*> WorkList;
467 WorkList.reserve(SUnits.size());
469 WorkList.push_back(SU);
471 SU = WorkList.back();
473 Visited.set(SU->NodeNum);
474 for (int I = SU->Succs.size()-1; I >= 0; --I) {
475 int s = SU->Succs[I].getSUnit()->NodeNum;
476 if (Node2Index[s] == UpperBound) {
480 // Visit successors if not already and in affected region.
481 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
482 WorkList.push_back(SU->Succs[I].getSUnit());
485 } while (!WorkList.empty());
488 /// Shift - Renumber the nodes so that the topological ordering is
490 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
496 for (i = LowerBound; i <= UpperBound; ++i) {
497 // w is node at topological index i.
498 int w = Index2Node[i];
499 if (Visited.test(w)) {
505 Allocate(w, i - shift);
509 for (unsigned j = 0; j < L.size(); ++j) {
510 Allocate(L[j], i - shift);
516 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
518 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
519 if (IsReachable(TargetSU, SU))
521 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
523 if (I->isAssignedRegDep() &&
524 IsReachable(TargetSU, I->getSUnit()))
529 /// IsReachable - Checks if SU is reachable from TargetSU.
530 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
531 const SUnit *TargetSU) {
532 // If insertion of the edge SU->TargetSU would create a cycle
533 // then there is a path from TargetSU to SU.
534 int UpperBound, LowerBound;
535 LowerBound = Node2Index[TargetSU->NodeNum];
536 UpperBound = Node2Index[SU->NodeNum];
537 bool HasLoop = false;
538 // Is Ord(TargetSU) < Ord(SU) ?
539 if (LowerBound < UpperBound) {
541 // There may be a path from TargetSU to SU. Check for it.
542 DFS(TargetSU, UpperBound, HasLoop);
547 /// Allocate - assign the topological index to the node n.
548 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
549 Node2Index[n] = index;
550 Index2Node[index] = n;
553 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
554 std::vector<SUnit> &sunits)