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 SmallVector<SUnit*, 8> WorkList;
123 WorkList.push_back(this);
124 while (!WorkList.empty()) {
125 SUnit *SU = WorkList.back();
127 if (!SU->isDepthCurrent) continue;
128 SU->isDepthCurrent = false;
129 for (SUnit::const_succ_iterator I = Succs.begin(),
130 E = Succs.end(); I != E; ++I)
131 WorkList.push_back(I->getSUnit());
135 void SUnit::setHeightDirty() {
136 SmallVector<SUnit*, 8> WorkList;
137 WorkList.push_back(this);
138 while (!WorkList.empty()) {
139 SUnit *SU = WorkList.back();
141 if (!SU->isHeightCurrent) continue;
142 SU->isHeightCurrent = false;
143 for (SUnit::const_pred_iterator I = Preds.begin(),
144 E = Preds.end(); I != E; ++I)
145 WorkList.push_back(I->getSUnit());
149 /// setDepthToAtLeast - Update this node's successors to reflect the
150 /// fact that this node's depth just increased.
152 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
153 if (NewDepth <= getDepth())
157 isDepthCurrent = true;
160 /// setHeightToAtLeast - Update this node's predecessors to reflect the
161 /// fact that this node's height just increased.
163 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
164 if (NewHeight <= getHeight())
168 isHeightCurrent = true;
171 /// ComputeDepth - Calculate the maximal path from the node to the exit.
173 void SUnit::ComputeDepth() {
174 SmallVector<SUnit*, 8> WorkList;
175 WorkList.push_back(this);
176 while (!WorkList.empty()) {
177 SUnit *Cur = WorkList.back();
180 unsigned MaxPredDepth = 0;
181 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
182 E = Cur->Preds.end(); I != E; ++I) {
183 SUnit *PredSU = I->getSUnit();
184 if (PredSU->isDepthCurrent)
185 MaxPredDepth = std::max(MaxPredDepth,
186 PredSU->Depth + I->getLatency());
189 WorkList.push_back(PredSU);
195 if (MaxPredDepth != Cur->Depth) {
196 Cur->setDepthDirty();
197 Cur->Depth = MaxPredDepth;
199 Cur->isDepthCurrent = true;
204 /// ComputeHeight - Calculate the maximal path from the node to the entry.
206 void SUnit::ComputeHeight() {
207 SmallVector<SUnit*, 8> WorkList;
208 WorkList.push_back(this);
209 while (!WorkList.empty()) {
210 SUnit *Cur = WorkList.back();
213 unsigned MaxSuccHeight = 0;
214 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
215 E = Cur->Succs.end(); I != E; ++I) {
216 SUnit *SuccSU = I->getSUnit();
217 if (SuccSU->isHeightCurrent)
218 MaxSuccHeight = std::max(MaxSuccHeight,
219 SuccSU->Height + I->getLatency());
222 WorkList.push_back(SuccSU);
228 if (MaxSuccHeight != Cur->Height) {
229 Cur->setHeightDirty();
230 Cur->Height = MaxSuccHeight;
232 Cur->isHeightCurrent = true;
237 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
238 /// a group of nodes flagged together.
239 void SUnit::dump(const ScheduleDAG *G) const {
240 cerr << "SU(" << NodeNum << "): ";
244 void SUnit::dumpAll(const ScheduleDAG *G) const {
247 cerr << " # preds left : " << NumPredsLeft << "\n";
248 cerr << " # succs left : " << NumSuccsLeft << "\n";
249 cerr << " Latency : " << Latency << "\n";
250 cerr << " Depth : " << Depth << "\n";
251 cerr << " Height : " << Height << "\n";
253 if (Preds.size() != 0) {
254 cerr << " Predecessors:\n";
255 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
258 switch (I->getKind()) {
259 case SDep::Data: cerr << "val "; break;
260 case SDep::Anti: cerr << "anti"; break;
261 case SDep::Output: cerr << "out "; break;
262 case SDep::Order: cerr << "ch "; break;
265 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
266 if (I->isArtificial())
271 if (Succs.size() != 0) {
272 cerr << " Successors:\n";
273 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
276 switch (I->getKind()) {
277 case SDep::Data: cerr << "val "; break;
278 case SDep::Anti: cerr << "anti"; break;
279 case SDep::Output: cerr << "out "; break;
280 case SDep::Order: cerr << "ch "; break;
283 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
284 if (I->isArtificial())
293 /// VerifySchedule - Verify that all SUnits were scheduled and that
294 /// their state is consistent.
296 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
297 bool AnyNotSched = false;
298 unsigned DeadNodes = 0;
300 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
301 if (!SUnits[i].isScheduled) {
302 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
307 cerr << "*** Scheduling failed! ***\n";
308 SUnits[i].dump(this);
309 cerr << "has not been scheduled!\n";
312 if (SUnits[i].isScheduled &&
313 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
316 cerr << "*** Scheduling failed! ***\n";
317 SUnits[i].dump(this);
318 cerr << "has an unexpected "
319 << (isBottomUp ? "Height" : "Depth") << " value!\n";
323 if (SUnits[i].NumSuccsLeft != 0) {
325 cerr << "*** Scheduling failed! ***\n";
326 SUnits[i].dump(this);
327 cerr << "has successors left!\n";
331 if (SUnits[i].NumPredsLeft != 0) {
333 cerr << "*** Scheduling failed! ***\n";
334 SUnits[i].dump(this);
335 cerr << "has predecessors left!\n";
340 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
343 assert(!AnyNotSched);
344 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
345 "The number of nodes scheduled doesn't match the expected number!");
349 /// InitDAGTopologicalSorting - create the initial topological
350 /// ordering from the DAG to be scheduled.
352 /// The idea of the algorithm is taken from
353 /// "Online algorithms for managing the topological order of
354 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
355 /// This is the MNR algorithm, which was first introduced by
356 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
357 /// "Maintaining a topological order under edge insertions".
359 /// Short description of the algorithm:
361 /// Topological ordering, ord, of a DAG maps each node to a topological
362 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
364 /// This means that if there is a path from the node X to the node Z,
365 /// then ord(X) < ord(Z).
367 /// This property can be used to check for reachability of nodes:
368 /// if Z is reachable from X, then an insertion of the edge Z->X would
371 /// The algorithm first computes a topological ordering for the DAG by
372 /// initializing the Index2Node and Node2Index arrays and then tries to keep
373 /// the ordering up-to-date after edge insertions by reordering the DAG.
375 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
376 /// the nodes reachable from Y, and then shifts them using Shift to lie
377 /// immediately after X in Index2Node.
378 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
379 unsigned DAGSize = SUnits.size();
380 std::vector<SUnit*> WorkList;
381 WorkList.reserve(DAGSize);
383 Index2Node.resize(DAGSize);
384 Node2Index.resize(DAGSize);
386 // Initialize the data structures.
387 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
388 SUnit *SU = &SUnits[i];
389 int NodeNum = SU->NodeNum;
390 unsigned Degree = SU->Succs.size();
391 // Temporarily use the Node2Index array as scratch space for degree counts.
392 Node2Index[NodeNum] = Degree;
394 // Is it a node without dependencies?
396 assert(SU->Succs.empty() && "SUnit should have no successors");
397 // Collect leaf nodes.
398 WorkList.push_back(SU);
403 while (!WorkList.empty()) {
404 SUnit *SU = WorkList.back();
406 Allocate(SU->NodeNum, --Id);
407 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
409 SUnit *SU = I->getSUnit();
410 if (!--Node2Index[SU->NodeNum])
411 // If all dependencies of the node are processed already,
412 // then the node can be computed now.
413 WorkList.push_back(SU);
417 Visited.resize(DAGSize);
420 // Check correctness of the ordering
421 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
422 SUnit *SU = &SUnits[i];
423 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
425 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
426 "Wrong topological sorting");
432 /// AddPred - Updates the topological ordering to accomodate an edge
433 /// to be added from SUnit X to SUnit Y.
434 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
435 int UpperBound, LowerBound;
436 LowerBound = Node2Index[Y->NodeNum];
437 UpperBound = Node2Index[X->NodeNum];
438 bool HasLoop = false;
439 // Is Ord(X) < Ord(Y) ?
440 if (LowerBound < UpperBound) {
441 // Update the topological order.
443 DFS(Y, UpperBound, HasLoop);
444 assert(!HasLoop && "Inserted edge creates a loop!");
445 // Recompute topological indexes.
446 Shift(Visited, LowerBound, UpperBound);
450 /// RemovePred - Updates the topological ordering to accomodate an
451 /// an edge to be removed from the specified node N from the predecessors
452 /// of the current node M.
453 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
454 // InitDAGTopologicalSorting();
457 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
458 /// all nodes affected by the edge insertion. These nodes will later get new
459 /// topological indexes by means of the Shift method.
460 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
462 std::vector<const SUnit*> WorkList;
463 WorkList.reserve(SUnits.size());
465 WorkList.push_back(SU);
466 while (!WorkList.empty()) {
467 SU = WorkList.back();
469 Visited.set(SU->NodeNum);
470 for (int I = SU->Succs.size()-1; I >= 0; --I) {
471 int s = SU->Succs[I].getSUnit()->NodeNum;
472 if (Node2Index[s] == UpperBound) {
476 // Visit successors if not already and in affected region.
477 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
478 WorkList.push_back(SU->Succs[I].getSUnit());
484 /// Shift - Renumber the nodes so that the topological ordering is
486 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
492 for (i = LowerBound; i <= UpperBound; ++i) {
493 // w is node at topological index i.
494 int w = Index2Node[i];
495 if (Visited.test(w)) {
501 Allocate(w, i - shift);
505 for (unsigned j = 0; j < L.size(); ++j) {
506 Allocate(L[j], i - shift);
512 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
514 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
515 if (IsReachable(TargetSU, SU))
517 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
519 if (I->isAssignedRegDep() &&
520 IsReachable(TargetSU, I->getSUnit()))
525 /// IsReachable - Checks if SU is reachable from TargetSU.
526 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
527 const SUnit *TargetSU) {
528 // If insertion of the edge SU->TargetSU would create a cycle
529 // then there is a path from TargetSU to SU.
530 int UpperBound, LowerBound;
531 LowerBound = Node2Index[TargetSU->NodeNum];
532 UpperBound = Node2Index[SU->NodeNum];
533 bool HasLoop = false;
534 // Is Ord(TargetSU) < Ord(SU) ?
535 if (LowerBound < UpperBound) {
537 // There may be a path from TargetSU to SU. Check for it.
538 DFS(TargetSU, UpperBound, HasLoop);
543 /// Allocate - assign the topological index to the node n.
544 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
545 Node2Index[n] = index;
546 Index2Node[index] = n;
549 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
550 std::vector<SUnit> &sunits)