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/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
27 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
29 TII(TM.getInstrInfo()),
30 TRI(TM.getRegisterInfo()),
31 MF(mf), MRI(mf.getRegInfo()),
35 ScheduleDAG::~ScheduleDAG() {}
37 /// getInstrDesc helper to handle SDNodes.
38 const TargetInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
39 if (!Node || !Node->isMachineOpcode()) return NULL;
40 return &TII->get(Node->getMachineOpcode());
43 /// dump - dump the schedule.
44 void ScheduleDAG::dumpSchedule() const {
45 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
46 if (SUnit *SU = Sequence[i])
49 dbgs() << "**** NOOP ****\n";
54 /// Run - perform scheduling.
56 void ScheduleDAG::Run(MachineBasicBlock *bb,
57 MachineBasicBlock::iterator insertPos) {
59 InsertPos = insertPos;
69 dbgs() << "*** Final schedule ***\n";
75 /// addPred - This adds the specified edge as a pred of the current node if
76 /// not already. It also adds the current node as a successor of the
78 bool SUnit::addPred(const SDep &D) {
79 // If this node already has this depenence, don't add a redundant one.
80 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
84 // Now add a corresponding succ to N.
87 SUnit *N = D.getSUnit();
88 // Update the bookkeeping.
89 if (D.getKind() == SDep::Data) {
90 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
91 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
95 if (!N->isScheduled) {
96 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
100 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
104 N->Succs.push_back(P);
105 if (P.getLatency() != 0) {
106 this->setDepthDirty();
112 /// removePred - This removes the specified edge as a pred of the current
113 /// node if it exists. It also removes the current node as a successor of
114 /// the specified node.
115 void SUnit::removePred(const SDep &D) {
116 // Find the matching predecessor.
117 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
120 bool FoundSucc = false;
121 // Find the corresponding successor in N.
124 SUnit *N = D.getSUnit();
125 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
126 EE = N->Succs.end(); II != EE; ++II)
132 assert(FoundSucc && "Mismatching preds / succs lists!");
134 // Update the bookkeeping.
135 if (P.getKind() == SDep::Data) {
136 assert(NumPreds > 0 && "NumPreds will underflow!");
137 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
141 if (!N->isScheduled) {
142 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
146 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
149 if (P.getLatency() != 0) {
150 this->setDepthDirty();
157 void SUnit::setDepthDirty() {
158 if (!isDepthCurrent) return;
159 SmallVector<SUnit*, 8> WorkList;
160 WorkList.push_back(this);
162 SUnit *SU = WorkList.pop_back_val();
163 SU->isDepthCurrent = false;
164 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
165 E = SU->Succs.end(); I != E; ++I) {
166 SUnit *SuccSU = I->getSUnit();
167 if (SuccSU->isDepthCurrent)
168 WorkList.push_back(SuccSU);
170 } while (!WorkList.empty());
173 void SUnit::setHeightDirty() {
174 if (!isHeightCurrent) return;
175 SmallVector<SUnit*, 8> WorkList;
176 WorkList.push_back(this);
178 SUnit *SU = WorkList.pop_back_val();
179 SU->isHeightCurrent = false;
180 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
181 E = SU->Preds.end(); I != E; ++I) {
182 SUnit *PredSU = I->getSUnit();
183 if (PredSU->isHeightCurrent)
184 WorkList.push_back(PredSU);
186 } while (!WorkList.empty());
189 /// setDepthToAtLeast - Update this node's successors to reflect the
190 /// fact that this node's depth just increased.
192 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
193 if (NewDepth <= getDepth())
197 isDepthCurrent = true;
200 /// setHeightToAtLeast - Update this node's predecessors to reflect the
201 /// fact that this node's height just increased.
203 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
204 if (NewHeight <= getHeight())
208 isHeightCurrent = true;
211 /// ComputeDepth - Calculate the maximal path from the node to the exit.
213 void SUnit::ComputeDepth() {
214 SmallVector<SUnit*, 8> WorkList;
215 WorkList.push_back(this);
217 SUnit *Cur = WorkList.back();
220 unsigned MaxPredDepth = 0;
221 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
222 E = Cur->Preds.end(); I != E; ++I) {
223 SUnit *PredSU = I->getSUnit();
224 if (PredSU->isDepthCurrent)
225 MaxPredDepth = std::max(MaxPredDepth,
226 PredSU->Depth + I->getLatency());
229 WorkList.push_back(PredSU);
235 if (MaxPredDepth != Cur->Depth) {
236 Cur->setDepthDirty();
237 Cur->Depth = MaxPredDepth;
239 Cur->isDepthCurrent = true;
241 } while (!WorkList.empty());
244 /// ComputeHeight - Calculate the maximal path from the node to the entry.
246 void SUnit::ComputeHeight() {
247 SmallVector<SUnit*, 8> WorkList;
248 WorkList.push_back(this);
250 SUnit *Cur = WorkList.back();
253 unsigned MaxSuccHeight = 0;
254 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
255 E = Cur->Succs.end(); I != E; ++I) {
256 SUnit *SuccSU = I->getSUnit();
257 if (SuccSU->isHeightCurrent)
258 MaxSuccHeight = std::max(MaxSuccHeight,
259 SuccSU->Height + I->getLatency());
262 WorkList.push_back(SuccSU);
268 if (MaxSuccHeight != Cur->Height) {
269 Cur->setHeightDirty();
270 Cur->Height = MaxSuccHeight;
272 Cur->isHeightCurrent = true;
274 } while (!WorkList.empty());
277 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
278 /// a group of nodes flagged together.
279 void SUnit::dump(const ScheduleDAG *G) const {
280 dbgs() << "SU(" << NodeNum << "): ";
284 void SUnit::dumpAll(const ScheduleDAG *G) const {
287 dbgs() << " # preds left : " << NumPredsLeft << "\n";
288 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
289 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
290 dbgs() << " Latency : " << Latency << "\n";
291 dbgs() << " Depth : " << Depth << "\n";
292 dbgs() << " Height : " << Height << "\n";
294 if (Preds.size() != 0) {
295 dbgs() << " Predecessors:\n";
296 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
299 switch (I->getKind()) {
300 case SDep::Data: dbgs() << "val "; break;
301 case SDep::Anti: dbgs() << "anti"; break;
302 case SDep::Output: dbgs() << "out "; break;
303 case SDep::Order: dbgs() << "ch "; break;
306 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
307 if (I->isArtificial())
309 dbgs() << ": Latency=" << I->getLatency();
313 if (Succs.size() != 0) {
314 dbgs() << " Successors:\n";
315 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
318 switch (I->getKind()) {
319 case SDep::Data: dbgs() << "val "; break;
320 case SDep::Anti: dbgs() << "anti"; break;
321 case SDep::Output: dbgs() << "out "; break;
322 case SDep::Order: dbgs() << "ch "; break;
325 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
326 if (I->isArtificial())
328 dbgs() << ": Latency=" << I->getLatency();
336 /// VerifySchedule - Verify that all SUnits were scheduled and that
337 /// their state is consistent.
339 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
340 bool AnyNotSched = false;
341 unsigned DeadNodes = 0;
343 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
344 if (!SUnits[i].isScheduled) {
345 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
350 dbgs() << "*** Scheduling failed! ***\n";
351 SUnits[i].dump(this);
352 dbgs() << "has not been scheduled!\n";
355 if (SUnits[i].isScheduled &&
356 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
359 dbgs() << "*** Scheduling failed! ***\n";
360 SUnits[i].dump(this);
361 dbgs() << "has an unexpected "
362 << (isBottomUp ? "Height" : "Depth") << " value!\n";
366 if (SUnits[i].NumSuccsLeft != 0) {
368 dbgs() << "*** Scheduling failed! ***\n";
369 SUnits[i].dump(this);
370 dbgs() << "has successors left!\n";
374 if (SUnits[i].NumPredsLeft != 0) {
376 dbgs() << "*** Scheduling failed! ***\n";
377 SUnits[i].dump(this);
378 dbgs() << "has predecessors left!\n";
383 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
386 assert(!AnyNotSched);
387 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
388 "The number of nodes scheduled doesn't match the expected number!");
392 /// InitDAGTopologicalSorting - create the initial topological
393 /// ordering from the DAG to be scheduled.
395 /// The idea of the algorithm is taken from
396 /// "Online algorithms for managing the topological order of
397 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
398 /// This is the MNR algorithm, which was first introduced by
399 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
400 /// "Maintaining a topological order under edge insertions".
402 /// Short description of the algorithm:
404 /// Topological ordering, ord, of a DAG maps each node to a topological
405 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
407 /// This means that if there is a path from the node X to the node Z,
408 /// then ord(X) < ord(Z).
410 /// This property can be used to check for reachability of nodes:
411 /// if Z is reachable from X, then an insertion of the edge Z->X would
414 /// The algorithm first computes a topological ordering for the DAG by
415 /// initializing the Index2Node and Node2Index arrays and then tries to keep
416 /// the ordering up-to-date after edge insertions by reordering the DAG.
418 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
419 /// the nodes reachable from Y, and then shifts them using Shift to lie
420 /// immediately after X in Index2Node.
421 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
422 unsigned DAGSize = SUnits.size();
423 std::vector<SUnit*> WorkList;
424 WorkList.reserve(DAGSize);
426 Index2Node.resize(DAGSize);
427 Node2Index.resize(DAGSize);
429 // Initialize the data structures.
430 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
431 SUnit *SU = &SUnits[i];
432 int NodeNum = SU->NodeNum;
433 unsigned Degree = SU->Succs.size();
434 // Temporarily use the Node2Index array as scratch space for degree counts.
435 Node2Index[NodeNum] = Degree;
437 // Is it a node without dependencies?
439 assert(SU->Succs.empty() && "SUnit should have no successors");
440 // Collect leaf nodes.
441 WorkList.push_back(SU);
446 while (!WorkList.empty()) {
447 SUnit *SU = WorkList.back();
449 Allocate(SU->NodeNum, --Id);
450 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
452 SUnit *SU = I->getSUnit();
453 if (!--Node2Index[SU->NodeNum])
454 // If all dependencies of the node are processed already,
455 // then the node can be computed now.
456 WorkList.push_back(SU);
460 Visited.resize(DAGSize);
463 // Check correctness of the ordering
464 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
465 SUnit *SU = &SUnits[i];
466 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
468 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
469 "Wrong topological sorting");
475 /// AddPred - Updates the topological ordering to accommodate an edge
476 /// to be added from SUnit X to SUnit Y.
477 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
478 int UpperBound, LowerBound;
479 LowerBound = Node2Index[Y->NodeNum];
480 UpperBound = Node2Index[X->NodeNum];
481 bool HasLoop = false;
482 // Is Ord(X) < Ord(Y) ?
483 if (LowerBound < UpperBound) {
484 // Update the topological order.
486 DFS(Y, UpperBound, HasLoop);
487 assert(!HasLoop && "Inserted edge creates a loop!");
488 // Recompute topological indexes.
489 Shift(Visited, LowerBound, UpperBound);
493 /// RemovePred - Updates the topological ordering to accommodate an
494 /// an edge to be removed from the specified node N from the predecessors
495 /// of the current node M.
496 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
497 // InitDAGTopologicalSorting();
500 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
501 /// all nodes affected by the edge insertion. These nodes will later get new
502 /// topological indexes by means of the Shift method.
503 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
505 std::vector<const SUnit*> WorkList;
506 WorkList.reserve(SUnits.size());
508 WorkList.push_back(SU);
510 SU = WorkList.back();
512 Visited.set(SU->NodeNum);
513 for (int I = SU->Succs.size()-1; I >= 0; --I) {
514 int s = SU->Succs[I].getSUnit()->NodeNum;
515 if (Node2Index[s] == UpperBound) {
519 // Visit successors if not already and in affected region.
520 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
521 WorkList.push_back(SU->Succs[I].getSUnit());
524 } while (!WorkList.empty());
527 /// Shift - Renumber the nodes so that the topological ordering is
529 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
535 for (i = LowerBound; i <= UpperBound; ++i) {
536 // w is node at topological index i.
537 int w = Index2Node[i];
538 if (Visited.test(w)) {
544 Allocate(w, i - shift);
548 for (unsigned j = 0; j < L.size(); ++j) {
549 Allocate(L[j], i - shift);
555 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
557 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
558 if (IsReachable(TargetSU, SU))
560 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
562 if (I->isAssignedRegDep() &&
563 IsReachable(TargetSU, I->getSUnit()))
568 /// IsReachable - Checks if SU is reachable from TargetSU.
569 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
570 const SUnit *TargetSU) {
571 // If insertion of the edge SU->TargetSU would create a cycle
572 // then there is a path from TargetSU to SU.
573 int UpperBound, LowerBound;
574 LowerBound = Node2Index[TargetSU->NodeNum];
575 UpperBound = Node2Index[SU->NodeNum];
576 bool HasLoop = false;
577 // Is Ord(TargetSU) < Ord(SU) ?
578 if (LowerBound < UpperBound) {
580 // There may be a path from TargetSU to SU. Check for it.
581 DFS(TargetSU, UpperBound, HasLoop);
586 /// Allocate - assign the topological index to the node n.
587 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
588 Node2Index[n] = index;
589 Index2Node[index] = n;
592 ScheduleDAGTopologicalSort::
593 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits) : SUnits(sunits) {}
595 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}