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 /// getInstrDesc helper to handle SDNodes.
50 const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
51 if (!Node || !Node->isMachineOpcode()) return NULL;
52 return &TII->get(Node->getMachineOpcode());
55 /// dump - dump the schedule.
56 void ScheduleDAG::dumpSchedule() const {
57 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
58 if (SUnit *SU = Sequence[i])
61 dbgs() << "**** NOOP ****\n";
66 /// Run - perform scheduling.
68 void ScheduleDAG::Run(MachineBasicBlock *bb,
69 MachineBasicBlock::iterator insertPos) {
71 InsertPos = insertPos;
81 dbgs() << "*** Final schedule ***\n";
87 /// addPred - This adds the specified edge as a pred of the current node if
88 /// not already. It also adds the current node as a successor of the
90 bool SUnit::addPred(const SDep &D) {
91 // If this node already has this depenence, don't add a redundant one.
92 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
96 // Now add a corresponding succ to N.
99 SUnit *N = D.getSUnit();
100 // Update the bookkeeping.
101 if (D.getKind() == SDep::Data) {
102 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
103 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
107 if (!N->isScheduled) {
108 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
112 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
116 N->Succs.push_back(P);
117 if (P.getLatency() != 0) {
118 this->setDepthDirty();
124 /// removePred - This removes the specified edge as a pred of the current
125 /// node if it exists. It also removes the current node as a successor of
126 /// the specified node.
127 void SUnit::removePred(const SDep &D) {
128 // Find the matching predecessor.
129 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
132 bool FoundSucc = false;
133 // Find the corresponding successor in N.
136 SUnit *N = D.getSUnit();
137 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
138 EE = N->Succs.end(); II != EE; ++II)
144 assert(FoundSucc && "Mismatching preds / succs lists!");
147 // Update the bookkeeping.
148 if (P.getKind() == SDep::Data) {
149 assert(NumPreds > 0 && "NumPreds will underflow!");
150 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
154 if (!N->isScheduled) {
155 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
159 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
162 if (P.getLatency() != 0) {
163 this->setDepthDirty();
170 void SUnit::setDepthDirty() {
171 if (!isDepthCurrent) return;
172 SmallVector<SUnit*, 8> WorkList;
173 WorkList.push_back(this);
175 SUnit *SU = WorkList.pop_back_val();
176 SU->isDepthCurrent = false;
177 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
178 E = SU->Succs.end(); I != E; ++I) {
179 SUnit *SuccSU = I->getSUnit();
180 if (SuccSU->isDepthCurrent)
181 WorkList.push_back(SuccSU);
183 } while (!WorkList.empty());
186 void SUnit::setHeightDirty() {
187 if (!isHeightCurrent) return;
188 SmallVector<SUnit*, 8> WorkList;
189 WorkList.push_back(this);
191 SUnit *SU = WorkList.pop_back_val();
192 SU->isHeightCurrent = false;
193 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
194 E = SU->Preds.end(); I != E; ++I) {
195 SUnit *PredSU = I->getSUnit();
196 if (PredSU->isHeightCurrent)
197 WorkList.push_back(PredSU);
199 } while (!WorkList.empty());
202 /// setDepthToAtLeast - Update this node's successors to reflect the
203 /// fact that this node's depth just increased.
205 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
206 if (NewDepth <= getDepth())
210 isDepthCurrent = true;
213 /// setHeightToAtLeast - Update this node's predecessors to reflect the
214 /// fact that this node's height just increased.
216 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
217 if (NewHeight <= getHeight())
221 isHeightCurrent = true;
224 /// ComputeDepth - Calculate the maximal path from the node to the exit.
226 void SUnit::ComputeDepth() {
227 SmallVector<SUnit*, 8> WorkList;
228 WorkList.push_back(this);
230 SUnit *Cur = WorkList.back();
233 unsigned MaxPredDepth = 0;
234 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
235 E = Cur->Preds.end(); I != E; ++I) {
236 SUnit *PredSU = I->getSUnit();
237 if (PredSU->isDepthCurrent)
238 MaxPredDepth = std::max(MaxPredDepth,
239 PredSU->Depth + I->getLatency());
242 WorkList.push_back(PredSU);
248 if (MaxPredDepth != Cur->Depth) {
249 Cur->setDepthDirty();
250 Cur->Depth = MaxPredDepth;
252 Cur->isDepthCurrent = true;
254 } while (!WorkList.empty());
257 /// ComputeHeight - Calculate the maximal path from the node to the entry.
259 void SUnit::ComputeHeight() {
260 SmallVector<SUnit*, 8> WorkList;
261 WorkList.push_back(this);
263 SUnit *Cur = WorkList.back();
266 unsigned MaxSuccHeight = 0;
267 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
268 E = Cur->Succs.end(); I != E; ++I) {
269 SUnit *SuccSU = I->getSUnit();
270 if (SuccSU->isHeightCurrent)
271 MaxSuccHeight = std::max(MaxSuccHeight,
272 SuccSU->Height + I->getLatency());
275 WorkList.push_back(SuccSU);
281 if (MaxSuccHeight != Cur->Height) {
282 Cur->setHeightDirty();
283 Cur->Height = MaxSuccHeight;
285 Cur->isHeightCurrent = true;
287 } while (!WorkList.empty());
290 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
291 /// a group of nodes flagged together.
292 void SUnit::dump(const ScheduleDAG *G) const {
293 dbgs() << "SU(" << NodeNum << "): ";
297 void SUnit::dumpAll(const ScheduleDAG *G) const {
300 dbgs() << " # preds left : " << NumPredsLeft << "\n";
301 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
302 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
303 dbgs() << " Latency : " << Latency << "\n";
304 dbgs() << " Depth : " << Depth << "\n";
305 dbgs() << " Height : " << Height << "\n";
307 if (Preds.size() != 0) {
308 dbgs() << " Predecessors:\n";
309 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
312 switch (I->getKind()) {
313 case SDep::Data: dbgs() << "val "; break;
314 case SDep::Anti: dbgs() << "anti"; break;
315 case SDep::Output: dbgs() << "out "; break;
316 case SDep::Order: dbgs() << "ch "; break;
319 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
320 if (I->isArtificial())
322 dbgs() << ": Latency=" << I->getLatency();
323 if (I->isAssignedRegDep())
324 dbgs() << " Reg=" << PrintReg(I->getReg());
328 if (Succs.size() != 0) {
329 dbgs() << " Successors:\n";
330 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
333 switch (I->getKind()) {
334 case SDep::Data: dbgs() << "val "; break;
335 case SDep::Anti: dbgs() << "anti"; break;
336 case SDep::Output: dbgs() << "out "; break;
337 case SDep::Order: dbgs() << "ch "; break;
340 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
341 if (I->isArtificial())
343 dbgs() << ": Latency=" << I->getLatency();
351 /// VerifySchedule - Verify that all SUnits were scheduled and that
352 /// their state is consistent.
354 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
355 bool AnyNotSched = false;
356 unsigned DeadNodes = 0;
358 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
359 if (!SUnits[i].isScheduled) {
360 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
365 dbgs() << "*** Scheduling failed! ***\n";
366 SUnits[i].dump(this);
367 dbgs() << "has not been scheduled!\n";
370 if (SUnits[i].isScheduled &&
371 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
374 dbgs() << "*** Scheduling failed! ***\n";
375 SUnits[i].dump(this);
376 dbgs() << "has an unexpected "
377 << (isBottomUp ? "Height" : "Depth") << " value!\n";
381 if (SUnits[i].NumSuccsLeft != 0) {
383 dbgs() << "*** Scheduling failed! ***\n";
384 SUnits[i].dump(this);
385 dbgs() << "has successors left!\n";
389 if (SUnits[i].NumPredsLeft != 0) {
391 dbgs() << "*** Scheduling failed! ***\n";
392 SUnits[i].dump(this);
393 dbgs() << "has predecessors left!\n";
398 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
401 assert(!AnyNotSched);
402 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
403 "The number of nodes scheduled doesn't match the expected number!");
407 /// InitDAGTopologicalSorting - create the initial topological
408 /// ordering from the DAG to be scheduled.
410 /// The idea of the algorithm is taken from
411 /// "Online algorithms for managing the topological order of
412 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
413 /// This is the MNR algorithm, which was first introduced by
414 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
415 /// "Maintaining a topological order under edge insertions".
417 /// Short description of the algorithm:
419 /// Topological ordering, ord, of a DAG maps each node to a topological
420 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
422 /// This means that if there is a path from the node X to the node Z,
423 /// then ord(X) < ord(Z).
425 /// This property can be used to check for reachability of nodes:
426 /// if Z is reachable from X, then an insertion of the edge Z->X would
429 /// The algorithm first computes a topological ordering for the DAG by
430 /// initializing the Index2Node and Node2Index arrays and then tries to keep
431 /// the ordering up-to-date after edge insertions by reordering the DAG.
433 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
434 /// the nodes reachable from Y, and then shifts them using Shift to lie
435 /// immediately after X in Index2Node.
436 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
437 unsigned DAGSize = SUnits.size();
438 std::vector<SUnit*> WorkList;
439 WorkList.reserve(DAGSize);
441 Index2Node.resize(DAGSize);
442 Node2Index.resize(DAGSize);
444 // Initialize the data structures.
445 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
446 SUnit *SU = &SUnits[i];
447 int NodeNum = SU->NodeNum;
448 unsigned Degree = SU->Succs.size();
449 // Temporarily use the Node2Index array as scratch space for degree counts.
450 Node2Index[NodeNum] = Degree;
452 // Is it a node without dependencies?
454 assert(SU->Succs.empty() && "SUnit should have no successors");
455 // Collect leaf nodes.
456 WorkList.push_back(SU);
461 while (!WorkList.empty()) {
462 SUnit *SU = WorkList.back();
464 Allocate(SU->NodeNum, --Id);
465 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
467 SUnit *SU = I->getSUnit();
468 if (!--Node2Index[SU->NodeNum])
469 // If all dependencies of the node are processed already,
470 // then the node can be computed now.
471 WorkList.push_back(SU);
475 Visited.resize(DAGSize);
478 // Check correctness of the ordering
479 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
480 SUnit *SU = &SUnits[i];
481 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
483 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
484 "Wrong topological sorting");
490 /// AddPred - Updates the topological ordering to accommodate an edge
491 /// to be added from SUnit X to SUnit Y.
492 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
493 int UpperBound, LowerBound;
494 LowerBound = Node2Index[Y->NodeNum];
495 UpperBound = Node2Index[X->NodeNum];
496 bool HasLoop = false;
497 // Is Ord(X) < Ord(Y) ?
498 if (LowerBound < UpperBound) {
499 // Update the topological order.
501 DFS(Y, UpperBound, HasLoop);
502 assert(!HasLoop && "Inserted edge creates a loop!");
503 // Recompute topological indexes.
504 Shift(Visited, LowerBound, UpperBound);
508 /// RemovePred - Updates the topological ordering to accommodate an
509 /// an edge to be removed from the specified node N from the predecessors
510 /// of the current node M.
511 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
512 // InitDAGTopologicalSorting();
515 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
516 /// all nodes affected by the edge insertion. These nodes will later get new
517 /// topological indexes by means of the Shift method.
518 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
520 std::vector<const SUnit*> WorkList;
521 WorkList.reserve(SUnits.size());
523 WorkList.push_back(SU);
525 SU = WorkList.back();
527 Visited.set(SU->NodeNum);
528 for (int I = SU->Succs.size()-1; I >= 0; --I) {
529 int s = SU->Succs[I].getSUnit()->NodeNum;
530 if (Node2Index[s] == UpperBound) {
534 // Visit successors if not already and in affected region.
535 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
536 WorkList.push_back(SU->Succs[I].getSUnit());
539 } while (!WorkList.empty());
542 /// Shift - Renumber the nodes so that the topological ordering is
544 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
550 for (i = LowerBound; i <= UpperBound; ++i) {
551 // w is node at topological index i.
552 int w = Index2Node[i];
553 if (Visited.test(w)) {
559 Allocate(w, i - shift);
563 for (unsigned j = 0; j < L.size(); ++j) {
564 Allocate(L[j], i - shift);
570 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
572 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
573 if (IsReachable(TargetSU, SU))
575 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
577 if (I->isAssignedRegDep() &&
578 IsReachable(TargetSU, I->getSUnit()))
583 /// IsReachable - Checks if SU is reachable from TargetSU.
584 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
585 const SUnit *TargetSU) {
586 // If insertion of the edge SU->TargetSU would create a cycle
587 // then there is a path from TargetSU to SU.
588 int UpperBound, LowerBound;
589 LowerBound = Node2Index[TargetSU->NodeNum];
590 UpperBound = Node2Index[SU->NodeNum];
591 bool HasLoop = false;
592 // Is Ord(TargetSU) < Ord(SU) ?
593 if (LowerBound < UpperBound) {
595 // There may be a path from TargetSU to SU. Check for it.
596 DFS(TargetSU, UpperBound, HasLoop);
601 /// Allocate - assign the topological index to the node n.
602 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
603 Node2Index[n] = index;
604 Index2Node[index] = n;
607 ScheduleDAGTopologicalSort::
608 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits) : SUnits(sunits) {}
610 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}