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/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
29 static cl::opt<bool> StressSchedOpt(
30 "stress-sched", cl::Hidden, cl::init(false),
31 cl::desc("Stress test instruction scheduling"));
34 void SchedulingPriorityQueue::anchor() { }
36 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
38 TII(TM.getInstrInfo()),
39 TRI(TM.getRegisterInfo()),
40 MF(mf), MRI(mf.getRegInfo()),
43 StressSched = StressSchedOpt;
47 ScheduleDAG::~ScheduleDAG() {}
49 /// Clear the DAG state (e.g. between scheduling regions).
50 void ScheduleDAG::clearDAG() {
56 /// getInstrDesc helper to handle SDNodes.
57 const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
58 if (!Node || !Node->isMachineOpcode()) return NULL;
59 return &TII->get(Node->getMachineOpcode());
62 /// addPred - This adds the specified edge as a pred of the current node if
63 /// not already. It also adds the current node as a successor of the
65 bool SUnit::addPred(const SDep &D, bool Required) {
66 // If this node already has this depenence, don't add a redundant one.
67 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
69 // Zero-latency weak edges may be added purely for heuristic ordering. Don't
70 // add them if another kind of edge already exists.
71 if (!Required && I->getSUnit() == D.getSUnit())
74 // Extend the latency if needed. Equivalent to removePred(I) + addPred(D).
75 if (I->getLatency() < D.getLatency()) {
76 SUnit *PredSU = I->getSUnit();
77 // Find the corresponding successor in N.
79 ForwardD.setSUnit(this);
80 for (SmallVector<SDep, 4>::iterator II = PredSU->Succs.begin(),
81 EE = PredSU->Succs.end(); II != EE; ++II) {
82 if (*II == ForwardD) {
83 II->setLatency(D.getLatency());
87 I->setLatency(D.getLatency());
92 // Now add a corresponding succ to N.
95 SUnit *N = D.getSUnit();
96 // Update the bookkeeping.
97 if (D.getKind() == SDep::Data) {
98 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
99 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
103 if (!N->isScheduled) {
108 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
117 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
122 N->Succs.push_back(P);
123 if (P.getLatency() != 0) {
124 this->setDepthDirty();
130 /// removePred - This removes the specified edge as a pred of the current
131 /// node if it exists. It also removes the current node as a successor of
132 /// the specified node.
133 void SUnit::removePred(const SDep &D) {
134 // Find the matching predecessor.
135 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
138 bool FoundSucc = false;
139 // Find the corresponding successor in N.
142 SUnit *N = D.getSUnit();
143 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
144 EE = N->Succs.end(); II != EE; ++II)
150 assert(FoundSucc && "Mismatching preds / succs lists!");
153 // Update the bookkeeping.
154 if (P.getKind() == SDep::Data) {
155 assert(NumPreds > 0 && "NumPreds will underflow!");
156 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
160 if (!N->isScheduled) {
164 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
172 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
176 if (P.getLatency() != 0) {
177 this->setDepthDirty();
184 void SUnit::setDepthDirty() {
185 if (!isDepthCurrent) return;
186 SmallVector<SUnit*, 8> WorkList;
187 WorkList.push_back(this);
189 SUnit *SU = WorkList.pop_back_val();
190 SU->isDepthCurrent = false;
191 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
192 E = SU->Succs.end(); I != E; ++I) {
193 SUnit *SuccSU = I->getSUnit();
194 if (SuccSU->isDepthCurrent)
195 WorkList.push_back(SuccSU);
197 } while (!WorkList.empty());
200 void SUnit::setHeightDirty() {
201 if (!isHeightCurrent) return;
202 SmallVector<SUnit*, 8> WorkList;
203 WorkList.push_back(this);
205 SUnit *SU = WorkList.pop_back_val();
206 SU->isHeightCurrent = false;
207 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
208 E = SU->Preds.end(); I != E; ++I) {
209 SUnit *PredSU = I->getSUnit();
210 if (PredSU->isHeightCurrent)
211 WorkList.push_back(PredSU);
213 } while (!WorkList.empty());
216 /// setDepthToAtLeast - Update this node's successors to reflect the
217 /// fact that this node's depth just increased.
219 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
220 if (NewDepth <= getDepth())
224 isDepthCurrent = true;
227 /// setHeightToAtLeast - Update this node's predecessors to reflect the
228 /// fact that this node's height just increased.
230 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
231 if (NewHeight <= getHeight())
235 isHeightCurrent = true;
238 /// ComputeDepth - Calculate the maximal path from the node to the exit.
240 void SUnit::ComputeDepth() {
241 SmallVector<SUnit*, 8> WorkList;
242 WorkList.push_back(this);
244 SUnit *Cur = WorkList.back();
247 unsigned MaxPredDepth = 0;
248 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
249 E = Cur->Preds.end(); I != E; ++I) {
250 SUnit *PredSU = I->getSUnit();
251 if (PredSU->isDepthCurrent)
252 MaxPredDepth = std::max(MaxPredDepth,
253 PredSU->Depth + I->getLatency());
256 WorkList.push_back(PredSU);
262 if (MaxPredDepth != Cur->Depth) {
263 Cur->setDepthDirty();
264 Cur->Depth = MaxPredDepth;
266 Cur->isDepthCurrent = true;
268 } while (!WorkList.empty());
271 /// ComputeHeight - Calculate the maximal path from the node to the entry.
273 void SUnit::ComputeHeight() {
274 SmallVector<SUnit*, 8> WorkList;
275 WorkList.push_back(this);
277 SUnit *Cur = WorkList.back();
280 unsigned MaxSuccHeight = 0;
281 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
282 E = Cur->Succs.end(); I != E; ++I) {
283 SUnit *SuccSU = I->getSUnit();
284 if (SuccSU->isHeightCurrent)
285 MaxSuccHeight = std::max(MaxSuccHeight,
286 SuccSU->Height + I->getLatency());
289 WorkList.push_back(SuccSU);
295 if (MaxSuccHeight != Cur->Height) {
296 Cur->setHeightDirty();
297 Cur->Height = MaxSuccHeight;
299 Cur->isHeightCurrent = true;
301 } while (!WorkList.empty());
304 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
305 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
306 /// a group of nodes flagged together.
307 void SUnit::dump(const ScheduleDAG *G) const {
308 dbgs() << "SU(" << NodeNum << "): ";
312 void SUnit::dumpAll(const ScheduleDAG *G) const {
315 dbgs() << " # preds left : " << NumPredsLeft << "\n";
316 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
318 dbgs() << " # weak preds left : " << WeakPredsLeft << "\n";
320 dbgs() << " # weak succs left : " << WeakSuccsLeft << "\n";
321 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
322 dbgs() << " Latency : " << Latency << "\n";
323 dbgs() << " Depth : " << Depth << "\n";
324 dbgs() << " Height : " << Height << "\n";
326 if (Preds.size() != 0) {
327 dbgs() << " Predecessors:\n";
328 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
331 switch (I->getKind()) {
332 case SDep::Data: dbgs() << "val "; break;
333 case SDep::Anti: dbgs() << "anti"; break;
334 case SDep::Output: dbgs() << "out "; break;
335 case SDep::Order: dbgs() << "ch "; break;
337 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
338 if (I->isArtificial())
340 dbgs() << ": Latency=" << I->getLatency();
341 if (I->isAssignedRegDep())
342 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
346 if (Succs.size() != 0) {
347 dbgs() << " Successors:\n";
348 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
351 switch (I->getKind()) {
352 case SDep::Data: dbgs() << "val "; break;
353 case SDep::Anti: dbgs() << "anti"; break;
354 case SDep::Output: dbgs() << "out "; break;
355 case SDep::Order: dbgs() << "ch "; break;
357 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
358 if (I->isArtificial())
360 dbgs() << ": Latency=" << I->getLatency();
369 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
370 /// their state is consistent. Return the number of scheduled nodes.
372 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
373 bool AnyNotSched = false;
374 unsigned DeadNodes = 0;
375 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
376 if (!SUnits[i].isScheduled) {
377 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
382 dbgs() << "*** Scheduling failed! ***\n";
383 SUnits[i].dump(this);
384 dbgs() << "has not been scheduled!\n";
387 if (SUnits[i].isScheduled &&
388 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
391 dbgs() << "*** Scheduling failed! ***\n";
392 SUnits[i].dump(this);
393 dbgs() << "has an unexpected "
394 << (isBottomUp ? "Height" : "Depth") << " value!\n";
398 if (SUnits[i].NumSuccsLeft != 0) {
400 dbgs() << "*** Scheduling failed! ***\n";
401 SUnits[i].dump(this);
402 dbgs() << "has successors left!\n";
406 if (SUnits[i].NumPredsLeft != 0) {
408 dbgs() << "*** Scheduling failed! ***\n";
409 SUnits[i].dump(this);
410 dbgs() << "has predecessors left!\n";
415 assert(!AnyNotSched);
416 return SUnits.size() - DeadNodes;
420 /// InitDAGTopologicalSorting - create the initial topological
421 /// ordering from the DAG to be scheduled.
423 /// The idea of the algorithm is taken from
424 /// "Online algorithms for managing the topological order of
425 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
426 /// This is the MNR algorithm, which was first introduced by
427 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
428 /// "Maintaining a topological order under edge insertions".
430 /// Short description of the algorithm:
432 /// Topological ordering, ord, of a DAG maps each node to a topological
433 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
435 /// This means that if there is a path from the node X to the node Z,
436 /// then ord(X) < ord(Z).
438 /// This property can be used to check for reachability of nodes:
439 /// if Z is reachable from X, then an insertion of the edge Z->X would
442 /// The algorithm first computes a topological ordering for the DAG by
443 /// initializing the Index2Node and Node2Index arrays and then tries to keep
444 /// the ordering up-to-date after edge insertions by reordering the DAG.
446 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
447 /// the nodes reachable from Y, and then shifts them using Shift to lie
448 /// immediately after X in Index2Node.
449 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
450 unsigned DAGSize = SUnits.size();
451 std::vector<SUnit*> WorkList;
452 WorkList.reserve(DAGSize);
454 Index2Node.resize(DAGSize);
455 Node2Index.resize(DAGSize);
457 // Initialize the data structures.
459 WorkList.push_back(ExitSU);
460 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
461 SUnit *SU = &SUnits[i];
462 int NodeNum = SU->NodeNum;
463 unsigned Degree = SU->Succs.size();
464 // Temporarily use the Node2Index array as scratch space for degree counts.
465 Node2Index[NodeNum] = Degree;
467 // Is it a node without dependencies?
469 assert(SU->Succs.empty() && "SUnit should have no successors");
470 // Collect leaf nodes.
471 WorkList.push_back(SU);
476 while (!WorkList.empty()) {
477 SUnit *SU = WorkList.back();
479 if (SU->NodeNum < DAGSize)
480 Allocate(SU->NodeNum, --Id);
481 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
483 SUnit *SU = I->getSUnit();
484 if (SU->NodeNum < DAGSize && !--Node2Index[SU->NodeNum])
485 // If all dependencies of the node are processed already,
486 // then the node can be computed now.
487 WorkList.push_back(SU);
491 Visited.resize(DAGSize);
494 // Check correctness of the ordering
495 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
496 SUnit *SU = &SUnits[i];
497 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
499 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
500 "Wrong topological sorting");
506 /// AddPred - Updates the topological ordering to accommodate an edge
507 /// to be added from SUnit X to SUnit Y.
508 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
509 int UpperBound, LowerBound;
510 LowerBound = Node2Index[Y->NodeNum];
511 UpperBound = Node2Index[X->NodeNum];
512 bool HasLoop = false;
513 // Is Ord(X) < Ord(Y) ?
514 if (LowerBound < UpperBound) {
515 // Update the topological order.
517 DFS(Y, UpperBound, HasLoop);
518 assert(!HasLoop && "Inserted edge creates a loop!");
519 // Recompute topological indexes.
520 Shift(Visited, LowerBound, UpperBound);
524 /// RemovePred - Updates the topological ordering to accommodate an
525 /// an edge to be removed from the specified node N from the predecessors
526 /// of the current node M.
527 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
528 // InitDAGTopologicalSorting();
531 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
532 /// all nodes affected by the edge insertion. These nodes will later get new
533 /// topological indexes by means of the Shift method.
534 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
536 std::vector<const SUnit*> WorkList;
537 WorkList.reserve(SUnits.size());
539 WorkList.push_back(SU);
541 SU = WorkList.back();
543 Visited.set(SU->NodeNum);
544 for (int I = SU->Succs.size()-1; I >= 0; --I) {
545 unsigned s = SU->Succs[I].getSUnit()->NodeNum;
546 // Edges to non-SUnits are allowed but ignored (e.g. ExitSU).
547 if (s >= Node2Index.size())
549 if (Node2Index[s] == UpperBound) {
553 // Visit successors if not already and in affected region.
554 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
555 WorkList.push_back(SU->Succs[I].getSUnit());
558 } while (!WorkList.empty());
561 /// Shift - Renumber the nodes so that the topological ordering is
563 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
569 for (i = LowerBound; i <= UpperBound; ++i) {
570 // w is node at topological index i.
571 int w = Index2Node[i];
572 if (Visited.test(w)) {
578 Allocate(w, i - shift);
582 for (unsigned j = 0; j < L.size(); ++j) {
583 Allocate(L[j], i - shift);
589 /// WillCreateCycle - Returns true if adding an edge to TargetSU from SU will
590 /// create a cycle. If so, it is not safe to call AddPred(TargetSU, SU).
591 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *TargetSU, SUnit *SU) {
592 // Is SU reachable from TargetSU via successor edges?
593 if (IsReachable(SU, TargetSU))
595 for (SUnit::pred_iterator
596 I = TargetSU->Preds.begin(), E = TargetSU->Preds.end(); I != E; ++I)
597 if (I->isAssignedRegDep() &&
598 IsReachable(SU, I->getSUnit()))
603 /// IsReachable - Checks if SU is reachable from TargetSU.
604 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
605 const SUnit *TargetSU) {
606 // If insertion of the edge SU->TargetSU would create a cycle
607 // then there is a path from TargetSU to SU.
608 int UpperBound, LowerBound;
609 LowerBound = Node2Index[TargetSU->NodeNum];
610 UpperBound = Node2Index[SU->NodeNum];
611 bool HasLoop = false;
612 // Is Ord(TargetSU) < Ord(SU) ?
613 if (LowerBound < UpperBound) {
615 // There may be a path from TargetSU to SU. Check for it.
616 DFS(TargetSU, UpperBound, HasLoop);
621 /// Allocate - assign the topological index to the node n.
622 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
623 Node2Index[n] = index;
624 Index2Node[index] = n;
627 ScheduleDAGTopologicalSort::
628 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits, SUnit *exitsu)
629 : SUnits(sunits), ExitSU(exitsu) {}
631 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}