Tidy up #includes, deleting a bunch of unnecessary #includes.
[oota-llvm.git] / include / llvm / Analysis / DominatorInternals.h
1 //=== llvm/Analysis/DominatorInternals.h - Dominator Calculation -*- C++ -*-==//
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 #ifndef LLVM_ANALYSIS_DOMINATOR_INTERNALS_H
11 #define LLVM_ANALYSIS_DOMINATOR_INTERNALS_H
12
13 #include "llvm/Analysis/Dominators.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15
16 //===----------------------------------------------------------------------===//
17 //
18 // DominatorTree construction - This pass constructs immediate dominator
19 // information for a flow-graph based on the algorithm described in this
20 // document:
21 //
22 //   A Fast Algorithm for Finding Dominators in a Flowgraph
23 //   T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
24 //
25 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
26 // LINK, but it turns out that the theoretically slower O(n*log(n))
27 // implementation is actually faster than the "efficient" algorithm (even for
28 // large CFGs) because the constant overheads are substantially smaller.  The
29 // lower-complexity version can be enabled with the following #define:
30 //
31 #define BALANCE_IDOM_TREE 0
32 //
33 //===----------------------------------------------------------------------===//
34
35 namespace llvm {
36
37 template<class GraphT>
38 unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
39                  typename GraphT::NodeType* V, unsigned N) {
40   // This is more understandable as a recursive algorithm, but we can't use the
41   // recursive algorithm due to stack depth issues.  Keep it here for
42   // documentation purposes.
43 #if 0
44   InfoRec &VInfo = DT.Info[DT.Roots[i]];
45   VInfo.DFSNum = VInfo.Semi = ++N;
46   VInfo.Label = V;
47
48   Vertex.push_back(V);        // Vertex[n] = V;
49   //Info[V].Ancestor = 0;     // Ancestor[n] = 0
50   //Info[V].Child = 0;        // Child[v] = 0
51   VInfo.Size = 1;             // Size[v] = 1
52
53   for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
54     InfoRec &SuccVInfo = DT.Info[*SI];
55     if (SuccVInfo.Semi == 0) {
56       SuccVInfo.Parent = V;
57       N = DTDFSPass(DT, *SI, N);
58     }
59   }
60 #else
61   bool IsChilOfArtificialExit = (N != 0);
62
63   std::vector<std::pair<typename GraphT::NodeType*,
64                         typename GraphT::ChildIteratorType> > Worklist;
65   Worklist.push_back(std::make_pair(V, GraphT::child_begin(V)));
66   while (!Worklist.empty()) {
67     typename GraphT::NodeType* BB = Worklist.back().first;
68     typename GraphT::ChildIteratorType NextSucc = Worklist.back().second;
69
70     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &BBInfo =
71                                                                     DT.Info[BB];
72
73     // First time we visited this BB?
74     if (NextSucc == GraphT::child_begin(BB)) {
75       BBInfo.DFSNum = BBInfo.Semi = ++N;
76       BBInfo.Label = BB;
77
78       DT.Vertex.push_back(BB);       // Vertex[n] = V;
79       //BBInfo[V].Ancestor = 0;   // Ancestor[n] = 0
80       //BBInfo[V].Child = 0;      // Child[v] = 0
81       BBInfo.Size = 1;            // Size[v] = 1
82
83       if (IsChilOfArtificialExit)
84         BBInfo.Parent = 1;
85
86       IsChilOfArtificialExit = false;
87     }
88
89     // store the DFS number of the current BB - the reference to BBInfo might
90     // get invalidated when processing the successors.
91     unsigned BBDFSNum = BBInfo.DFSNum;
92
93     // If we are done with this block, remove it from the worklist.
94     if (NextSucc == GraphT::child_end(BB)) {
95       Worklist.pop_back();
96       continue;
97     }
98
99     // Increment the successor number for the next time we get to it.
100     ++Worklist.back().second;
101     
102     // Visit the successor next, if it isn't already visited.
103     typename GraphT::NodeType* Succ = *NextSucc;
104
105     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &SuccVInfo =
106                                                                   DT.Info[Succ];
107     if (SuccVInfo.Semi == 0) {
108       SuccVInfo.Parent = BBDFSNum;
109       Worklist.push_back(std::make_pair(Succ, GraphT::child_begin(Succ)));
110     }
111   }
112 #endif
113     return N;
114 }
115
116 template<class GraphT>
117 void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
118               typename GraphT::NodeType *VIn) {
119   std::vector<typename GraphT::NodeType*> Work;
120   SmallPtrSet<typename GraphT::NodeType*, 32> Visited;
121   typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInVAInfo =
122                                       DT.Info[DT.Vertex[DT.Info[VIn].Ancestor]];
123
124   if (VInVAInfo.Ancestor != 0)
125     Work.push_back(VIn);
126   
127   while (!Work.empty()) {
128     typename GraphT::NodeType* V = Work.back();
129     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInfo =
130                                                                      DT.Info[V];
131     typename GraphT::NodeType* VAncestor = DT.Vertex[VInfo.Ancestor];
132     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VAInfo =
133                                                              DT.Info[VAncestor];
134
135     // Process Ancestor first
136     if (Visited.insert(VAncestor) &&
137         VAInfo.Ancestor != 0) {
138       Work.push_back(VAncestor);
139       continue;
140     } 
141     Work.pop_back(); 
142
143     // Update VInfo based on Ancestor info
144     if (VAInfo.Ancestor == 0)
145       continue;
146     typename GraphT::NodeType* VAncestorLabel = VAInfo.Label;
147     typename GraphT::NodeType* VLabel = VInfo.Label;
148     if (DT.Info[VAncestorLabel].Semi < DT.Info[VLabel].Semi)
149       VInfo.Label = VAncestorLabel;
150     VInfo.Ancestor = VAInfo.Ancestor;
151   }
152 }
153
154 template<class GraphT>
155 typename GraphT::NodeType* Eval(DominatorTreeBase<typename GraphT::NodeType>& DT,
156                                 typename GraphT::NodeType *V) {
157   typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInfo =
158                                                                      DT.Info[V];
159 #if !BALANCE_IDOM_TREE
160   // Higher-complexity but faster implementation
161   if (VInfo.Ancestor == 0)
162     return V;
163   Compress<GraphT>(DT, V);
164   return VInfo.Label;
165 #else
166   // Lower-complexity but slower implementation
167   if (VInfo.Ancestor == 0)
168     return VInfo.Label;
169   Compress<GraphT>(DT, V);
170   GraphT::NodeType* VLabel = VInfo.Label;
171
172   GraphT::NodeType* VAncestorLabel = DT.Info[VInfo.Ancestor].Label;
173   if (DT.Info[VAncestorLabel].Semi >= DT.Info[VLabel].Semi)
174     return VLabel;
175   else
176     return VAncestorLabel;
177 #endif
178 }
179
180 template<class GraphT>
181 void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
182           unsigned DFSNumV, typename GraphT::NodeType* W,
183         typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo) {
184 #if !BALANCE_IDOM_TREE
185   // Higher-complexity but faster implementation
186   WInfo.Ancestor = DFSNumV;
187 #else
188   // Lower-complexity but slower implementation
189   GraphT::NodeType* WLabel = WInfo.Label;
190   unsigned WLabelSemi = DT.Info[WLabel].Semi;
191   GraphT::NodeType* S = W;
192   InfoRec *SInfo = &DT.Info[S];
193
194   GraphT::NodeType* SChild = SInfo->Child;
195   InfoRec *SChildInfo = &DT.Info[SChild];
196
197   while (WLabelSemi < DT.Info[SChildInfo->Label].Semi) {
198     GraphT::NodeType* SChildChild = SChildInfo->Child;
199     if (SInfo->Size+DT.Info[SChildChild].Size >= 2*SChildInfo->Size) {
200       SChildInfo->Ancestor = S;
201       SInfo->Child = SChild = SChildChild;
202       SChildInfo = &DT.Info[SChild];
203     } else {
204       SChildInfo->Size = SInfo->Size;
205       S = SInfo->Ancestor = SChild;
206       SInfo = SChildInfo;
207       SChild = SChildChild;
208       SChildInfo = &DT.Info[SChild];
209     }
210   }
211
212   DominatorTreeBase::InfoRec &VInfo = DT.Info[V];
213   SInfo->Label = WLabel;
214
215   assert(V != W && "The optimization here will not work in this case!");
216   unsigned WSize = WInfo.Size;
217   unsigned VSize = (VInfo.Size += WSize);
218
219   if (VSize < 2*WSize)
220     std::swap(S, VInfo.Child);
221
222   while (S) {
223     SInfo = &DT.Info[S];
224     SInfo->Ancestor = V;
225     S = SInfo->Child;
226   }
227 #endif
228 }
229
230 template<class FuncT, class NodeT>
231 void Calculate(DominatorTreeBase<typename GraphTraits<NodeT>::NodeType>& DT,
232                FuncT& F) {
233   typedef GraphTraits<NodeT> GraphT;
234
235   unsigned N = 0;
236   bool MultipleRoots = (DT.Roots.size() > 1);
237   if (MultipleRoots) {
238     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &BBInfo =
239         DT.Info[NULL];
240     BBInfo.DFSNum = BBInfo.Semi = ++N;
241     BBInfo.Label = NULL;
242
243     DT.Vertex.push_back(NULL);       // Vertex[n] = V;
244       //BBInfo[V].Ancestor = 0;   // Ancestor[n] = 0
245       //BBInfo[V].Child = 0;      // Child[v] = 0
246     BBInfo.Size = 1;            // Size[v] = 1
247   }
248
249   // Step #1: Number blocks in depth-first order and initialize variables used
250   // in later stages of the algorithm.
251   for (unsigned i = 0, e = static_cast<unsigned>(DT.Roots.size());
252        i != e; ++i)
253     N = DFSPass<GraphT>(DT, DT.Roots[i], N);
254
255   // it might be that some blocks did not get a DFS number (e.g., blocks of 
256   // infinite loops). In these cases an artificial exit node is required.
257   MultipleRoots |= (DT.isPostDominator() && N != F.size());
258
259   for (unsigned i = N; i >= 2; --i) {
260     typename GraphT::NodeType* W = DT.Vertex[i];
261     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo =
262                                                                      DT.Info[W];
263
264     // Step #2: Calculate the semidominators of all vertices
265     bool HasChildOutsideDFS = false;
266
267     // initialize the semi dominator to point to the parent node
268     WInfo.Semi = WInfo.Parent;
269     for (typename GraphTraits<Inverse<NodeT> >::ChildIteratorType CI =
270          GraphTraits<Inverse<NodeT> >::child_begin(W),
271          E = GraphTraits<Inverse<NodeT> >::child_end(W); CI != E; ++CI) {
272       if (DT.Info.count(*CI)) {  // Only if this predecessor is reachable!
273         unsigned SemiU = DT.Info[Eval<GraphT>(DT, *CI)].Semi;
274         if (SemiU < WInfo.Semi)
275           WInfo.Semi = SemiU;
276       }
277       else {
278         // if the child has no DFS number it is not post-dominated by any exit, 
279         // and so is the current block.
280         HasChildOutsideDFS = true;
281       }
282     }
283
284     // if some child has no DFS number it is not post-dominated by any exit, 
285     // and so is the current block.
286     if (DT.isPostDominator() && HasChildOutsideDFS)
287       WInfo.Semi = 0;
288
289     DT.Info[DT.Vertex[WInfo.Semi]].Bucket.push_back(W);
290
291     typename GraphT::NodeType* WParent = DT.Vertex[WInfo.Parent];
292     Link<GraphT>(DT, WInfo.Parent, W, WInfo);
293
294     // Step #3: Implicitly define the immediate dominator of vertices
295     std::vector<typename GraphT::NodeType*> &WParentBucket =
296                                                         DT.Info[WParent].Bucket;
297     while (!WParentBucket.empty()) {
298       typename GraphT::NodeType* V = WParentBucket.back();
299       WParentBucket.pop_back();
300       typename GraphT::NodeType* U = Eval<GraphT>(DT, V);
301       DT.IDoms[V] = DT.Info[U].Semi < DT.Info[V].Semi ? U : WParent;
302     }
303   }
304
305   // Step #4: Explicitly define the immediate dominator of each vertex
306   for (unsigned i = 2; i <= N; ++i) {
307     typename GraphT::NodeType* W = DT.Vertex[i];
308     typename GraphT::NodeType*& WIDom = DT.IDoms[W];
309     if (WIDom != DT.Vertex[DT.Info[W].Semi])
310       WIDom = DT.IDoms[WIDom];
311   }
312
313   if (DT.Roots.empty()) return;
314
315   // Add a node for the root.  This node might be the actual root, if there is
316   // one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
317   // which postdominates all real exits if there are multiple exit blocks, or
318   // an infinite loop.
319   typename GraphT::NodeType* Root = !MultipleRoots ? DT.Roots[0] : 0;
320
321   DT.DomTreeNodes[Root] = DT.RootNode =
322                         new DomTreeNodeBase<typename GraphT::NodeType>(Root, 0);
323
324   // Loop over all of the reachable blocks in the function...
325   for (unsigned i = 2; i <= N; ++i) {
326     typename GraphT::NodeType* W = DT.Vertex[i];
327
328     DomTreeNodeBase<typename GraphT::NodeType> *BBNode = DT.DomTreeNodes[W];
329     if (BBNode) continue;  // Haven't calculated this node yet?
330
331     typename GraphT::NodeType* ImmDom = DT.getIDom(W);
332
333     assert(ImmDom || DT.DomTreeNodes[NULL]);
334
335     // Get or calculate the node for the immediate dominator
336     DomTreeNodeBase<typename GraphT::NodeType> *IDomNode =
337                                                      DT.getNodeForBlock(ImmDom);
338
339     // Add a new tree node for this BasicBlock, and link it as a child of
340     // IDomNode
341     DomTreeNodeBase<typename GraphT::NodeType> *C =
342                     new DomTreeNodeBase<typename GraphT::NodeType>(W, IDomNode);
343     DT.DomTreeNodes[W] = IDomNode->addChild(C);
344   }
345
346   // Free temporary memory used to construct idom's
347   DT.IDoms.clear();
348   DT.Info.clear();
349   std::vector<typename GraphT::NodeType*>().swap(DT.Vertex);
350   
351   // FIXME: This does not work on PostDomTrees.  It seems likely that this is
352   // due to an error in the algorithm for post-dominators.  This really should
353   // be investigated and fixed at some point.
354   // DT.updateDFSNumbers();
355
356   // Start out with the DFS numbers being invalid.  Let them be computed if
357   // demanded.
358   DT.DFSInfoValid = false;
359 }
360
361 }
362
363 #endif