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) {
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();
70 // Extend the latency if needed. Equivalent to removePred(I) + addPred(D).
71 if (I->getLatency() < D.getLatency()) {
72 SUnit *PredSU = I->getSUnit();
73 // Find the corresponding successor in N.
75 ForwardD.setSUnit(this);
76 for (SmallVector<SDep, 4>::iterator II = PredSU->Succs.begin(),
77 EE = PredSU->Succs.end(); II != EE; ++II) {
78 if (*II == ForwardD) {
79 II->setLatency(D.getLatency());
83 I->setLatency(D.getLatency());
88 // Now add a corresponding succ to N.
91 SUnit *N = D.getSUnit();
92 // Update the bookkeeping.
93 if (D.getKind() == SDep::Data) {
94 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
95 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
99 if (!N->isScheduled) {
100 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
104 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
108 N->Succs.push_back(P);
109 if (P.getLatency() != 0) {
110 this->setDepthDirty();
116 /// removePred - This removes the specified edge as a pred of the current
117 /// node if it exists. It also removes the current node as a successor of
118 /// the specified node.
119 void SUnit::removePred(const SDep &D) {
120 // Find the matching predecessor.
121 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
124 bool FoundSucc = false;
125 // Find the corresponding successor in N.
128 SUnit *N = D.getSUnit();
129 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
130 EE = N->Succs.end(); II != EE; ++II)
136 assert(FoundSucc && "Mismatching preds / succs lists!");
139 // Update the bookkeeping.
140 if (P.getKind() == SDep::Data) {
141 assert(NumPreds > 0 && "NumPreds will underflow!");
142 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
146 if (!N->isScheduled) {
147 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
151 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
154 if (P.getLatency() != 0) {
155 this->setDepthDirty();
162 void SUnit::setDepthDirty() {
163 if (!isDepthCurrent) return;
164 SmallVector<SUnit*, 8> WorkList;
165 WorkList.push_back(this);
167 SUnit *SU = WorkList.pop_back_val();
168 SU->isDepthCurrent = false;
169 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
170 E = SU->Succs.end(); I != E; ++I) {
171 SUnit *SuccSU = I->getSUnit();
172 if (SuccSU->isDepthCurrent)
173 WorkList.push_back(SuccSU);
175 } while (!WorkList.empty());
178 void SUnit::setHeightDirty() {
179 if (!isHeightCurrent) return;
180 SmallVector<SUnit*, 8> WorkList;
181 WorkList.push_back(this);
183 SUnit *SU = WorkList.pop_back_val();
184 SU->isHeightCurrent = false;
185 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
186 E = SU->Preds.end(); I != E; ++I) {
187 SUnit *PredSU = I->getSUnit();
188 if (PredSU->isHeightCurrent)
189 WorkList.push_back(PredSU);
191 } while (!WorkList.empty());
194 /// setDepthToAtLeast - Update this node's successors to reflect the
195 /// fact that this node's depth just increased.
197 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
198 if (NewDepth <= getDepth())
202 isDepthCurrent = true;
205 /// setHeightToAtLeast - Update this node's predecessors to reflect the
206 /// fact that this node's height just increased.
208 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
209 if (NewHeight <= getHeight())
213 isHeightCurrent = true;
216 /// ComputeDepth - Calculate the maximal path from the node to the exit.
218 void SUnit::ComputeDepth() {
219 SmallVector<SUnit*, 8> WorkList;
220 WorkList.push_back(this);
222 SUnit *Cur = WorkList.back();
225 unsigned MaxPredDepth = 0;
226 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
227 E = Cur->Preds.end(); I != E; ++I) {
228 SUnit *PredSU = I->getSUnit();
229 if (PredSU->isDepthCurrent)
230 MaxPredDepth = std::max(MaxPredDepth,
231 PredSU->Depth + I->getLatency());
234 WorkList.push_back(PredSU);
240 if (MaxPredDepth != Cur->Depth) {
241 Cur->setDepthDirty();
242 Cur->Depth = MaxPredDepth;
244 Cur->isDepthCurrent = true;
246 } while (!WorkList.empty());
249 /// ComputeHeight - Calculate the maximal path from the node to the entry.
251 void SUnit::ComputeHeight() {
252 SmallVector<SUnit*, 8> WorkList;
253 WorkList.push_back(this);
255 SUnit *Cur = WorkList.back();
258 unsigned MaxSuccHeight = 0;
259 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
260 E = Cur->Succs.end(); I != E; ++I) {
261 SUnit *SuccSU = I->getSUnit();
262 if (SuccSU->isHeightCurrent)
263 MaxSuccHeight = std::max(MaxSuccHeight,
264 SuccSU->Height + I->getLatency());
267 WorkList.push_back(SuccSU);
273 if (MaxSuccHeight != Cur->Height) {
274 Cur->setHeightDirty();
275 Cur->Height = MaxSuccHeight;
277 Cur->isHeightCurrent = true;
279 } while (!WorkList.empty());
282 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
283 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
284 /// a group of nodes flagged together.
285 void SUnit::dump(const ScheduleDAG *G) const {
286 dbgs() << "SU(" << NodeNum << "): ";
290 void SUnit::dumpAll(const ScheduleDAG *G) const {
293 dbgs() << " # preds left : " << NumPredsLeft << "\n";
294 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
295 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
296 dbgs() << " Latency : " << Latency << "\n";
297 dbgs() << " Depth : " << Depth << "\n";
298 dbgs() << " Height : " << Height << "\n";
300 if (Preds.size() != 0) {
301 dbgs() << " Predecessors:\n";
302 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
305 switch (I->getKind()) {
306 case SDep::Data: dbgs() << "val "; break;
307 case SDep::Anti: dbgs() << "anti"; break;
308 case SDep::Output: dbgs() << "out "; break;
309 case SDep::Order: dbgs() << "ch "; break;
311 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
312 if (I->isArtificial())
314 dbgs() << ": Latency=" << I->getLatency();
315 if (I->isAssignedRegDep())
316 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
320 if (Succs.size() != 0) {
321 dbgs() << " Successors:\n";
322 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
325 switch (I->getKind()) {
326 case SDep::Data: dbgs() << "val "; break;
327 case SDep::Anti: dbgs() << "anti"; break;
328 case SDep::Output: dbgs() << "out "; break;
329 case SDep::Order: dbgs() << "ch "; break;
331 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
332 if (I->isArtificial())
334 dbgs() << ": Latency=" << I->getLatency();
343 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
344 /// their state is consistent. Return the number of scheduled nodes.
346 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
347 bool AnyNotSched = false;
348 unsigned DeadNodes = 0;
349 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
350 if (!SUnits[i].isScheduled) {
351 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
356 dbgs() << "*** Scheduling failed! ***\n";
357 SUnits[i].dump(this);
358 dbgs() << "has not been scheduled!\n";
361 if (SUnits[i].isScheduled &&
362 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
365 dbgs() << "*** Scheduling failed! ***\n";
366 SUnits[i].dump(this);
367 dbgs() << "has an unexpected "
368 << (isBottomUp ? "Height" : "Depth") << " value!\n";
372 if (SUnits[i].NumSuccsLeft != 0) {
374 dbgs() << "*** Scheduling failed! ***\n";
375 SUnits[i].dump(this);
376 dbgs() << "has successors left!\n";
380 if (SUnits[i].NumPredsLeft != 0) {
382 dbgs() << "*** Scheduling failed! ***\n";
383 SUnits[i].dump(this);
384 dbgs() << "has predecessors left!\n";
389 assert(!AnyNotSched);
390 return SUnits.size() - DeadNodes;
394 /// InitDAGTopologicalSorting - create the initial topological
395 /// ordering from the DAG to be scheduled.
397 /// The idea of the algorithm is taken from
398 /// "Online algorithms for managing the topological order of
399 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
400 /// This is the MNR algorithm, which was first introduced by
401 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
402 /// "Maintaining a topological order under edge insertions".
404 /// Short description of the algorithm:
406 /// Topological ordering, ord, of a DAG maps each node to a topological
407 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
409 /// This means that if there is a path from the node X to the node Z,
410 /// then ord(X) < ord(Z).
412 /// This property can be used to check for reachability of nodes:
413 /// if Z is reachable from X, then an insertion of the edge Z->X would
416 /// The algorithm first computes a topological ordering for the DAG by
417 /// initializing the Index2Node and Node2Index arrays and then tries to keep
418 /// the ordering up-to-date after edge insertions by reordering the DAG.
420 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
421 /// the nodes reachable from Y, and then shifts them using Shift to lie
422 /// immediately after X in Index2Node.
423 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
424 unsigned DAGSize = SUnits.size();
425 std::vector<SUnit*> WorkList;
426 WorkList.reserve(DAGSize);
428 Index2Node.resize(DAGSize);
429 Node2Index.resize(DAGSize);
431 // Initialize the data structures.
432 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
433 SUnit *SU = &SUnits[i];
434 int NodeNum = SU->NodeNum;
435 unsigned Degree = SU->Succs.size();
436 // Temporarily use the Node2Index array as scratch space for degree counts.
437 Node2Index[NodeNum] = Degree;
439 // Is it a node without dependencies?
441 assert(SU->Succs.empty() && "SUnit should have no successors");
442 // Collect leaf nodes.
443 WorkList.push_back(SU);
448 while (!WorkList.empty()) {
449 SUnit *SU = WorkList.back();
451 Allocate(SU->NodeNum, --Id);
452 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
454 SUnit *SU = I->getSUnit();
455 if (!--Node2Index[SU->NodeNum])
456 // If all dependencies of the node are processed already,
457 // then the node can be computed now.
458 WorkList.push_back(SU);
462 Visited.resize(DAGSize);
465 // Check correctness of the ordering
466 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
467 SUnit *SU = &SUnits[i];
468 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
470 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
471 "Wrong topological sorting");
477 /// AddPred - Updates the topological ordering to accommodate an edge
478 /// to be added from SUnit X to SUnit Y.
479 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
480 int UpperBound, LowerBound;
481 LowerBound = Node2Index[Y->NodeNum];
482 UpperBound = Node2Index[X->NodeNum];
483 bool HasLoop = false;
484 // Is Ord(X) < Ord(Y) ?
485 if (LowerBound < UpperBound) {
486 // Update the topological order.
488 DFS(Y, UpperBound, HasLoop);
489 assert(!HasLoop && "Inserted edge creates a loop!");
490 // Recompute topological indexes.
491 Shift(Visited, LowerBound, UpperBound);
495 /// RemovePred - Updates the topological ordering to accommodate an
496 /// an edge to be removed from the specified node N from the predecessors
497 /// of the current node M.
498 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
499 // InitDAGTopologicalSorting();
502 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
503 /// all nodes affected by the edge insertion. These nodes will later get new
504 /// topological indexes by means of the Shift method.
505 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
507 std::vector<const SUnit*> WorkList;
508 WorkList.reserve(SUnits.size());
510 WorkList.push_back(SU);
512 SU = WorkList.back();
514 Visited.set(SU->NodeNum);
515 for (int I = SU->Succs.size()-1; I >= 0; --I) {
516 int s = SU->Succs[I].getSUnit()->NodeNum;
517 if (Node2Index[s] == UpperBound) {
521 // Visit successors if not already and in affected region.
522 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
523 WorkList.push_back(SU->Succs[I].getSUnit());
526 } while (!WorkList.empty());
529 /// Shift - Renumber the nodes so that the topological ordering is
531 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
537 for (i = LowerBound; i <= UpperBound; ++i) {
538 // w is node at topological index i.
539 int w = Index2Node[i];
540 if (Visited.test(w)) {
546 Allocate(w, i - shift);
550 for (unsigned j = 0; j < L.size(); ++j) {
551 Allocate(L[j], i - shift);
557 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
559 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
560 if (IsReachable(TargetSU, SU))
562 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
564 if (I->isAssignedRegDep() &&
565 IsReachable(TargetSU, I->getSUnit()))
570 /// IsReachable - Checks if SU is reachable from TargetSU.
571 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
572 const SUnit *TargetSU) {
573 // If insertion of the edge SU->TargetSU would create a cycle
574 // then there is a path from TargetSU to SU.
575 int UpperBound, LowerBound;
576 LowerBound = Node2Index[TargetSU->NodeNum];
577 UpperBound = Node2Index[SU->NodeNum];
578 bool HasLoop = false;
579 // Is Ord(TargetSU) < Ord(SU) ?
580 if (LowerBound < UpperBound) {
582 // There may be a path from TargetSU to SU. Check for it.
583 DFS(TargetSU, UpperBound, HasLoop);
588 /// Allocate - assign the topological index to the node n.
589 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
590 Node2Index[n] = index;
591 Index2Node[index] = n;
594 ScheduleDAGTopologicalSort::
595 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits) : SUnits(sunits) {}
597 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}