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(MachineFunction &mf)
25 : DAG(0), BB(0), TM(mf.getTarget()),
26 TII(TM.getInstrInfo()),
27 TRI(TM.getRegisterInfo()),
28 TLI(TM.getTargetLowering()),
29 MF(mf), MRI(mf.getRegInfo()),
30 ConstPool(MF.getConstantPool()) {
33 ScheduleDAG::~ScheduleDAG() {}
35 /// dump - dump the schedule.
36 void ScheduleDAG::dumpSchedule() const {
37 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
38 if (SUnit *SU = Sequence[i])
41 cerr << "**** NOOP ****\n";
46 /// Run - perform scheduling.
48 void ScheduleDAG::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
56 DOUT << "*** Final schedule ***\n";
57 DEBUG(dumpSchedule());
61 /// addPred - This adds the specified edge as a pred of the current node if
62 /// not already. It also adds the current node as a successor of the
64 void SUnit::addPred(const SDep &D) {
65 // If this node already has this depenence, don't add a redundant one.
66 for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
69 // Now add a corresponding succ to N.
72 SUnit *N = D.getSUnit();
73 // Update the bookkeeping.
74 if (D.getKind() == SDep::Data) {
83 N->Succs.push_back(P);
84 if (P.getLatency() != 0) {
85 this->setDepthDirty();
90 /// removePred - This removes the specified edge as a pred of the current
91 /// node if it exists. It also removes the current node as a successor of
92 /// the specified node.
93 void SUnit::removePred(const SDep &D) {
94 // Find the matching predecessor.
95 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
98 bool FoundSucc = false;
99 // Find the corresponding successor in N.
102 SUnit *N = D.getSUnit();
103 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
104 EE = N->Succs.end(); II != EE; ++II)
110 assert(FoundSucc && "Mismatching preds / succs lists!");
112 // Update the bookkeeping.
113 if (P.getKind() == SDep::Data) {
121 if (P.getLatency() != 0) {
122 this->setDepthDirty();
129 void SUnit::setDepthDirty() {
130 if (!isDepthCurrent) return;
131 SmallVector<SUnit*, 8> WorkList;
132 WorkList.push_back(this);
134 SUnit *SU = WorkList.pop_back_val();
135 SU->isDepthCurrent = false;
136 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
137 E = SU->Succs.end(); I != E; ++I) {
138 SUnit *SuccSU = I->getSUnit();
139 if (SuccSU->isDepthCurrent)
140 WorkList.push_back(SuccSU);
142 } while (!WorkList.empty());
145 void SUnit::setHeightDirty() {
146 if (!isHeightCurrent) return;
147 SmallVector<SUnit*, 8> WorkList;
148 WorkList.push_back(this);
150 SUnit *SU = WorkList.pop_back_val();
151 SU->isHeightCurrent = false;
152 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
153 E = SU->Preds.end(); I != E; ++I) {
154 SUnit *PredSU = I->getSUnit();
155 if (PredSU->isHeightCurrent)
156 WorkList.push_back(PredSU);
158 } while (!WorkList.empty());
161 /// setDepthToAtLeast - Update this node's successors to reflect the
162 /// fact that this node's depth just increased.
164 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
165 if (NewDepth <= getDepth())
169 isDepthCurrent = true;
172 /// setHeightToAtLeast - Update this node's predecessors to reflect the
173 /// fact that this node's height just increased.
175 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
176 if (NewHeight <= getHeight())
180 isHeightCurrent = true;
183 /// ComputeDepth - Calculate the maximal path from the node to the exit.
185 void SUnit::ComputeDepth() {
186 SmallVector<SUnit*, 8> WorkList;
187 WorkList.push_back(this);
189 SUnit *Cur = WorkList.back();
192 unsigned MaxPredDepth = 0;
193 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
194 E = Cur->Preds.end(); I != E; ++I) {
195 SUnit *PredSU = I->getSUnit();
196 if (PredSU->isDepthCurrent)
197 MaxPredDepth = std::max(MaxPredDepth,
198 PredSU->Depth + I->getLatency());
201 WorkList.push_back(PredSU);
207 if (MaxPredDepth != Cur->Depth) {
208 Cur->setDepthDirty();
209 Cur->Depth = MaxPredDepth;
211 Cur->isDepthCurrent = true;
213 } while (!WorkList.empty());
216 /// ComputeHeight - Calculate the maximal path from the node to the entry.
218 void SUnit::ComputeHeight() {
219 SmallVector<SUnit*, 8> WorkList;
220 WorkList.push_back(this);
222 SUnit *Cur = WorkList.back();
225 unsigned MaxSuccHeight = 0;
226 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
227 E = Cur->Succs.end(); I != E; ++I) {
228 SUnit *SuccSU = I->getSUnit();
229 if (SuccSU->isHeightCurrent)
230 MaxSuccHeight = std::max(MaxSuccHeight,
231 SuccSU->Height + I->getLatency());
234 WorkList.push_back(SuccSU);
240 if (MaxSuccHeight != Cur->Height) {
241 Cur->setHeightDirty();
242 Cur->Height = MaxSuccHeight;
244 Cur->isHeightCurrent = true;
246 } while (!WorkList.empty());
249 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
250 /// a group of nodes flagged together.
251 void SUnit::dump(const ScheduleDAG *G) const {
252 cerr << "SU(" << NodeNum << "): ";
256 void SUnit::dumpAll(const ScheduleDAG *G) const {
259 cerr << " # preds left : " << NumPredsLeft << "\n";
260 cerr << " # succs left : " << NumSuccsLeft << "\n";
261 cerr << " Latency : " << Latency << "\n";
262 cerr << " Depth : " << Depth << "\n";
263 cerr << " Height : " << Height << "\n";
265 if (Preds.size() != 0) {
266 cerr << " Predecessors:\n";
267 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
270 switch (I->getKind()) {
271 case SDep::Data: cerr << "val "; break;
272 case SDep::Anti: cerr << "anti"; break;
273 case SDep::Output: cerr << "out "; break;
274 case SDep::Order: cerr << "ch "; break;
277 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
278 if (I->isArtificial())
283 if (Succs.size() != 0) {
284 cerr << " Successors:\n";
285 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
288 switch (I->getKind()) {
289 case SDep::Data: cerr << "val "; break;
290 case SDep::Anti: cerr << "anti"; break;
291 case SDep::Output: cerr << "out "; break;
292 case SDep::Order: cerr << "ch "; break;
295 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
296 if (I->isArtificial())
305 /// VerifySchedule - Verify that all SUnits were scheduled and that
306 /// their state is consistent.
308 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
309 bool AnyNotSched = false;
310 unsigned DeadNodes = 0;
312 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
313 if (!SUnits[i].isScheduled) {
314 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
319 cerr << "*** Scheduling failed! ***\n";
320 SUnits[i].dump(this);
321 cerr << "has not been scheduled!\n";
324 if (SUnits[i].isScheduled &&
325 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
328 cerr << "*** Scheduling failed! ***\n";
329 SUnits[i].dump(this);
330 cerr << "has an unexpected "
331 << (isBottomUp ? "Height" : "Depth") << " value!\n";
335 if (SUnits[i].NumSuccsLeft != 0) {
337 cerr << "*** Scheduling failed! ***\n";
338 SUnits[i].dump(this);
339 cerr << "has successors left!\n";
343 if (SUnits[i].NumPredsLeft != 0) {
345 cerr << "*** Scheduling failed! ***\n";
346 SUnits[i].dump(this);
347 cerr << "has predecessors left!\n";
352 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
355 assert(!AnyNotSched);
356 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
357 "The number of nodes scheduled doesn't match the expected number!");
361 /// InitDAGTopologicalSorting - create the initial topological
362 /// ordering from the DAG to be scheduled.
364 /// The idea of the algorithm is taken from
365 /// "Online algorithms for managing the topological order of
366 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
367 /// This is the MNR algorithm, which was first introduced by
368 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
369 /// "Maintaining a topological order under edge insertions".
371 /// Short description of the algorithm:
373 /// Topological ordering, ord, of a DAG maps each node to a topological
374 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
376 /// This means that if there is a path from the node X to the node Z,
377 /// then ord(X) < ord(Z).
379 /// This property can be used to check for reachability of nodes:
380 /// if Z is reachable from X, then an insertion of the edge Z->X would
383 /// The algorithm first computes a topological ordering for the DAG by
384 /// initializing the Index2Node and Node2Index arrays and then tries to keep
385 /// the ordering up-to-date after edge insertions by reordering the DAG.
387 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
388 /// the nodes reachable from Y, and then shifts them using Shift to lie
389 /// immediately after X in Index2Node.
390 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
391 unsigned DAGSize = SUnits.size();
392 std::vector<SUnit*> WorkList;
393 WorkList.reserve(DAGSize);
395 Index2Node.resize(DAGSize);
396 Node2Index.resize(DAGSize);
398 // Initialize the data structures.
399 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
400 SUnit *SU = &SUnits[i];
401 int NodeNum = SU->NodeNum;
402 unsigned Degree = SU->Succs.size();
403 // Temporarily use the Node2Index array as scratch space for degree counts.
404 Node2Index[NodeNum] = Degree;
406 // Is it a node without dependencies?
408 assert(SU->Succs.empty() && "SUnit should have no successors");
409 // Collect leaf nodes.
410 WorkList.push_back(SU);
415 while (!WorkList.empty()) {
416 SUnit *SU = WorkList.back();
418 Allocate(SU->NodeNum, --Id);
419 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
421 SUnit *SU = I->getSUnit();
422 if (!--Node2Index[SU->NodeNum])
423 // If all dependencies of the node are processed already,
424 // then the node can be computed now.
425 WorkList.push_back(SU);
429 Visited.resize(DAGSize);
432 // Check correctness of the ordering
433 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
434 SUnit *SU = &SUnits[i];
435 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
437 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
438 "Wrong topological sorting");
444 /// AddPred - Updates the topological ordering to accomodate an edge
445 /// to be added from SUnit X to SUnit Y.
446 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
447 int UpperBound, LowerBound;
448 LowerBound = Node2Index[Y->NodeNum];
449 UpperBound = Node2Index[X->NodeNum];
450 bool HasLoop = false;
451 // Is Ord(X) < Ord(Y) ?
452 if (LowerBound < UpperBound) {
453 // Update the topological order.
455 DFS(Y, UpperBound, HasLoop);
456 assert(!HasLoop && "Inserted edge creates a loop!");
457 // Recompute topological indexes.
458 Shift(Visited, LowerBound, UpperBound);
462 /// RemovePred - Updates the topological ordering to accomodate an
463 /// an edge to be removed from the specified node N from the predecessors
464 /// of the current node M.
465 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
466 // InitDAGTopologicalSorting();
469 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
470 /// all nodes affected by the edge insertion. These nodes will later get new
471 /// topological indexes by means of the Shift method.
472 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
474 std::vector<const SUnit*> WorkList;
475 WorkList.reserve(SUnits.size());
477 WorkList.push_back(SU);
479 SU = WorkList.back();
481 Visited.set(SU->NodeNum);
482 for (int I = SU->Succs.size()-1; I >= 0; --I) {
483 int s = SU->Succs[I].getSUnit()->NodeNum;
484 if (Node2Index[s] == UpperBound) {
488 // Visit successors if not already and in affected region.
489 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
490 WorkList.push_back(SU->Succs[I].getSUnit());
493 } while (!WorkList.empty());
496 /// Shift - Renumber the nodes so that the topological ordering is
498 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
504 for (i = LowerBound; i <= UpperBound; ++i) {
505 // w is node at topological index i.
506 int w = Index2Node[i];
507 if (Visited.test(w)) {
513 Allocate(w, i - shift);
517 for (unsigned j = 0; j < L.size(); ++j) {
518 Allocate(L[j], i - shift);
524 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
526 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
527 if (IsReachable(TargetSU, SU))
529 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
531 if (I->isAssignedRegDep() &&
532 IsReachable(TargetSU, I->getSUnit()))
537 /// IsReachable - Checks if SU is reachable from TargetSU.
538 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
539 const SUnit *TargetSU) {
540 // If insertion of the edge SU->TargetSU would create a cycle
541 // then there is a path from TargetSU to SU.
542 int UpperBound, LowerBound;
543 LowerBound = Node2Index[TargetSU->NodeNum];
544 UpperBound = Node2Index[SU->NodeNum];
545 bool HasLoop = false;
546 // Is Ord(TargetSU) < Ord(SU) ?
547 if (LowerBound < UpperBound) {
549 // There may be a path from TargetSU to SU. Check for it.
550 DFS(TargetSU, UpperBound, HasLoop);
555 /// Allocate - assign the topological index to the node n.
556 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
557 Node2Index[n] = index;
558 Index2Node[index] = n;
561 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
562 std::vector<SUnit> &sunits)