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