LLVM API Documentation

ScheduleDAG.cpp

Go to the documentation of this file.
00001 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements the ScheduleDAG class, which is a base class used by
00011 // scheduling implementation classes.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "pre-RA-sched"
00016 #include "llvm/CodeGen/ScheduleDAG.h"
00017 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
00018 #include "llvm/Target/TargetMachine.h"
00019 #include "llvm/Target/TargetInstrInfo.h"
00020 #include "llvm/Target/TargetRegisterInfo.h"
00021 #include "llvm/Support/Debug.h"
00022 #include "llvm/Support/raw_ostream.h"
00023 #include <climits>
00024 using namespace llvm;
00025 
00026 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
00027   : TM(mf.getTarget()),
00028     TII(TM.getInstrInfo()),
00029     TRI(TM.getRegisterInfo()),
00030     TLI(TM.getTargetLowering()),
00031     MF(mf), MRI(mf.getRegInfo()),
00032     ConstPool(MF.getConstantPool()),
00033     EntrySU(), ExitSU() {
00034 }
00035 
00036 ScheduleDAG::~ScheduleDAG() {}
00037 
00038 /// dump - dump the schedule.
00039 void ScheduleDAG::dumpSchedule() const {
00040   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
00041     if (SUnit *SU = Sequence[i])
00042       SU->dump(this);
00043     else
00044       errs() << "**** NOOP ****\n";
00045   }
00046 }
00047 
00048 
00049 /// Run - perform scheduling.
00050 ///
00051 void ScheduleDAG::Run(MachineBasicBlock *bb,
00052                       MachineBasicBlock::iterator insertPos) {
00053   BB = bb;
00054   InsertPos = insertPos;
00055 
00056   SUnits.clear();
00057   Sequence.clear();
00058   EntrySU = SUnit();
00059   ExitSU = SUnit();
00060 
00061   Schedule();
00062 
00063   DOUT << "*** Final schedule ***\n";
00064   DEBUG(dumpSchedule());
00065   DOUT << "\n";
00066 }
00067 
00068 /// addPred - This adds the specified edge as a pred of the current node if
00069 /// not already.  It also adds the current node as a successor of the
00070 /// specified node.
00071 void SUnit::addPred(const SDep &D) {
00072   // If this node already has this depenence, don't add a redundant one.
00073   for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
00074        I != E; ++I)
00075     if (*I == D)
00076       return;
00077   // Now add a corresponding succ to N.
00078   SDep P = D;
00079   P.setSUnit(this);
00080   SUnit *N = D.getSUnit();
00081   // Update the bookkeeping.
00082   if (D.getKind() == SDep::Data) {
00083     ++NumPreds;
00084     ++N->NumSuccs;
00085   }
00086   if (!N->isScheduled)
00087     ++NumPredsLeft;
00088   if (!isScheduled)
00089     ++N->NumSuccsLeft;
00090   Preds.push_back(D);
00091   N->Succs.push_back(P);
00092   if (P.getLatency() != 0) {
00093     this->setDepthDirty();
00094     N->setHeightDirty();
00095   }
00096 }
00097 
00098 /// removePred - This removes the specified edge as a pred of the current
00099 /// node if it exists.  It also removes the current node as a successor of
00100 /// the specified node.
00101 void SUnit::removePred(const SDep &D) {
00102   // Find the matching predecessor.
00103   for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
00104        I != E; ++I)
00105     if (*I == D) {
00106       bool FoundSucc = false;
00107       // Find the corresponding successor in N.
00108       SDep P = D;
00109       P.setSUnit(this);
00110       SUnit *N = D.getSUnit();
00111       for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
00112              EE = N->Succs.end(); II != EE; ++II)
00113         if (*II == P) {
00114           FoundSucc = true;
00115           N->Succs.erase(II);
00116           break;
00117         }
00118       assert(FoundSucc && "Mismatching preds / succs lists!");
00119       Preds.erase(I);
00120       // Update the bookkeeping.
00121       if (P.getKind() == SDep::Data) {
00122         --NumPreds;
00123         --N->NumSuccs;
00124       }
00125       if (!N->isScheduled)
00126         --NumPredsLeft;
00127       if (!isScheduled)
00128         --N->NumSuccsLeft;
00129       if (P.getLatency() != 0) {
00130         this->setDepthDirty();
00131         N->setHeightDirty();
00132       }
00133       return;
00134     }
00135 }
00136 
00137 void SUnit::setDepthDirty() {
00138   if (!isDepthCurrent) return;
00139   SmallVector<SUnit*, 8> WorkList;
00140   WorkList.push_back(this);
00141   do {
00142     SUnit *SU = WorkList.pop_back_val();
00143     SU->isDepthCurrent = false;
00144     for (SUnit::const_succ_iterator I = SU->Succs.begin(),
00145          E = SU->Succs.end(); I != E; ++I) {
00146       SUnit *SuccSU = I->getSUnit();
00147       if (SuccSU->isDepthCurrent)
00148         WorkList.push_back(SuccSU);
00149     }
00150   } while (!WorkList.empty());
00151 }
00152 
00153 void SUnit::setHeightDirty() {
00154   if (!isHeightCurrent) return;
00155   SmallVector<SUnit*, 8> WorkList;
00156   WorkList.push_back(this);
00157   do {
00158     SUnit *SU = WorkList.pop_back_val();
00159     SU->isHeightCurrent = false;
00160     for (SUnit::const_pred_iterator I = SU->Preds.begin(),
00161          E = SU->Preds.end(); I != E; ++I) {
00162       SUnit *PredSU = I->getSUnit();
00163       if (PredSU->isHeightCurrent)
00164         WorkList.push_back(PredSU);
00165     }
00166   } while (!WorkList.empty());
00167 }
00168 
00169 /// setDepthToAtLeast - Update this node's successors to reflect the
00170 /// fact that this node's depth just increased.
00171 ///
00172 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
00173   if (NewDepth <= getDepth())
00174     return;
00175   setDepthDirty();
00176   Depth = NewDepth;
00177   isDepthCurrent = true;
00178 }
00179 
00180 /// setHeightToAtLeast - Update this node's predecessors to reflect the
00181 /// fact that this node's height just increased.
00182 ///
00183 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
00184   if (NewHeight <= getHeight())
00185     return;
00186   setHeightDirty();
00187   Height = NewHeight;
00188   isHeightCurrent = true;
00189 }
00190 
00191 /// ComputeDepth - Calculate the maximal path from the node to the exit.
00192 ///
00193 void SUnit::ComputeDepth() {
00194   SmallVector<SUnit*, 8> WorkList;
00195   WorkList.push_back(this);
00196   do {
00197     SUnit *Cur = WorkList.back();
00198 
00199     bool Done = true;
00200     unsigned MaxPredDepth = 0;
00201     for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
00202          E = Cur->Preds.end(); I != E; ++I) {
00203       SUnit *PredSU = I->getSUnit();
00204       if (PredSU->isDepthCurrent)
00205         MaxPredDepth = std::max(MaxPredDepth,
00206                                 PredSU->Depth + I->getLatency());
00207       else {
00208         Done = false;
00209         WorkList.push_back(PredSU);
00210       }
00211     }
00212 
00213     if (Done) {
00214       WorkList.pop_back();
00215       if (MaxPredDepth != Cur->Depth) {
00216         Cur->setDepthDirty();
00217         Cur->Depth = MaxPredDepth;
00218       }
00219       Cur->isDepthCurrent = true;
00220     }
00221   } while (!WorkList.empty());
00222 }
00223 
00224 /// ComputeHeight - Calculate the maximal path from the node to the entry.
00225 ///
00226 void SUnit::ComputeHeight() {
00227   SmallVector<SUnit*, 8> WorkList;
00228   WorkList.push_back(this);
00229   do {
00230     SUnit *Cur = WorkList.back();
00231 
00232     bool Done = true;
00233     unsigned MaxSuccHeight = 0;
00234     for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
00235          E = Cur->Succs.end(); I != E; ++I) {
00236       SUnit *SuccSU = I->getSUnit();
00237       if (SuccSU->isHeightCurrent)
00238         MaxSuccHeight = std::max(MaxSuccHeight,
00239                                  SuccSU->Height + I->getLatency());
00240       else {
00241         Done = false;
00242         WorkList.push_back(SuccSU);
00243       }
00244     }
00245 
00246     if (Done) {
00247       WorkList.pop_back();
00248       if (MaxSuccHeight != Cur->Height) {
00249         Cur->setHeightDirty();
00250         Cur->Height = MaxSuccHeight;
00251       }
00252       Cur->isHeightCurrent = true;
00253     }
00254   } while (!WorkList.empty());
00255 }
00256 
00257 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
00258 /// a group of nodes flagged together.
00259 void SUnit::dump(const ScheduleDAG *G) const {
00260   errs() << "SU(" << NodeNum << "): ";
00261   G->dumpNode(this);
00262 }
00263 
00264 void SUnit::dumpAll(const ScheduleDAG *G) const {
00265   dump(G);
00266 
00267   errs() << "  # preds left       : " << NumPredsLeft << "\n";
00268   errs() << "  # succs left       : " << NumSuccsLeft << "\n";
00269   errs() << "  Latency            : " << Latency << "\n";
00270   errs() << "  Depth              : " << Depth << "\n";
00271   errs() << "  Height             : " << Height << "\n";
00272 
00273   if (Preds.size() != 0) {
00274     errs() << "  Predecessors:\n";
00275     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
00276          I != E; ++I) {
00277       errs() << "   ";
00278       switch (I->getKind()) {
00279       case SDep::Data:        errs() << "val "; break;
00280       case SDep::Anti:        errs() << "anti"; break;
00281       case SDep::Output:      errs() << "out "; break;
00282       case SDep::Order:       errs() << "ch  "; break;
00283       }
00284       errs() << "#";
00285       errs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
00286       if (I->isArtificial())
00287         errs() << " *";
00288       errs() << ": Latency=" << I->getLatency();
00289       errs() << "\n";
00290     }
00291   }
00292   if (Succs.size() != 0) {
00293     errs() << "  Successors:\n";
00294     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
00295          I != E; ++I) {
00296       errs() << "   ";
00297       switch (I->getKind()) {
00298       case SDep::Data:        errs() << "val "; break;
00299       case SDep::Anti:        errs() << "anti"; break;
00300       case SDep::Output:      errs() << "out "; break;
00301       case SDep::Order:       errs() << "ch  "; break;
00302       }
00303       errs() << "#";
00304       errs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
00305       if (I->isArtificial())
00306         errs() << " *";
00307       errs() << ": Latency=" << I->getLatency();
00308       errs() << "\n";
00309     }
00310   }
00311   errs() << "\n";
00312 }
00313 
00314 #ifndef NDEBUG
00315 /// VerifySchedule - Verify that all SUnits were scheduled and that
00316 /// their state is consistent.
00317 ///
00318 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
00319   bool AnyNotSched = false;
00320   unsigned DeadNodes = 0;
00321   unsigned Noops = 0;
00322   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
00323     if (!SUnits[i].isScheduled) {
00324       if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
00325         ++DeadNodes;
00326         continue;
00327       }
00328       if (!AnyNotSched)
00329         errs() << "*** Scheduling failed! ***\n";
00330       SUnits[i].dump(this);
00331       errs() << "has not been scheduled!\n";
00332       AnyNotSched = true;
00333     }
00334     if (SUnits[i].isScheduled &&
00335         (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
00336           unsigned(INT_MAX)) {
00337       if (!AnyNotSched)
00338         errs() << "*** Scheduling failed! ***\n";
00339       SUnits[i].dump(this);
00340       errs() << "has an unexpected "
00341            << (isBottomUp ? "Height" : "Depth") << " value!\n";
00342       AnyNotSched = true;
00343     }
00344     if (isBottomUp) {
00345       if (SUnits[i].NumSuccsLeft != 0) {
00346         if (!AnyNotSched)
00347           errs() << "*** Scheduling failed! ***\n";
00348         SUnits[i].dump(this);
00349         errs() << "has successors left!\n";
00350         AnyNotSched = true;
00351       }
00352     } else {
00353       if (SUnits[i].NumPredsLeft != 0) {
00354         if (!AnyNotSched)
00355           errs() << "*** Scheduling failed! ***\n";
00356         SUnits[i].dump(this);
00357         errs() << "has predecessors left!\n";
00358         AnyNotSched = true;
00359       }
00360     }
00361   }
00362   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
00363     if (!Sequence[i])
00364       ++Noops;
00365   assert(!AnyNotSched);
00366   assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
00367          "The number of nodes scheduled doesn't match the expected number!");
00368 }
00369 #endif
00370 
00371 /// InitDAGTopologicalSorting - create the initial topological 
00372 /// ordering from the DAG to be scheduled.
00373 ///
00374 /// The idea of the algorithm is taken from 
00375 /// "Online algorithms for managing the topological order of
00376 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
00377 /// This is the MNR algorithm, which was first introduced by 
00378 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in  
00379 /// "Maintaining a topological order under edge insertions".
00380 ///
00381 /// Short description of the algorithm: 
00382 ///
00383 /// Topological ordering, ord, of a DAG maps each node to a topological
00384 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
00385 ///
00386 /// This means that if there is a path from the node X to the node Z, 
00387 /// then ord(X) < ord(Z).
00388 ///
00389 /// This property can be used to check for reachability of nodes:
00390 /// if Z is reachable from X, then an insertion of the edge Z->X would 
00391 /// create a cycle.
00392 ///
00393 /// The algorithm first computes a topological ordering for the DAG by
00394 /// initializing the Index2Node and Node2Index arrays and then tries to keep
00395 /// the ordering up-to-date after edge insertions by reordering the DAG.
00396 ///
00397 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
00398 /// the nodes reachable from Y, and then shifts them using Shift to lie
00399 /// immediately after X in Index2Node.
00400 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
00401   unsigned DAGSize = SUnits.size();
00402   std::vector<SUnit*> WorkList;
00403   WorkList.reserve(DAGSize);
00404 
00405   Index2Node.resize(DAGSize);
00406   Node2Index.resize(DAGSize);
00407 
00408   // Initialize the data structures.
00409   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
00410     SUnit *SU = &SUnits[i];
00411     int NodeNum = SU->NodeNum;
00412     unsigned Degree = SU->Succs.size();
00413     // Temporarily use the Node2Index array as scratch space for degree counts.
00414     Node2Index[NodeNum] = Degree;
00415 
00416     // Is it a node without dependencies?
00417     if (Degree == 0) {
00418       assert(SU->Succs.empty() && "SUnit should have no successors");
00419       // Collect leaf nodes.
00420       WorkList.push_back(SU);
00421     }
00422   }  
00423 
00424   int Id = DAGSize;
00425   while (!WorkList.empty()) {
00426     SUnit *SU = WorkList.back();
00427     WorkList.pop_back();
00428     Allocate(SU->NodeNum, --Id);
00429     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
00430          I != E; ++I) {
00431       SUnit *SU = I->getSUnit();
00432       if (!--Node2Index[SU->NodeNum])
00433         // If all dependencies of the node are processed already,
00434         // then the node can be computed now.
00435         WorkList.push_back(SU);
00436     }
00437   }
00438 
00439   Visited.resize(DAGSize);
00440 
00441 #ifndef NDEBUG
00442   // Check correctness of the ordering
00443   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
00444     SUnit *SU = &SUnits[i];
00445     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
00446          I != E; ++I) {
00447       assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] && 
00448       "Wrong topological sorting");
00449     }
00450   }
00451 #endif
00452 }
00453 
00454 /// AddPred - Updates the topological ordering to accomodate an edge
00455 /// to be added from SUnit X to SUnit Y.
00456 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
00457   int UpperBound, LowerBound;
00458   LowerBound = Node2Index[Y->NodeNum];
00459   UpperBound = Node2Index[X->NodeNum];
00460   bool HasLoop = false;
00461   // Is Ord(X) < Ord(Y) ?
00462   if (LowerBound < UpperBound) {
00463     // Update the topological order.
00464     Visited.reset();
00465     DFS(Y, UpperBound, HasLoop);
00466     assert(!HasLoop && "Inserted edge creates a loop!");
00467     // Recompute topological indexes.
00468     Shift(Visited, LowerBound, UpperBound);
00469   }
00470 }
00471 
00472 /// RemovePred - Updates the topological ordering to accomodate an
00473 /// an edge to be removed from the specified node N from the predecessors
00474 /// of the current node M.
00475 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
00476   // InitDAGTopologicalSorting();
00477 }
00478 
00479 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
00480 /// all nodes affected by the edge insertion. These nodes will later get new
00481 /// topological indexes by means of the Shift method.
00482 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
00483                                      bool& HasLoop) {
00484   std::vector<const SUnit*> WorkList;
00485   WorkList.reserve(SUnits.size()); 
00486 
00487   WorkList.push_back(SU);
00488   do {
00489     SU = WorkList.back();
00490     WorkList.pop_back();
00491     Visited.set(SU->NodeNum);
00492     for (int I = SU->Succs.size()-1; I >= 0; --I) {
00493       int s = SU->Succs[I].getSUnit()->NodeNum;
00494       if (Node2Index[s] == UpperBound) {
00495         HasLoop = true; 
00496         return;
00497       }
00498       // Visit successors if not already and in affected region.
00499       if (!Visited.test(s) && Node2Index[s] < UpperBound) {
00500         WorkList.push_back(SU->Succs[I].getSUnit());
00501       } 
00502     } 
00503   } while (!WorkList.empty());
00504 }
00505 
00506 /// Shift - Renumber the nodes so that the topological ordering is 
00507 /// preserved.
00508 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound, 
00509                                        int UpperBound) {
00510   std::vector<int> L;
00511   int shift = 0;
00512   int i;
00513 
00514   for (i = LowerBound; i <= UpperBound; ++i) {
00515     // w is node at topological index i.
00516     int w = Index2Node[i];
00517     if (Visited.test(w)) {
00518       // Unmark.
00519       Visited.reset(w);
00520       L.push_back(w);
00521       shift = shift + 1;
00522     } else {
00523       Allocate(w, i - shift);
00524     }
00525   }
00526 
00527   for (unsigned j = 0; j < L.size(); ++j) {
00528     Allocate(L[j], i - shift);
00529     i = i + 1;
00530   }
00531 }
00532 
00533 
00534 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
00535 /// create a cycle.
00536 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
00537   if (IsReachable(TargetSU, SU))
00538     return true;
00539   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
00540        I != E; ++I)
00541     if (I->isAssignedRegDep() &&
00542         IsReachable(TargetSU, I->getSUnit()))
00543       return true;
00544   return false;
00545 }
00546 
00547 /// IsReachable - Checks if SU is reachable from TargetSU.
00548 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
00549                                              const SUnit *TargetSU) {
00550   // If insertion of the edge SU->TargetSU would create a cycle
00551   // then there is a path from TargetSU to SU.
00552   int UpperBound, LowerBound;
00553   LowerBound = Node2Index[TargetSU->NodeNum];
00554   UpperBound = Node2Index[SU->NodeNum];
00555   bool HasLoop = false;
00556   // Is Ord(TargetSU) < Ord(SU) ?
00557   if (LowerBound < UpperBound) {
00558     Visited.reset();
00559     // There may be a path from TargetSU to SU. Check for it. 
00560     DFS(TargetSU, UpperBound, HasLoop);
00561   }
00562   return HasLoop;
00563 }
00564 
00565 /// Allocate - assign the topological index to the node n.
00566 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
00567   Node2Index[n] = index;
00568   Index2Node[index] = n;
00569 }
00570 
00571 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
00572                                                      std::vector<SUnit> &sunits)
00573  : SUnits(sunits) {}
00574 
00575 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}