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 #include "llvm/CodeGen/ScheduleDAG.h"
16 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
17 #include "llvm/CodeGen/SelectionDAGNodes.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetSubtargetInfo.h"
28 #define DEBUG_TYPE "pre-RA-sched"
31 static cl::opt<bool> StressSchedOpt(
32 "stress-sched", cl::Hidden, cl::init(false),
33 cl::desc("Stress test instruction scheduling"));
36 void SchedulingPriorityQueue::anchor() { }
38 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
39 : TM(mf.getTarget()), TII(mf.getSubtarget().getInstrInfo()),
40 TRI(mf.getSubtarget().getRegisterInfo()), MF(mf),
41 MRI(mf.getRegInfo()), EntrySU(), ExitSU() {
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 nullptr;
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 dependence, don't add a redundant one.
67 for (SmallVectorImpl<SDep>::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 (SmallVectorImpl<SDep>::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 (SmallVectorImpl<SDep>::iterator I = Preds.begin(), E = Preds.end();
138 // Find the corresponding successor in N.
141 SUnit *N = D.getSUnit();
142 SmallVectorImpl<SDep>::iterator Succ = std::find(N->Succs.begin(),
144 assert(Succ != N->Succs.end() && "Mismatching preds / succs lists!");
145 N->Succs.erase(Succ);
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) {
158 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
166 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
170 if (P.getLatency() != 0) {
171 this->setDepthDirty();
178 void SUnit::setDepthDirty() {
179 if (!isDepthCurrent) return;
180 SmallVector<SUnit*, 8> WorkList;
181 WorkList.push_back(this);
183 SUnit *SU = WorkList.pop_back_val();
184 SU->isDepthCurrent = false;
185 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
186 E = SU->Succs.end(); I != E; ++I) {
187 SUnit *SuccSU = I->getSUnit();
188 if (SuccSU->isDepthCurrent)
189 WorkList.push_back(SuccSU);
191 } while (!WorkList.empty());
194 void SUnit::setHeightDirty() {
195 if (!isHeightCurrent) return;
196 SmallVector<SUnit*, 8> WorkList;
197 WorkList.push_back(this);
199 SUnit *SU = WorkList.pop_back_val();
200 SU->isHeightCurrent = false;
201 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
202 E = SU->Preds.end(); I != E; ++I) {
203 SUnit *PredSU = I->getSUnit();
204 if (PredSU->isHeightCurrent)
205 WorkList.push_back(PredSU);
207 } while (!WorkList.empty());
210 /// setDepthToAtLeast - Update this node's successors to reflect the
211 /// fact that this node's depth just increased.
213 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
214 if (NewDepth <= getDepth())
218 isDepthCurrent = true;
221 /// setHeightToAtLeast - Update this node's predecessors to reflect the
222 /// fact that this node's height just increased.
224 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
225 if (NewHeight <= getHeight())
229 isHeightCurrent = true;
232 /// ComputeDepth - Calculate the maximal path from the node to the exit.
234 void SUnit::ComputeDepth() {
235 SmallVector<SUnit*, 8> WorkList;
236 WorkList.push_back(this);
238 SUnit *Cur = WorkList.back();
241 unsigned MaxPredDepth = 0;
242 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
243 E = Cur->Preds.end(); I != E; ++I) {
244 SUnit *PredSU = I->getSUnit();
245 if (PredSU->isDepthCurrent)
246 MaxPredDepth = std::max(MaxPredDepth,
247 PredSU->Depth + I->getLatency());
250 WorkList.push_back(PredSU);
256 if (MaxPredDepth != Cur->Depth) {
257 Cur->setDepthDirty();
258 Cur->Depth = MaxPredDepth;
260 Cur->isDepthCurrent = true;
262 } while (!WorkList.empty());
265 /// ComputeHeight - Calculate the maximal path from the node to the entry.
267 void SUnit::ComputeHeight() {
268 SmallVector<SUnit*, 8> WorkList;
269 WorkList.push_back(this);
271 SUnit *Cur = WorkList.back();
274 unsigned MaxSuccHeight = 0;
275 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
276 E = Cur->Succs.end(); I != E; ++I) {
277 SUnit *SuccSU = I->getSUnit();
278 if (SuccSU->isHeightCurrent)
279 MaxSuccHeight = std::max(MaxSuccHeight,
280 SuccSU->Height + I->getLatency());
283 WorkList.push_back(SuccSU);
289 if (MaxSuccHeight != Cur->Height) {
290 Cur->setHeightDirty();
291 Cur->Height = MaxSuccHeight;
293 Cur->isHeightCurrent = true;
295 } while (!WorkList.empty());
298 void SUnit::biasCriticalPath() {
302 SUnit::pred_iterator BestI = Preds.begin();
303 unsigned MaxDepth = BestI->getSUnit()->getDepth();
304 for (SUnit::pred_iterator I = std::next(BestI), E = Preds.end(); I != E;
306 if (I->getKind() == SDep::Data && I->getSUnit()->getDepth() > MaxDepth)
309 if (BestI != Preds.begin())
310 std::swap(*Preds.begin(), *BestI);
313 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
314 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
315 /// a group of nodes flagged together.
316 void SUnit::dump(const ScheduleDAG *G) const {
317 dbgs() << "SU(" << NodeNum << "): ";
321 void SUnit::dumpAll(const ScheduleDAG *G) const {
324 dbgs() << " # preds left : " << NumPredsLeft << "\n";
325 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
327 dbgs() << " # weak preds left : " << WeakPredsLeft << "\n";
329 dbgs() << " # weak succs left : " << WeakSuccsLeft << "\n";
330 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
331 dbgs() << " Latency : " << Latency << "\n";
332 dbgs() << " Depth : " << getDepth() << "\n";
333 dbgs() << " Height : " << getHeight() << "\n";
335 if (Preds.size() != 0) {
336 dbgs() << " Predecessors:\n";
337 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
340 switch (I->getKind()) {
341 case SDep::Data: dbgs() << "val "; break;
342 case SDep::Anti: dbgs() << "anti"; break;
343 case SDep::Output: dbgs() << "out "; break;
344 case SDep::Order: dbgs() << "ch "; break;
346 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
347 if (I->isArtificial())
349 dbgs() << ": Latency=" << I->getLatency();
350 if (I->isAssignedRegDep())
351 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
355 if (Succs.size() != 0) {
356 dbgs() << " Successors:\n";
357 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
360 switch (I->getKind()) {
361 case SDep::Data: dbgs() << "val "; break;
362 case SDep::Anti: dbgs() << "anti"; break;
363 case SDep::Output: dbgs() << "out "; break;
364 case SDep::Order: dbgs() << "ch "; break;
366 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
367 if (I->isArtificial())
369 dbgs() << ": Latency=" << I->getLatency();
370 if (I->isAssignedRegDep())
371 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
380 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
381 /// their state is consistent. Return the number of scheduled nodes.
383 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
384 bool AnyNotSched = false;
385 unsigned DeadNodes = 0;
386 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
387 if (!SUnits[i].isScheduled) {
388 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
393 dbgs() << "*** Scheduling failed! ***\n";
394 SUnits[i].dump(this);
395 dbgs() << "has not been scheduled!\n";
398 if (SUnits[i].isScheduled &&
399 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
402 dbgs() << "*** Scheduling failed! ***\n";
403 SUnits[i].dump(this);
404 dbgs() << "has an unexpected "
405 << (isBottomUp ? "Height" : "Depth") << " value!\n";
409 if (SUnits[i].NumSuccsLeft != 0) {
411 dbgs() << "*** Scheduling failed! ***\n";
412 SUnits[i].dump(this);
413 dbgs() << "has successors left!\n";
417 if (SUnits[i].NumPredsLeft != 0) {
419 dbgs() << "*** Scheduling failed! ***\n";
420 SUnits[i].dump(this);
421 dbgs() << "has predecessors left!\n";
426 assert(!AnyNotSched);
427 return SUnits.size() - DeadNodes;
431 /// InitDAGTopologicalSorting - create the initial topological
432 /// ordering from the DAG to be scheduled.
434 /// The idea of the algorithm is taken from
435 /// "Online algorithms for managing the topological order of
436 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
437 /// This is the MNR algorithm, which was first introduced by
438 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
439 /// "Maintaining a topological order under edge insertions".
441 /// Short description of the algorithm:
443 /// Topological ordering, ord, of a DAG maps each node to a topological
444 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
446 /// This means that if there is a path from the node X to the node Z,
447 /// then ord(X) < ord(Z).
449 /// This property can be used to check for reachability of nodes:
450 /// if Z is reachable from X, then an insertion of the edge Z->X would
453 /// The algorithm first computes a topological ordering for the DAG by
454 /// initializing the Index2Node and Node2Index arrays and then tries to keep
455 /// the ordering up-to-date after edge insertions by reordering the DAG.
457 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
458 /// the nodes reachable from Y, and then shifts them using Shift to lie
459 /// immediately after X in Index2Node.
460 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
461 unsigned DAGSize = SUnits.size();
462 std::vector<SUnit*> WorkList;
463 WorkList.reserve(DAGSize);
465 Index2Node.resize(DAGSize);
466 Node2Index.resize(DAGSize);
468 // Initialize the data structures.
470 WorkList.push_back(ExitSU);
471 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
472 SUnit *SU = &SUnits[i];
473 int NodeNum = SU->NodeNum;
474 unsigned Degree = SU->Succs.size();
475 // Temporarily use the Node2Index array as scratch space for degree counts.
476 Node2Index[NodeNum] = Degree;
478 // Is it a node without dependencies?
480 assert(SU->Succs.empty() && "SUnit should have no successors");
481 // Collect leaf nodes.
482 WorkList.push_back(SU);
487 while (!WorkList.empty()) {
488 SUnit *SU = WorkList.back();
490 if (SU->NodeNum < DAGSize)
491 Allocate(SU->NodeNum, --Id);
492 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
494 SUnit *SU = I->getSUnit();
495 if (SU->NodeNum < DAGSize && !--Node2Index[SU->NodeNum])
496 // If all dependencies of the node are processed already,
497 // then the node can be computed now.
498 WorkList.push_back(SU);
502 Visited.resize(DAGSize);
505 // Check correctness of the ordering
506 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
507 SUnit *SU = &SUnits[i];
508 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
510 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
511 "Wrong topological sorting");
517 /// AddPred - Updates the topological ordering to accommodate an edge
518 /// to be added from SUnit X to SUnit Y.
519 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
520 int UpperBound, LowerBound;
521 LowerBound = Node2Index[Y->NodeNum];
522 UpperBound = Node2Index[X->NodeNum];
523 bool HasLoop = false;
524 // Is Ord(X) < Ord(Y) ?
525 if (LowerBound < UpperBound) {
526 // Update the topological order.
528 DFS(Y, UpperBound, HasLoop);
529 assert(!HasLoop && "Inserted edge creates a loop!");
530 // Recompute topological indexes.
531 Shift(Visited, LowerBound, UpperBound);
535 /// RemovePred - Updates the topological ordering to accommodate an
536 /// an edge to be removed from the specified node N from the predecessors
537 /// of the current node M.
538 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
539 // InitDAGTopologicalSorting();
542 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
543 /// all nodes affected by the edge insertion. These nodes will later get new
544 /// topological indexes by means of the Shift method.
545 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
547 std::vector<const SUnit*> WorkList;
548 WorkList.reserve(SUnits.size());
550 WorkList.push_back(SU);
552 SU = WorkList.back();
554 Visited.set(SU->NodeNum);
555 for (int I = SU->Succs.size()-1; I >= 0; --I) {
556 unsigned s = SU->Succs[I].getSUnit()->NodeNum;
557 // Edges to non-SUnits are allowed but ignored (e.g. ExitSU).
558 if (s >= Node2Index.size())
560 if (Node2Index[s] == UpperBound) {
564 // Visit successors if not already and in affected region.
565 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
566 WorkList.push_back(SU->Succs[I].getSUnit());
569 } while (!WorkList.empty());
572 /// Shift - Renumber the nodes so that the topological ordering is
574 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
580 for (i = LowerBound; i <= UpperBound; ++i) {
581 // w is node at topological index i.
582 int w = Index2Node[i];
583 if (Visited.test(w)) {
589 Allocate(w, i - shift);
593 for (unsigned j = 0; j < L.size(); ++j) {
594 Allocate(L[j], i - shift);
600 /// WillCreateCycle - Returns true if adding an edge to TargetSU from SU will
601 /// create a cycle. If so, it is not safe to call AddPred(TargetSU, SU).
602 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *TargetSU, SUnit *SU) {
603 // Is SU reachable from TargetSU via successor edges?
604 if (IsReachable(SU, TargetSU))
606 for (SUnit::pred_iterator
607 I = TargetSU->Preds.begin(), E = TargetSU->Preds.end(); I != E; ++I)
608 if (I->isAssignedRegDep() &&
609 IsReachable(SU, I->getSUnit()))
614 /// IsReachable - Checks if SU is reachable from TargetSU.
615 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
616 const SUnit *TargetSU) {
617 // If insertion of the edge SU->TargetSU would create a cycle
618 // then there is a path from TargetSU to SU.
619 int UpperBound, LowerBound;
620 LowerBound = Node2Index[TargetSU->NodeNum];
621 UpperBound = Node2Index[SU->NodeNum];
622 bool HasLoop = false;
623 // Is Ord(TargetSU) < Ord(SU) ?
624 if (LowerBound < UpperBound) {
626 // There may be a path from TargetSU to SU. Check for it.
627 DFS(TargetSU, UpperBound, HasLoop);
632 /// Allocate - assign the topological index to the node n.
633 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
634 Node2Index[n] = index;
635 Index2Node[index] = n;
638 ScheduleDAGTopologicalSort::
639 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits, SUnit *exitsu)
640 : SUnits(sunits), ExitSU(exitsu) {}
642 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}