Fix DFS walk.
[oota-llvm.git] / lib / Analysis / PostDominators.cpp
1 //===- PostDominators.cpp - Post-Dominator Calculation --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the post-dominator construction algorithms.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/PostDominators.h"
15 #include "llvm/Instructions.h"
16 #include "llvm/Support/CFG.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/SetOperations.h"
19 #include <iostream>
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 //  ImmediatePostDominators Implementation
24 //===----------------------------------------------------------------------===//
25
26 static RegisterPass<ImmediatePostDominators>
27 D("postidom", "Immediate Post-Dominators Construction", true);
28
29 unsigned ImmediatePostDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
30                                           unsigned N) {
31   std::vector<std::pair<BasicBlock *, InfoRec *> > workStack;
32   std::set<BasicBlock *> visited;
33   workStack.push_back(std::make_pair(V, &VInfo));
34
35   do {
36     BasicBlock *currentBB = workStack.back().first; 
37     InfoRec *currentVInfo = workStack.back().second;
38
39     // Visit each block only once.
40     if (visited.count(currentBB) == 0) {
41
42       visited.insert(currentBB);
43       currentVInfo->Semi = ++N;
44       currentVInfo->Label = currentBB;
45       
46       Vertex.push_back(currentBB);  // Vertex[n] = current;
47       // Info[currentBB].Ancestor = 0;     
48       // Ancestor[n] = 0
49       // Child[currentBB] = 0;
50       currentVInfo->Size = 1;       // Size[currentBB] = 1
51     }
52
53     // Visit children
54     bool visitChild = false;
55     for (pred_iterator PI = pred_begin(currentBB), PE = pred_end(currentBB); 
56          PI != PE && !visitChild; ++PI) {
57       InfoRec &SuccVInfo = Info[*PI];
58       if (SuccVInfo.Semi == 0) {
59         SuccVInfo.Parent = currentBB;
60         if (visited.count (*PI) == 0) {
61           workStack.push_back(std::make_pair(*PI, &SuccVInfo));   
62           visitChild = true;
63         }
64       }
65     }
66
67     // If all children are visited or if this block has no child then pop this
68     // block out of workStack.
69     if (!visitChild)
70       workStack.pop_back();
71
72   } while (!workStack.empty());
73
74   return N;
75 }
76
77 void ImmediatePostDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
78   BasicBlock *VAncestor = VInfo.Ancestor;
79   InfoRec &VAInfo = Info[VAncestor];
80   if (VAInfo.Ancestor == 0)
81     return;
82   
83   Compress(VAncestor, VAInfo);
84   
85   BasicBlock *VAncestorLabel = VAInfo.Label;
86   BasicBlock *VLabel = VInfo.Label;
87   if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
88     VInfo.Label = VAncestorLabel;
89   
90   VInfo.Ancestor = VAInfo.Ancestor;
91 }
92
93 BasicBlock *ImmediatePostDominators::Eval(BasicBlock *V) {
94   InfoRec &VInfo = Info[V];
95
96   // Higher-complexity but faster implementation
97   if (VInfo.Ancestor == 0)
98     return V;
99   Compress(V, VInfo);
100   return VInfo.Label;
101 }
102
103 void ImmediatePostDominators::Link(BasicBlock *V, BasicBlock *W, 
104                                    InfoRec &WInfo) {
105   // Higher-complexity but faster implementation
106   WInfo.Ancestor = V;
107 }
108
109 bool ImmediatePostDominators::runOnFunction(Function &F) {
110   IDoms.clear();     // Reset from the last time we were run...
111   Roots.clear();
112
113   // Step #0: Scan the function looking for the root nodes of the post-dominance
114   // relationships.  These blocks, which have no successors, end with return and
115   // unwind instructions.
116   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
117     if (succ_begin(I) == succ_end(I))
118       Roots.push_back(I);
119   
120   Vertex.push_back(0);
121   
122   // Step #1: Number blocks in depth-first order and initialize variables used
123   // in later stages of the algorithm.
124   unsigned N = 0;
125   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
126     N = DFSPass(Roots[i], Info[Roots[i]], N);
127   
128   for (unsigned i = N; i >= 2; --i) {
129     BasicBlock *W = Vertex[i];
130     InfoRec &WInfo = Info[W];
131     
132     // Step #2: Calculate the semidominators of all vertices
133     for (succ_iterator SI = succ_begin(W), SE = succ_end(W); SI != SE; ++SI)
134       if (Info.count(*SI)) {  // Only if this predecessor is reachable!
135         unsigned SemiU = Info[Eval(*SI)].Semi;
136         if (SemiU < WInfo.Semi)
137           WInfo.Semi = SemiU;
138       }
139         
140     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
141     
142     BasicBlock *WParent = WInfo.Parent;
143     Link(WParent, W, WInfo);
144     
145     // Step #3: Implicitly define the immediate dominator of vertices
146     std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
147     while (!WParentBucket.empty()) {
148       BasicBlock *V = WParentBucket.back();
149       WParentBucket.pop_back();
150       BasicBlock *U = Eval(V);
151       IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
152     }
153   }
154   
155   // Step #4: Explicitly define the immediate dominator of each vertex
156   for (unsigned i = 2; i <= N; ++i) {
157     BasicBlock *W = Vertex[i];
158     BasicBlock *&WIDom = IDoms[W];
159     if (WIDom != Vertex[Info[W].Semi])
160       WIDom = IDoms[WIDom];
161   }
162   
163   // Free temporary memory used to construct idom's
164   Info.clear();
165   std::vector<BasicBlock*>().swap(Vertex);
166   
167   return false;
168 }
169
170 //===----------------------------------------------------------------------===//
171 //  PostDominatorSet Implementation
172 //===----------------------------------------------------------------------===//
173
174 static RegisterPass<PostDominatorSet>
175 B("postdomset", "Post-Dominator Set Construction", true);
176
177 // Postdominator set construction.  This converts the specified function to only
178 // have a single exit node (return stmt), then calculates the post dominance
179 // sets for the function.
180 //
181 bool PostDominatorSet::runOnFunction(Function &F) {
182   // Scan the function looking for the root nodes of the post-dominance
183   // relationships.  These blocks end with return and unwind instructions.
184   // While we are iterating over the function, we also initialize all of the
185   // domsets to empty.
186   Roots.clear();
187   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
188     if (succ_begin(I) == succ_end(I))
189       Roots.push_back(I);
190
191   // If there are no exit nodes for the function, postdomsets are all empty.
192   // This can happen if the function just contains an infinite loop, for
193   // example.
194   ImmediatePostDominators &IPD = getAnalysis<ImmediatePostDominators>();
195   Doms.clear();   // Reset from the last time we were run...
196   if (Roots.empty()) return false;
197
198   // If we have more than one root, we insert an artificial "null" exit, which
199   // has "virtual edges" to each of the real exit nodes.
200   //if (Roots.size() > 1)
201   //  Doms[0].insert(0);
202
203   // Root nodes only dominate themselves.
204   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
205     Doms[Roots[i]].insert(Roots[i]);
206   
207   // Loop over all of the blocks in the function, calculating dominator sets for
208   // each function.
209   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
210     if (BasicBlock *IPDom = IPD[I]) {   // Get idom if block is reachable
211       DomSetType &DS = Doms[I];
212       assert(DS.empty() && "PostDomset already filled in for this block?");
213       DS.insert(I);  // Blocks always dominate themselves
214
215       // Insert all dominators into the set...
216       while (IPDom) {
217         // If we have already computed the dominator sets for our immediate post
218         // dominator, just use it instead of walking all the way up to the root.
219         DomSetType &IPDS = Doms[IPDom];
220         if (!IPDS.empty()) {
221           DS.insert(IPDS.begin(), IPDS.end());
222           break;
223         } else {
224           DS.insert(IPDom);
225           IPDom = IPD[IPDom];
226         }
227       }
228     } else {
229       // Ensure that every basic block has at least an empty set of nodes.  This
230       // is important for the case when there is unreachable blocks.
231       Doms[I];
232     }
233
234   return false;
235 }
236
237 //===----------------------------------------------------------------------===//
238 //  PostDominatorTree Implementation
239 //===----------------------------------------------------------------------===//
240
241 static RegisterPass<PostDominatorTree>
242 F("postdomtree", "Post-Dominator Tree Construction", true);
243
244 DominatorTreeBase::Node *PostDominatorTree::getNodeForBlock(BasicBlock *BB) {
245   Node *&BBNode = Nodes[BB];
246   if (BBNode) return BBNode;
247   
248   // Haven't calculated this node yet?  Get or calculate the node for the
249   // immediate postdominator.
250   BasicBlock *IPDom = getAnalysis<ImmediatePostDominators>()[BB];
251   Node *IPDomNode = getNodeForBlock(IPDom);
252   
253   // Add a new tree node for this BasicBlock, and link it as a child of
254   // IDomNode
255   return BBNode = IPDomNode->addChild(new Node(BB, IPDomNode));
256 }
257
258 void PostDominatorTree::calculate(const ImmediatePostDominators &IPD) {
259   if (Roots.empty()) return;
260
261   // Add a node for the root.  This node might be the actual root, if there is
262   // one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
263   // which postdominates all real exits if there are multiple exit blocks.
264   BasicBlock *Root = Roots.size() == 1 ? Roots[0] : 0;
265   Nodes[Root] = RootNode = new Node(Root, 0);
266   
267   Function *F = Roots[0]->getParent();
268   // Loop over all of the reachable blocks in the function...
269   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
270     if (BasicBlock *ImmPostDom = IPD.get(I)) {  // Reachable block.
271       Node *&BBNode = Nodes[I];
272       if (!BBNode) {  // Haven't calculated this node yet?
273                       // Get or calculate the node for the immediate dominator
274         Node *IPDomNode = getNodeForBlock(ImmPostDom);
275         
276         // Add a new tree node for this BasicBlock, and link it as a child of
277         // IDomNode
278         BBNode = IPDomNode->addChild(new Node(I, IPDomNode));
279       }
280     }
281 }
282
283 //===----------------------------------------------------------------------===//
284 // PostETForest Implementation
285 //===----------------------------------------------------------------------===//
286
287 static RegisterPass<PostETForest>
288 G("postetforest", "Post-ET-Forest Construction", true);
289
290 ETNode *PostETForest::getNodeForBlock(BasicBlock *BB) {
291   ETNode *&BBNode = Nodes[BB];
292   if (BBNode) return BBNode;
293
294   // Haven't calculated this node yet?  Get or calculate the node for the
295   // immediate dominator.
296   BasicBlock *IDom = getAnalysis<ImmediatePostDominators>()[BB];
297
298   // If we are unreachable, we may not have an immediate dominator.
299   if (!IDom)
300     return BBNode = new ETNode(BB);
301   else {
302     ETNode *IDomNode = getNodeForBlock(IDom);
303     
304     // Add a new tree node for this BasicBlock, and link it as a child of
305     // IDomNode
306     BBNode = new ETNode(BB);
307     BBNode->setFather(IDomNode);
308     return BBNode;
309   }
310 }
311
312 void PostETForest::calculate(const ImmediatePostDominators &ID) {
313   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
314     Nodes[Roots[i]] = new ETNode(Roots[i]); // Add a node for the root
315
316   // Iterate over all nodes in inverse depth first order.
317   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
318     for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
319            E = idf_end(Roots[i]); I != E; ++I) {
320     BasicBlock *BB = *I;
321     ETNode *&BBNode = Nodes[BB];
322     if (!BBNode) {  
323       ETNode *IDomNode =  NULL;
324
325       if (ID.get(BB))
326         IDomNode = getNodeForBlock(ID.get(BB));
327
328       // Add a new ETNode for this BasicBlock, and set it's parent
329       // to it's immediate dominator.
330       BBNode = new ETNode(BB);
331       if (IDomNode)          
332         BBNode->setFather(IDomNode);
333     }
334   }
335
336   int dfsnum = 0;
337   // Iterate over all nodes in depth first order...
338   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
339     for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
340            E = idf_end(Roots[i]); I != E; ++I) {
341         if (!getNodeForBlock(*I)->hasFather())
342           getNodeForBlock(*I)->assignDFSNumber(dfsnum);
343     }
344   DFSInfoValid = true;
345 }
346
347 //===----------------------------------------------------------------------===//
348 //  PostDominanceFrontier Implementation
349 //===----------------------------------------------------------------------===//
350
351 static RegisterPass<PostDominanceFrontier>
352 H("postdomfrontier", "Post-Dominance Frontier Construction", true);
353
354 const DominanceFrontier::DomSetType &
355 PostDominanceFrontier::calculate(const PostDominatorTree &DT,
356                                  const DominatorTree::Node *Node) {
357   // Loop over CFG successors to calculate DFlocal[Node]
358   BasicBlock *BB = Node->getBlock();
359   DomSetType &S = Frontiers[BB];       // The new set to fill in...
360   if (getRoots().empty()) return S;
361
362   if (BB)
363     for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB);
364          SI != SE; ++SI)
365       // Does Node immediately dominate this predecessor?
366       if (DT[*SI]->getIDom() != Node)
367         S.insert(*SI);
368
369   // At this point, S is DFlocal.  Now we union in DFup's of our children...
370   // Loop through and visit the nodes that Node immediately dominates (Node's
371   // children in the IDomTree)
372   //
373   for (PostDominatorTree::Node::const_iterator
374          NI = Node->begin(), NE = Node->end(); NI != NE; ++NI) {
375     DominatorTree::Node *IDominee = *NI;
376     const DomSetType &ChildDF = calculate(DT, IDominee);
377
378     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
379     for (; CDFI != CDFE; ++CDFI) {
380       if (!Node->properlyDominates(DT[*CDFI]))
381         S.insert(*CDFI);
382     }
383   }
384
385   return S;
386 }
387
388 // Ensure that this .cpp file gets linked when PostDominators.h is used.
389 DEFINING_FILE_FOR(PostDominanceFrontier)