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