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