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->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 void 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();
111 /// removePred - This removes the specified edge as a pred of the current
112 /// node if it exists. It also removes the current node as a successor of
113 /// the specified node.
114 void SUnit::removePred(const SDep &D) {
115 // Find the matching predecessor.
116 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
119 bool FoundSucc = false;
120 // Find the corresponding successor in N.
123 SUnit *N = D.getSUnit();
124 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
125 EE = N->Succs.end(); II != EE; ++II)
131 assert(FoundSucc && "Mismatching preds / succs lists!");
133 // Update the bookkeeping.
134 if (P.getKind() == SDep::Data) {
135 assert(NumPreds > 0 && "NumPreds will underflow!");
136 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
140 if (!N->isScheduled) {
141 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
145 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
148 if (P.getLatency() != 0) {
149 this->setDepthDirty();
156 void SUnit::setDepthDirty() {
157 if (!isDepthCurrent) return;
158 SmallVector<SUnit*, 8> WorkList;
159 WorkList.push_back(this);
161 SUnit *SU = WorkList.pop_back_val();
162 SU->isDepthCurrent = false;
163 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
164 E = SU->Succs.end(); I != E; ++I) {
165 SUnit *SuccSU = I->getSUnit();
166 if (SuccSU->isDepthCurrent)
167 WorkList.push_back(SuccSU);
169 } while (!WorkList.empty());
172 void SUnit::setHeightDirty() {
173 if (!isHeightCurrent) return;
174 SmallVector<SUnit*, 8> WorkList;
175 WorkList.push_back(this);
177 SUnit *SU = WorkList.pop_back_val();
178 SU->isHeightCurrent = false;
179 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
180 E = SU->Preds.end(); I != E; ++I) {
181 SUnit *PredSU = I->getSUnit();
182 if (PredSU->isHeightCurrent)
183 WorkList.push_back(PredSU);
185 } while (!WorkList.empty());
188 /// setDepthToAtLeast - Update this node's successors to reflect the
189 /// fact that this node's depth just increased.
191 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
192 if (NewDepth <= getDepth())
196 isDepthCurrent = true;
199 /// setHeightToAtLeast - Update this node's predecessors to reflect the
200 /// fact that this node's height just increased.
202 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
203 if (NewHeight <= getHeight())
207 isHeightCurrent = true;
210 /// ComputeDepth - Calculate the maximal path from the node to the exit.
212 void SUnit::ComputeDepth() {
213 SmallVector<SUnit*, 8> WorkList;
214 WorkList.push_back(this);
216 SUnit *Cur = WorkList.back();
219 unsigned MaxPredDepth = 0;
220 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
221 E = Cur->Preds.end(); I != E; ++I) {
222 SUnit *PredSU = I->getSUnit();
223 if (PredSU->isDepthCurrent)
224 MaxPredDepth = std::max(MaxPredDepth,
225 PredSU->Depth + I->getLatency());
228 WorkList.push_back(PredSU);
234 if (MaxPredDepth != Cur->Depth) {
235 Cur->setDepthDirty();
236 Cur->Depth = MaxPredDepth;
238 Cur->isDepthCurrent = true;
240 } while (!WorkList.empty());
243 /// ComputeHeight - Calculate the maximal path from the node to the entry.
245 void SUnit::ComputeHeight() {
246 SmallVector<SUnit*, 8> WorkList;
247 WorkList.push_back(this);
249 SUnit *Cur = WorkList.back();
252 unsigned MaxSuccHeight = 0;
253 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
254 E = Cur->Succs.end(); I != E; ++I) {
255 SUnit *SuccSU = I->getSUnit();
256 if (SuccSU->isHeightCurrent)
257 MaxSuccHeight = std::max(MaxSuccHeight,
258 SuccSU->Height + I->getLatency());
261 WorkList.push_back(SuccSU);
267 if (MaxSuccHeight != Cur->Height) {
268 Cur->setHeightDirty();
269 Cur->Height = MaxSuccHeight;
271 Cur->isHeightCurrent = true;
273 } while (!WorkList.empty());
276 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
277 /// a group of nodes flagged together.
278 void SUnit::dump(const ScheduleDAG *G) const {
279 dbgs() << "SU(" << NodeNum << "): ";
283 void SUnit::dumpAll(const ScheduleDAG *G) const {
286 dbgs() << " # preds left : " << NumPredsLeft << "\n";
287 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
288 dbgs() << " Latency : " << Latency << "\n";
289 dbgs() << " Depth : " << Depth << "\n";
290 dbgs() << " Height : " << Height << "\n";
292 if (Preds.size() != 0) {
293 dbgs() << " Predecessors:\n";
294 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
297 switch (I->getKind()) {
298 case SDep::Data: dbgs() << "val "; break;
299 case SDep::Anti: dbgs() << "anti"; break;
300 case SDep::Output: dbgs() << "out "; break;
301 case SDep::Order: dbgs() << "ch "; break;
304 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
305 if (I->isArtificial())
307 dbgs() << ": Latency=" << I->getLatency();
311 if (Succs.size() != 0) {
312 dbgs() << " Successors:\n";
313 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
316 switch (I->getKind()) {
317 case SDep::Data: dbgs() << "val "; break;
318 case SDep::Anti: dbgs() << "anti"; break;
319 case SDep::Output: dbgs() << "out "; break;
320 case SDep::Order: dbgs() << "ch "; break;
323 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
324 if (I->isArtificial())
326 dbgs() << ": Latency=" << I->getLatency();
334 /// VerifySchedule - Verify that all SUnits were scheduled and that
335 /// their state is consistent.
337 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
338 bool AnyNotSched = false;
339 unsigned DeadNodes = 0;
341 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
342 if (!SUnits[i].isScheduled) {
343 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
348 dbgs() << "*** Scheduling failed! ***\n";
349 SUnits[i].dump(this);
350 dbgs() << "has not been scheduled!\n";
353 if (SUnits[i].isScheduled &&
354 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
357 dbgs() << "*** Scheduling failed! ***\n";
358 SUnits[i].dump(this);
359 dbgs() << "has an unexpected "
360 << (isBottomUp ? "Height" : "Depth") << " value!\n";
364 if (SUnits[i].NumSuccsLeft != 0) {
366 dbgs() << "*** Scheduling failed! ***\n";
367 SUnits[i].dump(this);
368 dbgs() << "has successors left!\n";
372 if (SUnits[i].NumPredsLeft != 0) {
374 dbgs() << "*** Scheduling failed! ***\n";
375 SUnits[i].dump(this);
376 dbgs() << "has predecessors left!\n";
381 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
384 assert(!AnyNotSched);
385 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
386 "The number of nodes scheduled doesn't match the expected number!");
390 /// InitDAGTopologicalSorting - create the initial topological
391 /// ordering from the DAG to be scheduled.
393 /// The idea of the algorithm is taken from
394 /// "Online algorithms for managing the topological order of
395 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
396 /// This is the MNR algorithm, which was first introduced by
397 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
398 /// "Maintaining a topological order under edge insertions".
400 /// Short description of the algorithm:
402 /// Topological ordering, ord, of a DAG maps each node to a topological
403 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
405 /// This means that if there is a path from the node X to the node Z,
406 /// then ord(X) < ord(Z).
408 /// This property can be used to check for reachability of nodes:
409 /// if Z is reachable from X, then an insertion of the edge Z->X would
412 /// The algorithm first computes a topological ordering for the DAG by
413 /// initializing the Index2Node and Node2Index arrays and then tries to keep
414 /// the ordering up-to-date after edge insertions by reordering the DAG.
416 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
417 /// the nodes reachable from Y, and then shifts them using Shift to lie
418 /// immediately after X in Index2Node.
419 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
420 unsigned DAGSize = SUnits.size();
421 std::vector<SUnit*> WorkList;
422 WorkList.reserve(DAGSize);
424 Index2Node.resize(DAGSize);
425 Node2Index.resize(DAGSize);
427 // Initialize the data structures.
428 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
429 SUnit *SU = &SUnits[i];
430 int NodeNum = SU->NodeNum;
431 unsigned Degree = SU->Succs.size();
432 // Temporarily use the Node2Index array as scratch space for degree counts.
433 Node2Index[NodeNum] = Degree;
435 // Is it a node without dependencies?
437 assert(SU->Succs.empty() && "SUnit should have no successors");
438 // Collect leaf nodes.
439 WorkList.push_back(SU);
444 while (!WorkList.empty()) {
445 SUnit *SU = WorkList.back();
447 Allocate(SU->NodeNum, --Id);
448 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
450 SUnit *SU = I->getSUnit();
451 if (!--Node2Index[SU->NodeNum])
452 // If all dependencies of the node are processed already,
453 // then the node can be computed now.
454 WorkList.push_back(SU);
458 Visited.resize(DAGSize);
461 // Check correctness of the ordering
462 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
463 SUnit *SU = &SUnits[i];
464 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
466 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
467 "Wrong topological sorting");
473 /// AddPred - Updates the topological ordering to accomodate an edge
474 /// to be added from SUnit X to SUnit Y.
475 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
476 int UpperBound, LowerBound;
477 LowerBound = Node2Index[Y->NodeNum];
478 UpperBound = Node2Index[X->NodeNum];
479 bool HasLoop = false;
480 // Is Ord(X) < Ord(Y) ?
481 if (LowerBound < UpperBound) {
482 // Update the topological order.
484 DFS(Y, UpperBound, HasLoop);
485 assert(!HasLoop && "Inserted edge creates a loop!");
486 // Recompute topological indexes.
487 Shift(Visited, LowerBound, UpperBound);
491 /// RemovePred - Updates the topological ordering to accomodate an
492 /// an edge to be removed from the specified node N from the predecessors
493 /// of the current node M.
494 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
495 // InitDAGTopologicalSorting();
498 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
499 /// all nodes affected by the edge insertion. These nodes will later get new
500 /// topological indexes by means of the Shift method.
501 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
503 std::vector<const SUnit*> WorkList;
504 WorkList.reserve(SUnits.size());
506 WorkList.push_back(SU);
508 SU = WorkList.back();
510 Visited.set(SU->NodeNum);
511 for (int I = SU->Succs.size()-1; I >= 0; --I) {
512 int s = SU->Succs[I].getSUnit()->NodeNum;
513 if (Node2Index[s] == UpperBound) {
517 // Visit successors if not already and in affected region.
518 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
519 WorkList.push_back(SU->Succs[I].getSUnit());
522 } while (!WorkList.empty());
525 /// Shift - Renumber the nodes so that the topological ordering is
527 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
533 for (i = LowerBound; i <= UpperBound; ++i) {
534 // w is node at topological index i.
535 int w = Index2Node[i];
536 if (Visited.test(w)) {
542 Allocate(w, i - shift);
546 for (unsigned j = 0; j < L.size(); ++j) {
547 Allocate(L[j], i - shift);
553 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
555 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
556 if (IsReachable(TargetSU, SU))
558 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
560 if (I->isAssignedRegDep() &&
561 IsReachable(TargetSU, I->getSUnit()))
566 /// IsReachable - Checks if SU is reachable from TargetSU.
567 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
568 const SUnit *TargetSU) {
569 // If insertion of the edge SU->TargetSU would create a cycle
570 // then there is a path from TargetSU to SU.
571 int UpperBound, LowerBound;
572 LowerBound = Node2Index[TargetSU->NodeNum];
573 UpperBound = Node2Index[SU->NodeNum];
574 bool HasLoop = false;
575 // Is Ord(TargetSU) < Ord(SU) ?
576 if (LowerBound < UpperBound) {
578 // There may be a path from TargetSU to SU. Check for it.
579 DFS(TargetSU, UpperBound, HasLoop);
584 /// Allocate - assign the topological index to the node n.
585 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
586 Node2Index[n] = index;
587 Index2Node[index] = n;
590 ScheduleDAGTopologicalSort::
591 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits) : SUnits(sunits) {}
593 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}