Move addPred and removePred out-of-line.
[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/Target/TargetMachine.h"
18 #include "llvm/Target/TargetInstrInfo.h"
19 #include "llvm/Target/TargetRegisterInfo.h"
20 #include "llvm/Support/Debug.h"
21 #include <climits>
22 using namespace llvm;
23
24 ScheduleDAG::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
34 ScheduleDAG::~ScheduleDAG() {}
35
36 /// CalculateDepths - compute depths using algorithms for the longest
37 /// paths in the DAG
38 void 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
92 void 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.
146 void 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 ///
158 void ScheduleDAG::Run() {
159   Schedule();
160   
161   DOUT << "*** Final schedule ***\n";
162   DEBUG(dumpSchedule());
163   DOUT << "\n";
164 }
165
166 /// addPred - This adds the specified edge as a pred of the current node if
167 /// not already.  It also adds the current node as a successor of the
168 /// specified node.
169 void SUnit::addPred(const SDep &D) {
170   // If this node already has this depenence, don't add a redundant one.
171   for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
172     if (Preds[i] == D)
173       return;
174   // Add a pred to this SUnit.
175   Preds.push_back(D);
176   // Now add a corresponding succ to N.
177   SDep P = D;
178   P.setSUnit(this);
179   SUnit *N = D.getSUnit();
180   N->Succs.push_back(P);
181   // Update the bookkeeping.
182   if (D.getKind() == SDep::Data) {
183     ++NumPreds;
184     ++N->NumSuccs;
185   }
186   if (!N->isScheduled)
187     ++NumPredsLeft;
188   if (!isScheduled)
189     ++N->NumSuccsLeft;
190 }
191
192 /// removePred - This removes the specified edge as a pred of the current
193 /// node if it exists.  It also removes the current node as a successor of
194 /// the specified node.
195 void SUnit::removePred(const SDep &D) {
196   // Find the matching predecessor.
197   for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
198        I != E; ++I)
199     if (*I == D) {
200       bool FoundSucc = false;
201       // Find the corresponding successor in N.
202       SDep P = D;
203       P.setSUnit(this);
204       SUnit *N = D.getSUnit();
205       for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
206              EE = N->Succs.end(); II != EE; ++II)
207         if (*II == P) {
208           FoundSucc = true;
209           N->Succs.erase(II);
210           break;
211         }
212       assert(FoundSucc && "Mismatching preds / succs lists!");
213       Preds.erase(I);
214       // Update the bookkeeping;
215       if (D.getKind() == SDep::Data) {
216         --NumPreds;
217         --N->NumSuccs;
218       }
219       if (!N->isScheduled)
220         --NumPredsLeft;
221       if (!isScheduled)
222         --N->NumSuccsLeft;
223       return;
224     }
225 }
226
227 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
228 /// a group of nodes flagged together.
229 void SUnit::dump(const ScheduleDAG *G) const {
230   cerr << "SU(" << NodeNum << "): ";
231   G->dumpNode(this);
232 }
233
234 void SUnit::dumpAll(const ScheduleDAG *G) const {
235   dump(G);
236
237   cerr << "  # preds left       : " << NumPredsLeft << "\n";
238   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
239   cerr << "  Latency            : " << Latency << "\n";
240   cerr << "  Depth              : " << Depth << "\n";
241   cerr << "  Height             : " << Height << "\n";
242
243   if (Preds.size() != 0) {
244     cerr << "  Predecessors:\n";
245     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
246          I != E; ++I) {
247       cerr << "   ";
248       switch (I->getKind()) {
249       case SDep::Data:        cerr << "val "; break;
250       case SDep::Anti:        cerr << "anti"; break;
251       case SDep::Output:      cerr << "out "; break;
252       case SDep::Order:       cerr << "ch  "; break;
253       }
254       cerr << "#";
255       cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
256       if (I->isArtificial())
257         cerr << " *";
258       cerr << "\n";
259     }
260   }
261   if (Succs.size() != 0) {
262     cerr << "  Successors:\n";
263     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
264          I != E; ++I) {
265       cerr << "   ";
266       switch (I->getKind()) {
267       case SDep::Data:        cerr << "val "; break;
268       case SDep::Anti:        cerr << "anti"; break;
269       case SDep::Output:      cerr << "out "; break;
270       case SDep::Order:       cerr << "ch  "; break;
271       }
272       cerr << "#";
273       cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
274       if (I->isArtificial())
275         cerr << " *";
276       cerr << "\n";
277     }
278   }
279   cerr << "\n";
280 }
281
282 #ifndef NDEBUG
283 /// VerifySchedule - Verify that all SUnits were scheduled and that
284 /// their state is consistent.
285 ///
286 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
287   bool AnyNotSched = false;
288   unsigned DeadNodes = 0;
289   unsigned Noops = 0;
290   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
291     if (!SUnits[i].isScheduled) {
292       if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
293         ++DeadNodes;
294         continue;
295       }
296       if (!AnyNotSched)
297         cerr << "*** Scheduling failed! ***\n";
298       SUnits[i].dump(this);
299       cerr << "has not been scheduled!\n";
300       AnyNotSched = true;
301     }
302     if (SUnits[i].isScheduled && SUnits[i].Cycle > (unsigned)INT_MAX) {
303       if (!AnyNotSched)
304         cerr << "*** Scheduling failed! ***\n";
305       SUnits[i].dump(this);
306       cerr << "has an unexpected Cycle value!\n";
307       AnyNotSched = true;
308     }
309     if (isBottomUp) {
310       if (SUnits[i].NumSuccsLeft != 0) {
311         if (!AnyNotSched)
312           cerr << "*** Scheduling failed! ***\n";
313         SUnits[i].dump(this);
314         cerr << "has successors left!\n";
315         AnyNotSched = true;
316       }
317     } else {
318       if (SUnits[i].NumPredsLeft != 0) {
319         if (!AnyNotSched)
320           cerr << "*** Scheduling failed! ***\n";
321         SUnits[i].dump(this);
322         cerr << "has predecessors left!\n";
323         AnyNotSched = true;
324       }
325     }
326   }
327   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
328     if (!Sequence[i])
329       ++Noops;
330   assert(!AnyNotSched);
331   assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
332          "The number of nodes scheduled doesn't match the expected number!");
333 }
334 #endif
335
336 /// InitDAGTopologicalSorting - create the initial topological 
337 /// ordering from the DAG to be scheduled.
338 ///
339 /// The idea of the algorithm is taken from 
340 /// "Online algorithms for managing the topological order of
341 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
342 /// This is the MNR algorithm, which was first introduced by 
343 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in  
344 /// "Maintaining a topological order under edge insertions".
345 ///
346 /// Short description of the algorithm: 
347 ///
348 /// Topological ordering, ord, of a DAG maps each node to a topological
349 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
350 ///
351 /// This means that if there is a path from the node X to the node Z, 
352 /// then ord(X) < ord(Z).
353 ///
354 /// This property can be used to check for reachability of nodes:
355 /// if Z is reachable from X, then an insertion of the edge Z->X would 
356 /// create a cycle.
357 ///
358 /// The algorithm first computes a topological ordering for the DAG by
359 /// initializing the Index2Node and Node2Index arrays and then tries to keep
360 /// the ordering up-to-date after edge insertions by reordering the DAG.
361 ///
362 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
363 /// the nodes reachable from Y, and then shifts them using Shift to lie
364 /// immediately after X in Index2Node.
365 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
366   unsigned DAGSize = SUnits.size();
367   std::vector<SUnit*> WorkList;
368   WorkList.reserve(DAGSize);
369
370   Index2Node.resize(DAGSize);
371   Node2Index.resize(DAGSize);
372
373   // Initialize the data structures.
374   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
375     SUnit *SU = &SUnits[i];
376     int NodeNum = SU->NodeNum;
377     unsigned Degree = SU->Succs.size();
378     // Temporarily use the Node2Index array as scratch space for degree counts.
379     Node2Index[NodeNum] = Degree;
380
381     // Is it a node without dependencies?
382     if (Degree == 0) {
383       assert(SU->Succs.empty() && "SUnit should have no successors");
384       // Collect leaf nodes.
385       WorkList.push_back(SU);
386     }
387   }  
388
389   int Id = DAGSize;
390   while (!WorkList.empty()) {
391     SUnit *SU = WorkList.back();
392     WorkList.pop_back();
393     Allocate(SU->NodeNum, --Id);
394     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
395          I != E; ++I) {
396       SUnit *SU = I->getSUnit();
397       if (!--Node2Index[SU->NodeNum])
398         // If all dependencies of the node are processed already,
399         // then the node can be computed now.
400         WorkList.push_back(SU);
401     }
402   }
403
404   Visited.resize(DAGSize);
405
406 #ifndef NDEBUG
407   // Check correctness of the ordering
408   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
409     SUnit *SU = &SUnits[i];
410     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
411          I != E; ++I) {
412       assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] && 
413       "Wrong topological sorting");
414     }
415   }
416 #endif
417 }
418
419 /// AddPred - Updates the topological ordering to accomodate an edge
420 /// to be added from SUnit X to SUnit Y.
421 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
422   int UpperBound, LowerBound;
423   LowerBound = Node2Index[Y->NodeNum];
424   UpperBound = Node2Index[X->NodeNum];
425   bool HasLoop = false;
426   // Is Ord(X) < Ord(Y) ?
427   if (LowerBound < UpperBound) {
428     // Update the topological order.
429     Visited.reset();
430     DFS(Y, UpperBound, HasLoop);
431     assert(!HasLoop && "Inserted edge creates a loop!");
432     // Recompute topological indexes.
433     Shift(Visited, LowerBound, UpperBound);
434   }
435 }
436
437 /// RemovePred - Updates the topological ordering to accomodate an
438 /// an edge to be removed from the specified node N from the predecessors
439 /// of the current node M.
440 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
441   // InitDAGTopologicalSorting();
442 }
443
444 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
445 /// all nodes affected by the edge insertion. These nodes will later get new
446 /// topological indexes by means of the Shift method.
447 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
448                                      bool& HasLoop) {
449   std::vector<const SUnit*> WorkList;
450   WorkList.reserve(SUnits.size()); 
451
452   WorkList.push_back(SU);
453   while (!WorkList.empty()) {
454     SU = WorkList.back();
455     WorkList.pop_back();
456     Visited.set(SU->NodeNum);
457     for (int I = SU->Succs.size()-1; I >= 0; --I) {
458       int s = SU->Succs[I].getSUnit()->NodeNum;
459       if (Node2Index[s] == UpperBound) {
460         HasLoop = true; 
461         return;
462       }
463       // Visit successors if not already and in affected region.
464       if (!Visited.test(s) && Node2Index[s] < UpperBound) {
465         WorkList.push_back(SU->Succs[I].getSUnit());
466       } 
467     } 
468   }
469 }
470
471 /// Shift - Renumber the nodes so that the topological ordering is 
472 /// preserved.
473 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound, 
474                                        int UpperBound) {
475   std::vector<int> L;
476   int shift = 0;
477   int i;
478
479   for (i = LowerBound; i <= UpperBound; ++i) {
480     // w is node at topological index i.
481     int w = Index2Node[i];
482     if (Visited.test(w)) {
483       // Unmark.
484       Visited.reset(w);
485       L.push_back(w);
486       shift = shift + 1;
487     } else {
488       Allocate(w, i - shift);
489     }
490   }
491
492   for (unsigned j = 0; j < L.size(); ++j) {
493     Allocate(L[j], i - shift);
494     i = i + 1;
495   }
496 }
497
498
499 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
500 /// create a cycle.
501 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
502   if (IsReachable(TargetSU, SU))
503     return true;
504   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
505        I != E; ++I)
506     if (I->isAssignedRegDep() &&
507         IsReachable(TargetSU, I->getSUnit()))
508       return true;
509   return false;
510 }
511
512 /// IsReachable - Checks if SU is reachable from TargetSU.
513 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
514                                              const SUnit *TargetSU) {
515   // If insertion of the edge SU->TargetSU would create a cycle
516   // then there is a path from TargetSU to SU.
517   int UpperBound, LowerBound;
518   LowerBound = Node2Index[TargetSU->NodeNum];
519   UpperBound = Node2Index[SU->NodeNum];
520   bool HasLoop = false;
521   // Is Ord(TargetSU) < Ord(SU) ?
522   if (LowerBound < UpperBound) {
523     Visited.reset();
524     // There may be a path from TargetSU to SU. Check for it. 
525     DFS(TargetSU, UpperBound, HasLoop);
526   }
527   return HasLoop;
528 }
529
530 /// Allocate - assign the topological index to the node n.
531 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
532   Node2Index[n] = index;
533   Index2Node[index] = n;
534 }
535
536 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
537                                                      std::vector<SUnit> &sunits)
538  : SUnits(sunits) {}