ScheduleDAG.cpp revision 54e4c36a7349e94a84773afb56eccd4ca65b49e9
1//===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the ScheduleDAG class, which is a base class used by
11// scheduling implementation classes.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "pre-RA-sched"
16#include "llvm/CodeGen/ScheduleDAG.h"
17#include "llvm/Target/TargetMachine.h"
18#include "llvm/Target/TargetInstrInfo.h"
19#include "llvm/Target/TargetRegisterInfo.h"
20#include "llvm/Support/Debug.h"
21#include <climits>
22using namespace llvm;
23
24ScheduleDAG::ScheduleDAG(SelectionDAG *dag, MachineBasicBlock *bb,
25                         const TargetMachine &tm)
26  : DAG(dag), BB(bb), TM(tm), MRI(BB->getParent()->getRegInfo()) {
27  TII = TM.getInstrInfo();
28  MF  = BB->getParent();
29  TRI = TM.getRegisterInfo();
30  TLI = TM.getTargetLowering();
31  ConstPool = MF->getConstantPool();
32}
33
34ScheduleDAG::~ScheduleDAG() {}
35
36/// CalculateDepths - compute depths using algorithms for the longest
37/// paths in the DAG
38void ScheduleDAG::CalculateDepths() {
39  unsigned DAGSize = SUnits.size();
40  std::vector<SUnit*> WorkList;
41  WorkList.reserve(DAGSize);
42
43  // Initialize the data structures
44  for (unsigned i = 0, e = DAGSize; i != e; ++i) {
45    SUnit *SU = &SUnits[i];
46    unsigned Degree = SU->Preds.size();
47    // Temporarily use the Depth field as scratch space for the degree count.
48    SU->Depth = Degree;
49
50    // Is it a node without dependencies?
51    if (Degree == 0) {
52      assert(SU->Preds.empty() && "SUnit should have no predecessors");
53      // Collect leaf nodes
54      WorkList.push_back(SU);
55    }
56  }
57
58  // Process nodes in the topological order
59  while (!WorkList.empty()) {
60    SUnit *SU = WorkList.back();
61    WorkList.pop_back();
62    unsigned SUDepth = 0;
63
64    // Use dynamic programming:
65    // When current node is being processed, all of its dependencies
66    // are already processed.
67    // So, just iterate over all predecessors and take the longest path
68    for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
69         I != E; ++I) {
70      unsigned PredDepth = I->getSUnit()->Depth;
71      if (PredDepth+1 > SUDepth) {
72        SUDepth = PredDepth + 1;
73      }
74    }
75
76    SU->Depth = SUDepth;
77
78    // Update degrees of all nodes depending on current SUnit
79    for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
80         I != E; ++I) {
81      SUnit *SU = I->getSUnit();
82      if (!--SU->Depth)
83        // If all dependencies of the node are processed already,
84        // then the longest path for the node can be computed now
85        WorkList.push_back(SU);
86    }
87  }
88}
89
90/// CalculateHeights - compute heights using algorithms for the longest
91/// paths in the DAG
92void ScheduleDAG::CalculateHeights() {
93  unsigned DAGSize = SUnits.size();
94  std::vector<SUnit*> WorkList;
95  WorkList.reserve(DAGSize);
96
97  // Initialize the data structures
98  for (unsigned i = 0, e = DAGSize; i != e; ++i) {
99    SUnit *SU = &SUnits[i];
100    unsigned Degree = SU->Succs.size();
101    // Temporarily use the Height field as scratch space for the degree count.
102    SU->Height = Degree;
103
104    // Is it a node without dependencies?
105    if (Degree == 0) {
106      assert(SU->Succs.empty() && "Something wrong");
107      assert(WorkList.empty() && "Should be empty");
108      // Collect leaf nodes
109      WorkList.push_back(SU);
110    }
111  }
112
113  // Process nodes in the topological order
114  while (!WorkList.empty()) {
115    SUnit *SU = WorkList.back();
116    WorkList.pop_back();
117    unsigned SUHeight = 0;
118
119    // Use dynamic programming:
120    // When current node is being processed, all of its dependencies
121    // are already processed.
122    // So, just iterate over all successors and take the longest path
123    for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
124         I != E; ++I) {
125      unsigned SuccHeight = I->getSUnit()->Height;
126      if (SuccHeight+1 > SUHeight) {
127        SUHeight = SuccHeight + 1;
128      }
129    }
130
131    SU->Height = SUHeight;
132
133    // Update degrees of all nodes depending on current SUnit
134    for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
135         I != E; ++I) {
136      SUnit *SU = I->getSUnit();
137      if (!--SU->Height)
138        // If all dependencies of the node are processed already,
139        // then the longest path for the node can be computed now
140        WorkList.push_back(SU);
141    }
142  }
143}
144
145/// dump - dump the schedule.
146void ScheduleDAG::dumpSchedule() const {
147  for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
148    if (SUnit *SU = Sequence[i])
149      SU->dump(this);
150    else
151      cerr << "**** NOOP ****\n";
152  }
153}
154
155
156/// Run - perform scheduling.
157///
158void ScheduleDAG::Run() {
159  Schedule();
160
161  DOUT << "*** Final schedule ***\n";
162  DEBUG(dumpSchedule());
163  DOUT << "\n";
164}
165
166/// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
167/// a group of nodes flagged together.
168void SUnit::dump(const ScheduleDAG *G) const {
169  cerr << "SU(" << NodeNum << "): ";
170  G->dumpNode(this);
171}
172
173void SUnit::dumpAll(const ScheduleDAG *G) const {
174  dump(G);
175
176  cerr << "  # preds left       : " << NumPredsLeft << "\n";
177  cerr << "  # succs left       : " << NumSuccsLeft << "\n";
178  cerr << "  Latency            : " << Latency << "\n";
179  cerr << "  Depth              : " << Depth << "\n";
180  cerr << "  Height             : " << Height << "\n";
181
182  if (Preds.size() != 0) {
183    cerr << "  Predecessors:\n";
184    for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
185         I != E; ++I) {
186      cerr << "   ";
187      switch (I->getKind()) {
188      case SDep::Data:        cerr << "val "; break;
189      case SDep::Anti:        cerr << "anti"; break;
190      case SDep::Output:      cerr << "out "; break;
191      case SDep::Order:       cerr << "ch  "; break;
192      }
193      cerr << "#";
194      cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
195      if (I->isArtificial())
196        cerr << " *";
197      cerr << "\n";
198    }
199  }
200  if (Succs.size() != 0) {
201    cerr << "  Successors:\n";
202    for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
203         I != E; ++I) {
204      cerr << "   ";
205      switch (I->getKind()) {
206      case SDep::Data:        cerr << "val "; break;
207      case SDep::Anti:        cerr << "anti"; break;
208      case SDep::Output:      cerr << "out "; break;
209      case SDep::Order:       cerr << "ch  "; break;
210      }
211      cerr << "#";
212      cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
213      if (I->isArtificial())
214        cerr << " *";
215      cerr << "\n";
216    }
217  }
218  cerr << "\n";
219}
220
221#ifndef NDEBUG
222/// VerifySchedule - Verify that all SUnits were scheduled and that
223/// their state is consistent.
224///
225void ScheduleDAG::VerifySchedule(bool isBottomUp) {
226  bool AnyNotSched = false;
227  unsigned DeadNodes = 0;
228  unsigned Noops = 0;
229  for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
230    if (!SUnits[i].isScheduled) {
231      if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
232        ++DeadNodes;
233        continue;
234      }
235      if (!AnyNotSched)
236        cerr << "*** Scheduling failed! ***\n";
237      SUnits[i].dump(this);
238      cerr << "has not been scheduled!\n";
239      AnyNotSched = true;
240    }
241    if (SUnits[i].isScheduled && SUnits[i].Cycle > (unsigned)INT_MAX) {
242      if (!AnyNotSched)
243        cerr << "*** Scheduling failed! ***\n";
244      SUnits[i].dump(this);
245      cerr << "has an unexpected Cycle value!\n";
246      AnyNotSched = true;
247    }
248    if (isBottomUp) {
249      if (SUnits[i].NumSuccsLeft != 0) {
250        if (!AnyNotSched)
251          cerr << "*** Scheduling failed! ***\n";
252        SUnits[i].dump(this);
253        cerr << "has successors left!\n";
254        AnyNotSched = true;
255      }
256    } else {
257      if (SUnits[i].NumPredsLeft != 0) {
258        if (!AnyNotSched)
259          cerr << "*** Scheduling failed! ***\n";
260        SUnits[i].dump(this);
261        cerr << "has predecessors left!\n";
262        AnyNotSched = true;
263      }
264    }
265  }
266  for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
267    if (!Sequence[i])
268      ++Noops;
269  assert(!AnyNotSched);
270  assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
271         "The number of nodes scheduled doesn't match the expected number!");
272}
273#endif
274
275/// InitDAGTopologicalSorting - create the initial topological
276/// ordering from the DAG to be scheduled.
277///
278/// The idea of the algorithm is taken from
279/// "Online algorithms for managing the topological order of
280/// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
281/// This is the MNR algorithm, which was first introduced by
282/// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
283/// "Maintaining a topological order under edge insertions".
284///
285/// Short description of the algorithm:
286///
287/// Topological ordering, ord, of a DAG maps each node to a topological
288/// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
289///
290/// This means that if there is a path from the node X to the node Z,
291/// then ord(X) < ord(Z).
292///
293/// This property can be used to check for reachability of nodes:
294/// if Z is reachable from X, then an insertion of the edge Z->X would
295/// create a cycle.
296///
297/// The algorithm first computes a topological ordering for the DAG by
298/// initializing the Index2Node and Node2Index arrays and then tries to keep
299/// the ordering up-to-date after edge insertions by reordering the DAG.
300///
301/// On insertion of the edge X->Y, the algorithm first marks by calling DFS
302/// the nodes reachable from Y, and then shifts them using Shift to lie
303/// immediately after X in Index2Node.
304void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
305  unsigned DAGSize = SUnits.size();
306  std::vector<SUnit*> WorkList;
307  WorkList.reserve(DAGSize);
308
309  Index2Node.resize(DAGSize);
310  Node2Index.resize(DAGSize);
311
312  // Initialize the data structures.
313  for (unsigned i = 0, e = DAGSize; i != e; ++i) {
314    SUnit *SU = &SUnits[i];
315    int NodeNum = SU->NodeNum;
316    unsigned Degree = SU->Succs.size();
317    // Temporarily use the Node2Index array as scratch space for degree counts.
318    Node2Index[NodeNum] = Degree;
319
320    // Is it a node without dependencies?
321    if (Degree == 0) {
322      assert(SU->Succs.empty() && "SUnit should have no successors");
323      // Collect leaf nodes.
324      WorkList.push_back(SU);
325    }
326  }
327
328  int Id = DAGSize;
329  while (!WorkList.empty()) {
330    SUnit *SU = WorkList.back();
331    WorkList.pop_back();
332    Allocate(SU->NodeNum, --Id);
333    for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
334         I != E; ++I) {
335      SUnit *SU = I->getSUnit();
336      if (!--Node2Index[SU->NodeNum])
337        // If all dependencies of the node are processed already,
338        // then the node can be computed now.
339        WorkList.push_back(SU);
340    }
341  }
342
343  Visited.resize(DAGSize);
344
345#ifndef NDEBUG
346  // Check correctness of the ordering
347  for (unsigned i = 0, e = DAGSize; i != e; ++i) {
348    SUnit *SU = &SUnits[i];
349    for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
350         I != E; ++I) {
351      assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
352      "Wrong topological sorting");
353    }
354  }
355#endif
356}
357
358/// AddPred - Updates the topological ordering to accomodate an edge
359/// to be added from SUnit X to SUnit Y.
360void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
361  int UpperBound, LowerBound;
362  LowerBound = Node2Index[Y->NodeNum];
363  UpperBound = Node2Index[X->NodeNum];
364  bool HasLoop = false;
365  // Is Ord(X) < Ord(Y) ?
366  if (LowerBound < UpperBound) {
367    // Update the topological order.
368    Visited.reset();
369    DFS(Y, UpperBound, HasLoop);
370    assert(!HasLoop && "Inserted edge creates a loop!");
371    // Recompute topological indexes.
372    Shift(Visited, LowerBound, UpperBound);
373  }
374}
375
376/// RemovePred - Updates the topological ordering to accomodate an
377/// an edge to be removed from the specified node N from the predecessors
378/// of the current node M.
379void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
380  // InitDAGTopologicalSorting();
381}
382
383/// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
384/// all nodes affected by the edge insertion. These nodes will later get new
385/// topological indexes by means of the Shift method.
386void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
387                                     bool& HasLoop) {
388  std::vector<const SUnit*> WorkList;
389  WorkList.reserve(SUnits.size());
390
391  WorkList.push_back(SU);
392  while (!WorkList.empty()) {
393    SU = WorkList.back();
394    WorkList.pop_back();
395    Visited.set(SU->NodeNum);
396    for (int I = SU->Succs.size()-1; I >= 0; --I) {
397      int s = SU->Succs[I].getSUnit()->NodeNum;
398      if (Node2Index[s] == UpperBound) {
399        HasLoop = true;
400        return;
401      }
402      // Visit successors if not already and in affected region.
403      if (!Visited.test(s) && Node2Index[s] < UpperBound) {
404        WorkList.push_back(SU->Succs[I].getSUnit());
405      }
406    }
407  }
408}
409
410/// Shift - Renumber the nodes so that the topological ordering is
411/// preserved.
412void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
413                                       int UpperBound) {
414  std::vector<int> L;
415  int shift = 0;
416  int i;
417
418  for (i = LowerBound; i <= UpperBound; ++i) {
419    // w is node at topological index i.
420    int w = Index2Node[i];
421    if (Visited.test(w)) {
422      // Unmark.
423      Visited.reset(w);
424      L.push_back(w);
425      shift = shift + 1;
426    } else {
427      Allocate(w, i - shift);
428    }
429  }
430
431  for (unsigned j = 0; j < L.size(); ++j) {
432    Allocate(L[j], i - shift);
433    i = i + 1;
434  }
435}
436
437
438/// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
439/// create a cycle.
440bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
441  if (IsReachable(TargetSU, SU))
442    return true;
443  for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
444       I != E; ++I)
445    if (I->isAssignedRegDep() &&
446        IsReachable(TargetSU, I->getSUnit()))
447      return true;
448  return false;
449}
450
451/// IsReachable - Checks if SU is reachable from TargetSU.
452bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
453                                             const SUnit *TargetSU) {
454  // If insertion of the edge SU->TargetSU would create a cycle
455  // then there is a path from TargetSU to SU.
456  int UpperBound, LowerBound;
457  LowerBound = Node2Index[TargetSU->NodeNum];
458  UpperBound = Node2Index[SU->NodeNum];
459  bool HasLoop = false;
460  // Is Ord(TargetSU) < Ord(SU) ?
461  if (LowerBound < UpperBound) {
462    Visited.reset();
463    // There may be a path from TargetSU to SU. Check for it.
464    DFS(TargetSU, UpperBound, HasLoop);
465  }
466  return HasLoop;
467}
468
469/// Allocate - assign the topological index to the node n.
470void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
471  Node2Index[n] = index;
472  Index2Node[index] = n;
473}
474
475ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
476                                                     std::vector<SUnit> &sunits)
477 : SUnits(sunits) {}
478