e309a4385e4570bfc412cc8095619bb7c6956e20
[oota-llvm.git] / lib / CodeGen / ScheduleDAG.cpp
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/CodeGen/ScheduleHazardRecognizer.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Support/Debug.h"
22 #include <climits>
23 using namespace llvm;
24
25 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
26   : DAG(0), BB(0), TM(mf.getTarget()),
27     TII(TM.getInstrInfo()),
28     TRI(TM.getRegisterInfo()),
29     TLI(TM.getTargetLowering()),
30     MF(mf), MRI(mf.getRegInfo()),
31     ConstPool(MF.getConstantPool()) {
32 }
33
34 ScheduleDAG::~ScheduleDAG() {}
35
36 /// dump - dump the schedule.
37 void ScheduleDAG::dumpSchedule() const {
38   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
39     if (SUnit *SU = Sequence[i])
40       SU->dump(this);
41     else
42       cerr << "**** NOOP ****\n";
43   }
44 }
45
46
47 /// Run - perform scheduling.
48 ///
49 void ScheduleDAG::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
50   SUnits.clear();
51   Sequence.clear();
52   DAG = dag;
53   BB = bb;
54
55   Schedule();
56   
57   DOUT << "*** Final schedule ***\n";
58   DEBUG(dumpSchedule());
59   DOUT << "\n";
60 }
61
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
64 /// specified node.
65 void SUnit::addPred(const SDep &D) {
66   // If this node already has this depenence, don't add a redundant one.
67   for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
68     if (Preds[i] == D)
69       return;
70   // Now add a corresponding succ to N.
71   SDep P = D;
72   P.setSUnit(this);
73   SUnit *N = D.getSUnit();
74   // Update the bookkeeping.
75   if (D.getKind() == SDep::Data) {
76     ++NumPreds;
77     ++N->NumSuccs;
78   }
79   if (!N->isScheduled)
80     ++NumPredsLeft;
81   if (!isScheduled)
82     ++N->NumSuccsLeft;
83   Preds.push_back(D);
84   N->Succs.push_back(P);
85   if (P.getLatency() != 0) {
86     this->setDepthDirty();
87     N->setHeightDirty();
88   }
89 }
90
91 /// removePred - This removes the specified edge as a pred of the current
92 /// node if it exists.  It also removes the current node as a successor of
93 /// the specified node.
94 void SUnit::removePred(const SDep &D) {
95   // Find the matching predecessor.
96   for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
97        I != E; ++I)
98     if (*I == D) {
99       bool FoundSucc = false;
100       // Find the corresponding successor in N.
101       SDep P = D;
102       P.setSUnit(this);
103       SUnit *N = D.getSUnit();
104       for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
105              EE = N->Succs.end(); II != EE; ++II)
106         if (*II == P) {
107           FoundSucc = true;
108           N->Succs.erase(II);
109           break;
110         }
111       assert(FoundSucc && "Mismatching preds / succs lists!");
112       Preds.erase(I);
113       // Update the bookkeeping.
114       if (P.getKind() == SDep::Data) {
115         --NumPreds;
116         --N->NumSuccs;
117       }
118       if (!N->isScheduled)
119         --NumPredsLeft;
120       if (!isScheduled)
121         --N->NumSuccsLeft;
122       if (P.getLatency() != 0) {
123         this->setDepthDirty();
124         N->setHeightDirty();
125       }
126       return;
127     }
128 }
129
130 void SUnit::setDepthDirty() {
131   if (!isDepthCurrent) return;
132   SmallVector<SUnit*, 8> WorkList;
133   WorkList.push_back(this);
134   do {
135     SUnit *SU = WorkList.pop_back_val();
136     SU->isDepthCurrent = false;
137     for (SUnit::const_succ_iterator I = SU->Succs.begin(),
138          E = SU->Succs.end(); I != E; ++I) {
139       SUnit *SuccSU = I->getSUnit();
140       if (SuccSU->isDepthCurrent)
141         WorkList.push_back(SuccSU);
142     }
143   } while (!WorkList.empty());
144 }
145
146 void SUnit::setHeightDirty() {
147   if (!isHeightCurrent) return;
148   SmallVector<SUnit*, 8> WorkList;
149   WorkList.push_back(this);
150   do {
151     SUnit *SU = WorkList.pop_back_val();
152     SU->isHeightCurrent = false;
153     for (SUnit::const_pred_iterator I = SU->Preds.begin(),
154          E = SU->Preds.end(); I != E; ++I) {
155       SUnit *PredSU = I->getSUnit();
156       if (PredSU->isHeightCurrent)
157         WorkList.push_back(PredSU);
158     }
159   } while (!WorkList.empty());
160 }
161
162 /// setDepthToAtLeast - Update this node's successors to reflect the
163 /// fact that this node's depth just increased.
164 ///
165 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
166   if (NewDepth <= getDepth())
167     return;
168   setDepthDirty();
169   Depth = NewDepth;
170   isDepthCurrent = true;
171 }
172
173 /// setHeightToAtLeast - Update this node's predecessors to reflect the
174 /// fact that this node's height just increased.
175 ///
176 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
177   if (NewHeight <= getHeight())
178     return;
179   setHeightDirty();
180   Height = NewHeight;
181   isHeightCurrent = true;
182 }
183
184 /// ComputeDepth - Calculate the maximal path from the node to the exit.
185 ///
186 void SUnit::ComputeDepth() {
187   SmallVector<SUnit*, 8> WorkList;
188   WorkList.push_back(this);
189   do {
190     SUnit *Cur = WorkList.back();
191
192     bool Done = true;
193     unsigned MaxPredDepth = 0;
194     for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
195          E = Cur->Preds.end(); I != E; ++I) {
196       SUnit *PredSU = I->getSUnit();
197       if (PredSU->isDepthCurrent)
198         MaxPredDepth = std::max(MaxPredDepth,
199                                 PredSU->Depth + I->getLatency());
200       else {
201         Done = false;
202         WorkList.push_back(PredSU);
203       }
204     }
205
206     if (Done) {
207       WorkList.pop_back();
208       if (MaxPredDepth != Cur->Depth) {
209         Cur->setDepthDirty();
210         Cur->Depth = MaxPredDepth;
211       }
212       Cur->isDepthCurrent = true;
213     }
214   } while (!WorkList.empty());
215 }
216
217 /// ComputeHeight - Calculate the maximal path from the node to the entry.
218 ///
219 void SUnit::ComputeHeight() {
220   SmallVector<SUnit*, 8> WorkList;
221   WorkList.push_back(this);
222   do {
223     SUnit *Cur = WorkList.back();
224
225     bool Done = true;
226     unsigned MaxSuccHeight = 0;
227     for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
228          E = Cur->Succs.end(); I != E; ++I) {
229       SUnit *SuccSU = I->getSUnit();
230       if (SuccSU->isHeightCurrent)
231         MaxSuccHeight = std::max(MaxSuccHeight,
232                                  SuccSU->Height + I->getLatency());
233       else {
234         Done = false;
235         WorkList.push_back(SuccSU);
236       }
237     }
238
239     if (Done) {
240       WorkList.pop_back();
241       if (MaxSuccHeight != Cur->Height) {
242         Cur->setHeightDirty();
243         Cur->Height = MaxSuccHeight;
244       }
245       Cur->isHeightCurrent = true;
246     }
247   } while (!WorkList.empty());
248 }
249
250 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
251 /// a group of nodes flagged together.
252 void SUnit::dump(const ScheduleDAG *G) const {
253   cerr << "SU(" << NodeNum << "): ";
254   G->dumpNode(this);
255 }
256
257 void SUnit::dumpAll(const ScheduleDAG *G) const {
258   dump(G);
259
260   cerr << "  # preds left       : " << NumPredsLeft << "\n";
261   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
262   cerr << "  Latency            : " << Latency << "\n";
263   cerr << "  Depth              : " << Depth << "\n";
264   cerr << "  Height             : " << Height << "\n";
265
266   if (Preds.size() != 0) {
267     cerr << "  Predecessors:\n";
268     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
269          I != E; ++I) {
270       cerr << "   ";
271       switch (I->getKind()) {
272       case SDep::Data:        cerr << "val "; break;
273       case SDep::Anti:        cerr << "anti"; break;
274       case SDep::Output:      cerr << "out "; break;
275       case SDep::Order:       cerr << "ch  "; break;
276       }
277       cerr << "#";
278       cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
279       if (I->isArtificial())
280         cerr << " *";
281       cerr << "\n";
282     }
283   }
284   if (Succs.size() != 0) {
285     cerr << "  Successors:\n";
286     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
287          I != E; ++I) {
288       cerr << "   ";
289       switch (I->getKind()) {
290       case SDep::Data:        cerr << "val "; break;
291       case SDep::Anti:        cerr << "anti"; break;
292       case SDep::Output:      cerr << "out "; break;
293       case SDep::Order:       cerr << "ch  "; break;
294       }
295       cerr << "#";
296       cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
297       if (I->isArtificial())
298         cerr << " *";
299       cerr << "\n";
300     }
301   }
302   cerr << "\n";
303 }
304
305 #ifndef NDEBUG
306 /// VerifySchedule - Verify that all SUnits were scheduled and that
307 /// their state is consistent.
308 ///
309 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
310   bool AnyNotSched = false;
311   unsigned DeadNodes = 0;
312   unsigned Noops = 0;
313   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
314     if (!SUnits[i].isScheduled) {
315       if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
316         ++DeadNodes;
317         continue;
318       }
319       if (!AnyNotSched)
320         cerr << "*** Scheduling failed! ***\n";
321       SUnits[i].dump(this);
322       cerr << "has not been scheduled!\n";
323       AnyNotSched = true;
324     }
325     if (SUnits[i].isScheduled &&
326         (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
327           unsigned(INT_MAX)) {
328       if (!AnyNotSched)
329         cerr << "*** Scheduling failed! ***\n";
330       SUnits[i].dump(this);
331       cerr << "has an unexpected "
332            << (isBottomUp ? "Height" : "Depth") << " value!\n";
333       AnyNotSched = true;
334     }
335     if (isBottomUp) {
336       if (SUnits[i].NumSuccsLeft != 0) {
337         if (!AnyNotSched)
338           cerr << "*** Scheduling failed! ***\n";
339         SUnits[i].dump(this);
340         cerr << "has successors left!\n";
341         AnyNotSched = true;
342       }
343     } else {
344       if (SUnits[i].NumPredsLeft != 0) {
345         if (!AnyNotSched)
346           cerr << "*** Scheduling failed! ***\n";
347         SUnits[i].dump(this);
348         cerr << "has predecessors left!\n";
349         AnyNotSched = true;
350       }
351     }
352   }
353   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
354     if (!Sequence[i])
355       ++Noops;
356   assert(!AnyNotSched);
357   assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
358          "The number of nodes scheduled doesn't match the expected number!");
359 }
360 #endif
361
362 /// InitDAGTopologicalSorting - create the initial topological 
363 /// ordering from the DAG to be scheduled.
364 ///
365 /// The idea of the algorithm is taken from 
366 /// "Online algorithms for managing the topological order of
367 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
368 /// This is the MNR algorithm, which was first introduced by 
369 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in  
370 /// "Maintaining a topological order under edge insertions".
371 ///
372 /// Short description of the algorithm: 
373 ///
374 /// Topological ordering, ord, of a DAG maps each node to a topological
375 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
376 ///
377 /// This means that if there is a path from the node X to the node Z, 
378 /// then ord(X) < ord(Z).
379 ///
380 /// This property can be used to check for reachability of nodes:
381 /// if Z is reachable from X, then an insertion of the edge Z->X would 
382 /// create a cycle.
383 ///
384 /// The algorithm first computes a topological ordering for the DAG by
385 /// initializing the Index2Node and Node2Index arrays and then tries to keep
386 /// the ordering up-to-date after edge insertions by reordering the DAG.
387 ///
388 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
389 /// the nodes reachable from Y, and then shifts them using Shift to lie
390 /// immediately after X in Index2Node.
391 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
392   unsigned DAGSize = SUnits.size();
393   std::vector<SUnit*> WorkList;
394   WorkList.reserve(DAGSize);
395
396   Index2Node.resize(DAGSize);
397   Node2Index.resize(DAGSize);
398
399   // Initialize the data structures.
400   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
401     SUnit *SU = &SUnits[i];
402     int NodeNum = SU->NodeNum;
403     unsigned Degree = SU->Succs.size();
404     // Temporarily use the Node2Index array as scratch space for degree counts.
405     Node2Index[NodeNum] = Degree;
406
407     // Is it a node without dependencies?
408     if (Degree == 0) {
409       assert(SU->Succs.empty() && "SUnit should have no successors");
410       // Collect leaf nodes.
411       WorkList.push_back(SU);
412     }
413   }  
414
415   int Id = DAGSize;
416   while (!WorkList.empty()) {
417     SUnit *SU = WorkList.back();
418     WorkList.pop_back();
419     Allocate(SU->NodeNum, --Id);
420     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
421          I != E; ++I) {
422       SUnit *SU = I->getSUnit();
423       if (!--Node2Index[SU->NodeNum])
424         // If all dependencies of the node are processed already,
425         // then the node can be computed now.
426         WorkList.push_back(SU);
427     }
428   }
429
430   Visited.resize(DAGSize);
431
432 #ifndef NDEBUG
433   // Check correctness of the ordering
434   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
435     SUnit *SU = &SUnits[i];
436     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
437          I != E; ++I) {
438       assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] && 
439       "Wrong topological sorting");
440     }
441   }
442 #endif
443 }
444
445 /// AddPred - Updates the topological ordering to accomodate an edge
446 /// to be added from SUnit X to SUnit Y.
447 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
448   int UpperBound, LowerBound;
449   LowerBound = Node2Index[Y->NodeNum];
450   UpperBound = Node2Index[X->NodeNum];
451   bool HasLoop = false;
452   // Is Ord(X) < Ord(Y) ?
453   if (LowerBound < UpperBound) {
454     // Update the topological order.
455     Visited.reset();
456     DFS(Y, UpperBound, HasLoop);
457     assert(!HasLoop && "Inserted edge creates a loop!");
458     // Recompute topological indexes.
459     Shift(Visited, LowerBound, UpperBound);
460   }
461 }
462
463 /// RemovePred - Updates the topological ordering to accomodate an
464 /// an edge to be removed from the specified node N from the predecessors
465 /// of the current node M.
466 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
467   // InitDAGTopologicalSorting();
468 }
469
470 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
471 /// all nodes affected by the edge insertion. These nodes will later get new
472 /// topological indexes by means of the Shift method.
473 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
474                                      bool& HasLoop) {
475   std::vector<const SUnit*> WorkList;
476   WorkList.reserve(SUnits.size()); 
477
478   WorkList.push_back(SU);
479   do {
480     SU = WorkList.back();
481     WorkList.pop_back();
482     Visited.set(SU->NodeNum);
483     for (int I = SU->Succs.size()-1; I >= 0; --I) {
484       int s = SU->Succs[I].getSUnit()->NodeNum;
485       if (Node2Index[s] == UpperBound) {
486         HasLoop = true; 
487         return;
488       }
489       // Visit successors if not already and in affected region.
490       if (!Visited.test(s) && Node2Index[s] < UpperBound) {
491         WorkList.push_back(SU->Succs[I].getSUnit());
492       } 
493     } 
494   } while (!WorkList.empty());
495 }
496
497 /// Shift - Renumber the nodes so that the topological ordering is 
498 /// preserved.
499 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound, 
500                                        int UpperBound) {
501   std::vector<int> L;
502   int shift = 0;
503   int i;
504
505   for (i = LowerBound; i <= UpperBound; ++i) {
506     // w is node at topological index i.
507     int w = Index2Node[i];
508     if (Visited.test(w)) {
509       // Unmark.
510       Visited.reset(w);
511       L.push_back(w);
512       shift = shift + 1;
513     } else {
514       Allocate(w, i - shift);
515     }
516   }
517
518   for (unsigned j = 0; j < L.size(); ++j) {
519     Allocate(L[j], i - shift);
520     i = i + 1;
521   }
522 }
523
524
525 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
526 /// create a cycle.
527 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
528   if (IsReachable(TargetSU, SU))
529     return true;
530   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
531        I != E; ++I)
532     if (I->isAssignedRegDep() &&
533         IsReachable(TargetSU, I->getSUnit()))
534       return true;
535   return false;
536 }
537
538 /// IsReachable - Checks if SU is reachable from TargetSU.
539 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
540                                              const SUnit *TargetSU) {
541   // If insertion of the edge SU->TargetSU would create a cycle
542   // then there is a path from TargetSU to SU.
543   int UpperBound, LowerBound;
544   LowerBound = Node2Index[TargetSU->NodeNum];
545   UpperBound = Node2Index[SU->NodeNum];
546   bool HasLoop = false;
547   // Is Ord(TargetSU) < Ord(SU) ?
548   if (LowerBound < UpperBound) {
549     Visited.reset();
550     // There may be a path from TargetSU to SU. Check for it. 
551     DFS(TargetSU, UpperBound, HasLoop);
552   }
553   return HasLoop;
554 }
555
556 /// Allocate - assign the topological index to the node n.
557 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
558   Node2Index[n] = index;
559   Index2Node[index] = n;
560 }
561
562 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
563                                                      std::vector<SUnit> &sunits)
564  : SUnits(sunits) {}
565
566 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}