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.pop_back_val();
126 if (!SU->isDepthCurrent) continue;
127 SU->isDepthCurrent = false;
128 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
129 E = SU->Succs.end(); I != E; ++I)
130 WorkList.push_back(I->getSUnit());
134 void SUnit::setHeightDirty() {
135 SmallVector<SUnit*, 8> WorkList;
136 WorkList.push_back(this);
137 while (!WorkList.empty()) {
138 SUnit *SU = WorkList.pop_back_val();
139 if (!SU->isHeightCurrent) continue;
140 SU->isHeightCurrent = false;
141 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
142 E = SU->Preds.end(); I != E; ++I)
143 WorkList.push_back(I->getSUnit());
147 /// setDepthToAtLeast - Update this node's successors to reflect the
148 /// fact that this node's depth just increased.
150 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
151 if (NewDepth <= getDepth())
155 isDepthCurrent = true;
158 /// setHeightToAtLeast - Update this node's predecessors to reflect the
159 /// fact that this node's height just increased.
161 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
162 if (NewHeight <= getHeight())
166 isHeightCurrent = true;
169 /// ComputeDepth - Calculate the maximal path from the node to the exit.
171 void SUnit::ComputeDepth() {
172 SmallVector<SUnit*, 8> WorkList;
173 WorkList.push_back(this);
174 while (!WorkList.empty()) {
175 SUnit *Cur = WorkList.back();
178 unsigned MaxPredDepth = 0;
179 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
180 E = Cur->Preds.end(); I != E; ++I) {
181 SUnit *PredSU = I->getSUnit();
182 if (PredSU->isDepthCurrent)
183 MaxPredDepth = std::max(MaxPredDepth,
184 PredSU->Depth + I->getLatency());
187 WorkList.push_back(PredSU);
193 if (MaxPredDepth != Cur->Depth) {
194 Cur->setDepthDirty();
195 Cur->Depth = MaxPredDepth;
197 Cur->isDepthCurrent = true;
202 /// ComputeHeight - Calculate the maximal path from the node to the entry.
204 void SUnit::ComputeHeight() {
205 SmallVector<SUnit*, 8> WorkList;
206 WorkList.push_back(this);
207 while (!WorkList.empty()) {
208 SUnit *Cur = WorkList.back();
211 unsigned MaxSuccHeight = 0;
212 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
213 E = Cur->Succs.end(); I != E; ++I) {
214 SUnit *SuccSU = I->getSUnit();
215 if (SuccSU->isHeightCurrent)
216 MaxSuccHeight = std::max(MaxSuccHeight,
217 SuccSU->Height + I->getLatency());
220 WorkList.push_back(SuccSU);
226 if (MaxSuccHeight != Cur->Height) {
227 Cur->setHeightDirty();
228 Cur->Height = MaxSuccHeight;
230 Cur->isHeightCurrent = true;
235 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
236 /// a group of nodes flagged together.
237 void SUnit::dump(const ScheduleDAG *G) const {
238 cerr << "SU(" << NodeNum << "): ";
242 void SUnit::dumpAll(const ScheduleDAG *G) const {
245 cerr << " # preds left : " << NumPredsLeft << "\n";
246 cerr << " # succs left : " << NumSuccsLeft << "\n";
247 cerr << " Latency : " << Latency << "\n";
248 cerr << " Depth : " << Depth << "\n";
249 cerr << " Height : " << Height << "\n";
251 if (Preds.size() != 0) {
252 cerr << " Predecessors:\n";
253 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
256 switch (I->getKind()) {
257 case SDep::Data: cerr << "val "; break;
258 case SDep::Anti: cerr << "anti"; break;
259 case SDep::Output: cerr << "out "; break;
260 case SDep::Order: cerr << "ch "; break;
263 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
264 if (I->isArtificial())
269 if (Succs.size() != 0) {
270 cerr << " Successors:\n";
271 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
274 switch (I->getKind()) {
275 case SDep::Data: cerr << "val "; break;
276 case SDep::Anti: cerr << "anti"; break;
277 case SDep::Output: cerr << "out "; break;
278 case SDep::Order: cerr << "ch "; break;
281 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
282 if (I->isArtificial())
291 /// VerifySchedule - Verify that all SUnits were scheduled and that
292 /// their state is consistent.
294 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
295 bool AnyNotSched = false;
296 unsigned DeadNodes = 0;
298 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
299 if (!SUnits[i].isScheduled) {
300 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
305 cerr << "*** Scheduling failed! ***\n";
306 SUnits[i].dump(this);
307 cerr << "has not been scheduled!\n";
310 if (SUnits[i].isScheduled &&
311 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
314 cerr << "*** Scheduling failed! ***\n";
315 SUnits[i].dump(this);
316 cerr << "has an unexpected "
317 << (isBottomUp ? "Height" : "Depth") << " value!\n";
321 if (SUnits[i].NumSuccsLeft != 0) {
323 cerr << "*** Scheduling failed! ***\n";
324 SUnits[i].dump(this);
325 cerr << "has successors left!\n";
329 if (SUnits[i].NumPredsLeft != 0) {
331 cerr << "*** Scheduling failed! ***\n";
332 SUnits[i].dump(this);
333 cerr << "has predecessors left!\n";
338 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
341 assert(!AnyNotSched);
342 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
343 "The number of nodes scheduled doesn't match the expected number!");
347 /// InitDAGTopologicalSorting - create the initial topological
348 /// ordering from the DAG to be scheduled.
350 /// The idea of the algorithm is taken from
351 /// "Online algorithms for managing the topological order of
352 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
353 /// This is the MNR algorithm, which was first introduced by
354 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
355 /// "Maintaining a topological order under edge insertions".
357 /// Short description of the algorithm:
359 /// Topological ordering, ord, of a DAG maps each node to a topological
360 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
362 /// This means that if there is a path from the node X to the node Z,
363 /// then ord(X) < ord(Z).
365 /// This property can be used to check for reachability of nodes:
366 /// if Z is reachable from X, then an insertion of the edge Z->X would
369 /// The algorithm first computes a topological ordering for the DAG by
370 /// initializing the Index2Node and Node2Index arrays and then tries to keep
371 /// the ordering up-to-date after edge insertions by reordering the DAG.
373 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
374 /// the nodes reachable from Y, and then shifts them using Shift to lie
375 /// immediately after X in Index2Node.
376 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
377 unsigned DAGSize = SUnits.size();
378 std::vector<SUnit*> WorkList;
379 WorkList.reserve(DAGSize);
381 Index2Node.resize(DAGSize);
382 Node2Index.resize(DAGSize);
384 // Initialize the data structures.
385 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
386 SUnit *SU = &SUnits[i];
387 int NodeNum = SU->NodeNum;
388 unsigned Degree = SU->Succs.size();
389 // Temporarily use the Node2Index array as scratch space for degree counts.
390 Node2Index[NodeNum] = Degree;
392 // Is it a node without dependencies?
394 assert(SU->Succs.empty() && "SUnit should have no successors");
395 // Collect leaf nodes.
396 WorkList.push_back(SU);
401 while (!WorkList.empty()) {
402 SUnit *SU = WorkList.back();
404 Allocate(SU->NodeNum, --Id);
405 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
407 SUnit *SU = I->getSUnit();
408 if (!--Node2Index[SU->NodeNum])
409 // If all dependencies of the node are processed already,
410 // then the node can be computed now.
411 WorkList.push_back(SU);
415 Visited.resize(DAGSize);
418 // Check correctness of the ordering
419 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
420 SUnit *SU = &SUnits[i];
421 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
423 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
424 "Wrong topological sorting");
430 /// AddPred - Updates the topological ordering to accomodate an edge
431 /// to be added from SUnit X to SUnit Y.
432 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
433 int UpperBound, LowerBound;
434 LowerBound = Node2Index[Y->NodeNum];
435 UpperBound = Node2Index[X->NodeNum];
436 bool HasLoop = false;
437 // Is Ord(X) < Ord(Y) ?
438 if (LowerBound < UpperBound) {
439 // Update the topological order.
441 DFS(Y, UpperBound, HasLoop);
442 assert(!HasLoop && "Inserted edge creates a loop!");
443 // Recompute topological indexes.
444 Shift(Visited, LowerBound, UpperBound);
448 /// RemovePred - Updates the topological ordering to accomodate an
449 /// an edge to be removed from the specified node N from the predecessors
450 /// of the current node M.
451 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
452 // InitDAGTopologicalSorting();
455 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
456 /// all nodes affected by the edge insertion. These nodes will later get new
457 /// topological indexes by means of the Shift method.
458 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
460 std::vector<const SUnit*> WorkList;
461 WorkList.reserve(SUnits.size());
463 WorkList.push_back(SU);
464 while (!WorkList.empty()) {
465 SU = WorkList.back();
467 Visited.set(SU->NodeNum);
468 for (int I = SU->Succs.size()-1; I >= 0; --I) {
469 int s = SU->Succs[I].getSUnit()->NodeNum;
470 if (Node2Index[s] == UpperBound) {
474 // Visit successors if not already and in affected region.
475 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
476 WorkList.push_back(SU->Succs[I].getSUnit());
482 /// Shift - Renumber the nodes so that the topological ordering is
484 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
490 for (i = LowerBound; i <= UpperBound; ++i) {
491 // w is node at topological index i.
492 int w = Index2Node[i];
493 if (Visited.test(w)) {
499 Allocate(w, i - shift);
503 for (unsigned j = 0; j < L.size(); ++j) {
504 Allocate(L[j], i - shift);
510 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
512 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
513 if (IsReachable(TargetSU, SU))
515 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
517 if (I->isAssignedRegDep() &&
518 IsReachable(TargetSU, I->getSUnit()))
523 /// IsReachable - Checks if SU is reachable from TargetSU.
524 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
525 const SUnit *TargetSU) {
526 // If insertion of the edge SU->TargetSU would create a cycle
527 // then there is a path from TargetSU to SU.
528 int UpperBound, LowerBound;
529 LowerBound = Node2Index[TargetSU->NodeNum];
530 UpperBound = Node2Index[SU->NodeNum];
531 bool HasLoop = false;
532 // Is Ord(TargetSU) < Ord(SU) ?
533 if (LowerBound < UpperBound) {
535 // There may be a path from TargetSU to SU. Check for it.
536 DFS(TargetSU, UpperBound, HasLoop);
541 /// Allocate - assign the topological index to the node n.
542 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
543 Node2Index[n] = index;
544 Index2Node[index] = n;
547 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
548 std::vector<SUnit> &sunits)