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 = find(N->Succs, P);
143 assert(Succ != N->Succs.end() && "Mismatching preds / succs lists!");
144 N->Succs.erase(Succ);
146 // Update the bookkeeping.
147 if (P.getKind() == SDep::Data) {
148 assert(NumPreds > 0 && "NumPreds will underflow!");
149 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
153 if (!N->isScheduled) {
157 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
165 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
169 if (P.getLatency() != 0) {
170 this->setDepthDirty();
177 void SUnit::setDepthDirty() {
178 if (!isDepthCurrent) return;
179 SmallVector<SUnit*, 8> WorkList;
180 WorkList.push_back(this);
182 SUnit *SU = WorkList.pop_back_val();
183 SU->isDepthCurrent = false;
184 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
185 E = SU->Succs.end(); I != E; ++I) {
186 SUnit *SuccSU = I->getSUnit();
187 if (SuccSU->isDepthCurrent)
188 WorkList.push_back(SuccSU);
190 } while (!WorkList.empty());
193 void SUnit::setHeightDirty() {
194 if (!isHeightCurrent) return;
195 SmallVector<SUnit*, 8> WorkList;
196 WorkList.push_back(this);
198 SUnit *SU = WorkList.pop_back_val();
199 SU->isHeightCurrent = false;
200 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
201 E = SU->Preds.end(); I != E; ++I) {
202 SUnit *PredSU = I->getSUnit();
203 if (PredSU->isHeightCurrent)
204 WorkList.push_back(PredSU);
206 } while (!WorkList.empty());
209 /// setDepthToAtLeast - Update this node's successors to reflect the
210 /// fact that this node's depth just increased.
212 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
213 if (NewDepth <= getDepth())
217 isDepthCurrent = true;
220 /// setHeightToAtLeast - Update this node's predecessors to reflect the
221 /// fact that this node's height just increased.
223 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
224 if (NewHeight <= getHeight())
228 isHeightCurrent = true;
231 /// ComputeDepth - Calculate the maximal path from the node to the exit.
233 void SUnit::ComputeDepth() {
234 SmallVector<SUnit*, 8> WorkList;
235 WorkList.push_back(this);
237 SUnit *Cur = WorkList.back();
240 unsigned MaxPredDepth = 0;
241 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
242 E = Cur->Preds.end(); I != E; ++I) {
243 SUnit *PredSU = I->getSUnit();
244 if (PredSU->isDepthCurrent)
245 MaxPredDepth = std::max(MaxPredDepth,
246 PredSU->Depth + I->getLatency());
249 WorkList.push_back(PredSU);
255 if (MaxPredDepth != Cur->Depth) {
256 Cur->setDepthDirty();
257 Cur->Depth = MaxPredDepth;
259 Cur->isDepthCurrent = true;
261 } while (!WorkList.empty());
264 /// ComputeHeight - Calculate the maximal path from the node to the entry.
266 void SUnit::ComputeHeight() {
267 SmallVector<SUnit*, 8> WorkList;
268 WorkList.push_back(this);
270 SUnit *Cur = WorkList.back();
273 unsigned MaxSuccHeight = 0;
274 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
275 E = Cur->Succs.end(); I != E; ++I) {
276 SUnit *SuccSU = I->getSUnit();
277 if (SuccSU->isHeightCurrent)
278 MaxSuccHeight = std::max(MaxSuccHeight,
279 SuccSU->Height + I->getLatency());
282 WorkList.push_back(SuccSU);
288 if (MaxSuccHeight != Cur->Height) {
289 Cur->setHeightDirty();
290 Cur->Height = MaxSuccHeight;
292 Cur->isHeightCurrent = true;
294 } while (!WorkList.empty());
297 void SUnit::biasCriticalPath() {
301 SUnit::pred_iterator BestI = Preds.begin();
302 unsigned MaxDepth = BestI->getSUnit()->getDepth();
303 for (SUnit::pred_iterator I = std::next(BestI), E = Preds.end(); I != E;
305 if (I->getKind() == SDep::Data && I->getSUnit()->getDepth() > MaxDepth)
308 if (BestI != Preds.begin())
309 std::swap(*Preds.begin(), *BestI);
312 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
313 void SUnit::print(raw_ostream &OS, const ScheduleDAG *DAG) const {
314 if (this == &DAG->ExitSU)
316 else if (this == &DAG->EntrySU)
319 OS << "SU(" << NodeNum << ")";
322 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
323 /// a group of nodes flagged together.
324 void SUnit::dump(const ScheduleDAG *G) const {
330 void SUnit::dumpAll(const ScheduleDAG *G) const {
333 dbgs() << " # preds left : " << NumPredsLeft << "\n";
334 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
336 dbgs() << " # weak preds left : " << WeakPredsLeft << "\n";
338 dbgs() << " # weak succs left : " << WeakSuccsLeft << "\n";
339 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n";
340 dbgs() << " Latency : " << Latency << "\n";
341 dbgs() << " Depth : " << getDepth() << "\n";
342 dbgs() << " Height : " << getHeight() << "\n";
344 if (Preds.size() != 0) {
345 dbgs() << " Predecessors:\n";
346 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
349 switch (I->getKind()) {
350 case SDep::Data: dbgs() << "data "; break;
351 case SDep::Anti: dbgs() << "anti "; break;
352 case SDep::Output: dbgs() << "out "; break;
353 case SDep::Order: dbgs() << "ord "; break;
355 I->getSUnit()->print(dbgs(), G);
356 if (I->isArtificial())
358 dbgs() << ": Latency=" << I->getLatency();
359 if (I->isAssignedRegDep())
360 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
364 if (Succs.size() != 0) {
365 dbgs() << " Successors:\n";
366 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
369 switch (I->getKind()) {
370 case SDep::Data: dbgs() << "data "; break;
371 case SDep::Anti: dbgs() << "anti "; break;
372 case SDep::Output: dbgs() << "out "; break;
373 case SDep::Order: dbgs() << "ord "; break;
375 I->getSUnit()->print(dbgs(), G);
376 if (I->isArtificial())
378 dbgs() << ": Latency=" << I->getLatency();
379 if (I->isAssignedRegDep())
380 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
388 /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
389 /// their state is consistent. Return the number of scheduled nodes.
391 unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
392 bool AnyNotSched = false;
393 unsigned DeadNodes = 0;
394 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
395 if (!SUnits[i].isScheduled) {
396 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
401 dbgs() << "*** Scheduling failed! ***\n";
402 SUnits[i].dump(this);
403 dbgs() << "has not been scheduled!\n";
406 if (SUnits[i].isScheduled &&
407 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
410 dbgs() << "*** Scheduling failed! ***\n";
411 SUnits[i].dump(this);
412 dbgs() << "has an unexpected "
413 << (isBottomUp ? "Height" : "Depth") << " value!\n";
417 if (SUnits[i].NumSuccsLeft != 0) {
419 dbgs() << "*** Scheduling failed! ***\n";
420 SUnits[i].dump(this);
421 dbgs() << "has successors left!\n";
425 if (SUnits[i].NumPredsLeft != 0) {
427 dbgs() << "*** Scheduling failed! ***\n";
428 SUnits[i].dump(this);
429 dbgs() << "has predecessors left!\n";
434 assert(!AnyNotSched);
435 return SUnits.size() - DeadNodes;
439 /// InitDAGTopologicalSorting - create the initial topological
440 /// ordering from the DAG to be scheduled.
442 /// The idea of the algorithm is taken from
443 /// "Online algorithms for managing the topological order of
444 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
445 /// This is the MNR algorithm, which was first introduced by
446 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
447 /// "Maintaining a topological order under edge insertions".
449 /// Short description of the algorithm:
451 /// Topological ordering, ord, of a DAG maps each node to a topological
452 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
454 /// This means that if there is a path from the node X to the node Z,
455 /// then ord(X) < ord(Z).
457 /// This property can be used to check for reachability of nodes:
458 /// if Z is reachable from X, then an insertion of the edge Z->X would
461 /// The algorithm first computes a topological ordering for the DAG by
462 /// initializing the Index2Node and Node2Index arrays and then tries to keep
463 /// the ordering up-to-date after edge insertions by reordering the DAG.
465 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
466 /// the nodes reachable from Y, and then shifts them using Shift to lie
467 /// immediately after X in Index2Node.
468 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
469 unsigned DAGSize = SUnits.size();
470 std::vector<SUnit*> WorkList;
471 WorkList.reserve(DAGSize);
473 Index2Node.resize(DAGSize);
474 Node2Index.resize(DAGSize);
476 // Initialize the data structures.
478 WorkList.push_back(ExitSU);
479 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
480 SUnit *SU = &SUnits[i];
481 int NodeNum = SU->NodeNum;
482 unsigned Degree = SU->Succs.size();
483 // Temporarily use the Node2Index array as scratch space for degree counts.
484 Node2Index[NodeNum] = Degree;
486 // Is it a node without dependencies?
488 assert(SU->Succs.empty() && "SUnit should have no successors");
489 // Collect leaf nodes.
490 WorkList.push_back(SU);
495 while (!WorkList.empty()) {
496 SUnit *SU = WorkList.back();
498 if (SU->NodeNum < DAGSize)
499 Allocate(SU->NodeNum, --Id);
500 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
502 SUnit *SU = I->getSUnit();
503 if (SU->NodeNum < DAGSize && !--Node2Index[SU->NodeNum])
504 // If all dependencies of the node are processed already,
505 // then the node can be computed now.
506 WorkList.push_back(SU);
510 Visited.resize(DAGSize);
513 // Check correctness of the ordering
514 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
515 SUnit *SU = &SUnits[i];
516 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
518 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
519 "Wrong topological sorting");
525 /// AddPred - Updates the topological ordering to accommodate an edge
526 /// to be added from SUnit X to SUnit Y.
527 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
528 int UpperBound, LowerBound;
529 LowerBound = Node2Index[Y->NodeNum];
530 UpperBound = Node2Index[X->NodeNum];
531 bool HasLoop = false;
532 // Is Ord(X) < Ord(Y) ?
533 if (LowerBound < UpperBound) {
534 // Update the topological order.
536 DFS(Y, UpperBound, HasLoop);
537 assert(!HasLoop && "Inserted edge creates a loop!");
538 // Recompute topological indexes.
539 Shift(Visited, LowerBound, UpperBound);
543 /// RemovePred - Updates the topological ordering to accommodate an
544 /// an edge to be removed from the specified node N from the predecessors
545 /// of the current node M.
546 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
547 // InitDAGTopologicalSorting();
550 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
551 /// all nodes affected by the edge insertion. These nodes will later get new
552 /// topological indexes by means of the Shift method.
553 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
555 std::vector<const SUnit*> WorkList;
556 WorkList.reserve(SUnits.size());
558 WorkList.push_back(SU);
560 SU = WorkList.back();
562 Visited.set(SU->NodeNum);
563 for (int I = SU->Succs.size()-1; I >= 0; --I) {
564 unsigned s = SU->Succs[I].getSUnit()->NodeNum;
565 // Edges to non-SUnits are allowed but ignored (e.g. ExitSU).
566 if (s >= Node2Index.size())
568 if (Node2Index[s] == UpperBound) {
572 // Visit successors if not already and in affected region.
573 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
574 WorkList.push_back(SU->Succs[I].getSUnit());
577 } while (!WorkList.empty());
580 /// Shift - Renumber the nodes so that the topological ordering is
582 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
588 for (i = LowerBound; i <= UpperBound; ++i) {
589 // w is node at topological index i.
590 int w = Index2Node[i];
591 if (Visited.test(w)) {
597 Allocate(w, i - shift);
601 for (unsigned j = 0; j < L.size(); ++j) {
602 Allocate(L[j], i - shift);
608 /// WillCreateCycle - Returns true if adding an edge to TargetSU from SU will
609 /// create a cycle. If so, it is not safe to call AddPred(TargetSU, SU).
610 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *TargetSU, SUnit *SU) {
611 // Is SU reachable from TargetSU via successor edges?
612 if (IsReachable(SU, TargetSU))
614 for (SUnit::pred_iterator
615 I = TargetSU->Preds.begin(), E = TargetSU->Preds.end(); I != E; ++I)
616 if (I->isAssignedRegDep() &&
617 IsReachable(SU, I->getSUnit()))
622 /// IsReachable - Checks if SU is reachable from TargetSU.
623 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
624 const SUnit *TargetSU) {
625 // If insertion of the edge SU->TargetSU would create a cycle
626 // then there is a path from TargetSU to SU.
627 int UpperBound, LowerBound;
628 LowerBound = Node2Index[TargetSU->NodeNum];
629 UpperBound = Node2Index[SU->NodeNum];
630 bool HasLoop = false;
631 // Is Ord(TargetSU) < Ord(SU) ?
632 if (LowerBound < UpperBound) {
634 // There may be a path from TargetSU to SU. Check for it.
635 DFS(TargetSU, UpperBound, HasLoop);
640 /// Allocate - assign the topological index to the node n.
641 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
642 Node2Index[n] = index;
643 Index2Node[index] = n;
646 ScheduleDAGTopologicalSort::
647 ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits, SUnit *exitsu)
648 : SUnits(sunits), ExitSU(exitsu) {}
650 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}