Maintain ETNode as part of DomTreeNode.
[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 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 //  PostDominatorTree Implementation
23 //===----------------------------------------------------------------------===//
24
25 char PostDominatorTree::ID = 0;
26 char PostDominanceFrontier::ID = 0;
27 char PostETForest::ID = 0;
28 static RegisterPass<PostDominatorTree>
29 F("postdomtree", "Post-Dominator Tree Construction", true);
30
31 unsigned PostDominatorTree::DFSPass(BasicBlock *V, InfoRec &VInfo,
32                                           unsigned N) {
33   std::vector<std::pair<BasicBlock *, InfoRec *> > workStack;
34   std::set<BasicBlock *> visited;
35   workStack.push_back(std::make_pair(V, &VInfo));
36
37   do {
38     BasicBlock *currentBB = workStack.back().first; 
39     InfoRec *currentVInfo = workStack.back().second;
40
41     // Visit each block only once.
42     if (visited.count(currentBB) == 0) {
43
44       visited.insert(currentBB);
45       currentVInfo->Semi = ++N;
46       currentVInfo->Label = currentBB;
47       
48       Vertex.push_back(currentBB);  // Vertex[n] = current;
49       // Info[currentBB].Ancestor = 0;     
50       // Ancestor[n] = 0
51       // Child[currentBB] = 0;
52       currentVInfo->Size = 1;       // Size[currentBB] = 1
53     }
54
55     // Visit children
56     bool visitChild = false;
57     for (pred_iterator PI = pred_begin(currentBB), PE = pred_end(currentBB); 
58          PI != PE && !visitChild; ++PI) {
59       InfoRec &SuccVInfo = Info[*PI];
60       if (SuccVInfo.Semi == 0) {
61         SuccVInfo.Parent = currentBB;
62         if (visited.count (*PI) == 0) {
63           workStack.push_back(std::make_pair(*PI, &SuccVInfo));   
64           visitChild = true;
65         }
66       }
67     }
68
69     // If all children are visited or if this block has no child then pop this
70     // block out of workStack.
71     if (!visitChild)
72       workStack.pop_back();
73
74   } while (!workStack.empty());
75
76   return N;
77 }
78
79 void PostDominatorTree::Compress(BasicBlock *V, InfoRec &VInfo) {
80   BasicBlock *VAncestor = VInfo.Ancestor;
81   InfoRec &VAInfo = Info[VAncestor];
82   if (VAInfo.Ancestor == 0)
83     return;
84   
85   Compress(VAncestor, VAInfo);
86   
87   BasicBlock *VAncestorLabel = VAInfo.Label;
88   BasicBlock *VLabel = VInfo.Label;
89   if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
90     VInfo.Label = VAncestorLabel;
91   
92   VInfo.Ancestor = VAInfo.Ancestor;
93 }
94
95 BasicBlock *PostDominatorTree::Eval(BasicBlock *V) {
96   InfoRec &VInfo = Info[V];
97
98   // Higher-complexity but faster implementation
99   if (VInfo.Ancestor == 0)
100     return V;
101   Compress(V, VInfo);
102   return VInfo.Label;
103 }
104
105 void PostDominatorTree::Link(BasicBlock *V, BasicBlock *W, 
106                                    InfoRec &WInfo) {
107   // Higher-complexity but faster implementation
108   WInfo.Ancestor = V;
109 }
110
111 void PostDominatorTree::calculate(Function &F) {
112   // Step #0: Scan the function looking for the root nodes of the post-dominance
113   // relationships.  These blocks, which have no successors, end with return and
114   // unwind instructions.
115   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
116     if (succ_begin(I) == succ_end(I))
117       Roots.push_back(I);
118   
119   Vertex.push_back(0);
120   
121   // Step #1: Number blocks in depth-first order and initialize variables used
122   // in later stages of the algorithm.
123   unsigned N = 0;
124   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
125     N = DFSPass(Roots[i], Info[Roots[i]], N);
126   
127   for (unsigned i = N; i >= 2; --i) {
128     BasicBlock *W = Vertex[i];
129     InfoRec &WInfo = Info[W];
130     
131     // Step #2: Calculate the semidominators of all vertices
132     for (succ_iterator SI = succ_begin(W), SE = succ_end(W); SI != SE; ++SI)
133       if (Info.count(*SI)) {  // Only if this predecessor is reachable!
134         unsigned SemiU = Info[Eval(*SI)].Semi;
135         if (SemiU < WInfo.Semi)
136           WInfo.Semi = SemiU;
137       }
138         
139     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
140     
141     BasicBlock *WParent = WInfo.Parent;
142     Link(WParent, W, WInfo);
143     
144     // Step #3: Implicitly define the immediate dominator of vertices
145     std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
146     while (!WParentBucket.empty()) {
147       BasicBlock *V = WParentBucket.back();
148       WParentBucket.pop_back();
149       BasicBlock *U = Eval(V);
150       IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
151     }
152   }
153   
154   // Step #4: Explicitly define the immediate dominator of each vertex
155   for (unsigned i = 2; i <= N; ++i) {
156     BasicBlock *W = Vertex[i];
157     BasicBlock *&WIDom = IDoms[W];
158     if (WIDom != Vertex[Info[W].Semi])
159       WIDom = IDoms[WIDom];
160   }
161   
162   if (Roots.empty()) return;
163
164   // Add a node for the root.  This node might be the actual root, if there is
165   // one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
166   // which postdominates all real exits if there are multiple exit blocks.
167   BasicBlock *Root = Roots.size() == 1 ? Roots[0] : 0;
168   ETNode *ERoot = new ETNode(Root);
169   ETNodes[Root] = ERoot;
170   DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0, ERoot);
171   
172   // Loop over all of the reachable blocks in the function...
173   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
174     if (BasicBlock *ImmPostDom = getIDom(I)) {  // Reachable block.
175       DomTreeNode *&BBNode = DomTreeNodes[I];
176       if (!BBNode) {  // Haven't calculated this node yet?
177                       // Get or calculate the node for the immediate dominator
178         DomTreeNode *IPDomNode = getNodeForBlock(ImmPostDom);
179         
180         // Add a new tree node for this BasicBlock, and link it as a child of
181         // IDomNode
182         ETNode *ET = new ETNode(I);
183         ETNodes[I] = ET;
184         DomTreeNode *C = new DomTreeNode(I, IPDomNode, ET);
185         DomTreeNodes[I] = C;
186         BBNode = IPDomNode->addChild(C);
187       }
188     }
189
190   // Free temporary memory used to construct idom's
191   IDoms.clear();
192   Info.clear();
193   std::vector<BasicBlock*>().swap(Vertex);
194
195   int dfsnum = 0;
196   // Iterate over all nodes in depth first order...
197   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
198     for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
199            E = idf_end(Roots[i]); I != E; ++I) {
200       if (!getNodeForBlock(*I)->getETNode()->hasFather())
201         getNodeForBlock(*I)->getETNode()->assignDFSNumber(dfsnum);
202     }
203   DFSInfoValid = true;
204 }
205
206
207 DomTreeNode *PostDominatorTree::getNodeForBlock(BasicBlock *BB) {
208   DomTreeNode *&BBNode = DomTreeNodes[BB];
209   if (BBNode) return BBNode;
210   
211   // Haven't calculated this node yet?  Get or calculate the node for the
212   // immediate postdominator.
213   BasicBlock *IPDom = getIDom(BB);
214   DomTreeNode *IPDomNode = getNodeForBlock(IPDom);
215   
216   // Add a new tree node for this BasicBlock, and link it as a child of
217   // IDomNode
218   ETNode *ET = new ETNode(BB);
219   ETNodes[BB] = ET;
220   DomTreeNode *C = new DomTreeNode(BB, IPDomNode, ET);
221   DomTreeNodes[BB] = C;
222   return BBNode = IPDomNode->addChild(C);
223 }
224
225 //===----------------------------------------------------------------------===//
226 // PostETForest Implementation
227 //===----------------------------------------------------------------------===//
228
229 static RegisterPass<PostETForest>
230 G("postetforest", "Post-ET-Forest Construction", true);
231
232 ETNode *PostETForest::getNodeForBlock(BasicBlock *BB) {
233   ETNode *&BBNode = Nodes[BB];
234   if (BBNode) return BBNode;
235
236   // Haven't calculated this node yet?  Get or calculate the node for the
237   // immediate dominator.
238   DomTreeNode *node = getAnalysis<PostDominatorTree>().getNode(BB);
239
240   // If we are unreachable, we may not have an immediate dominator.
241   if (!node)
242     return 0;
243   else if (!node->getIDom())
244     return BBNode = new ETNode(BB);
245   else {
246     ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
247     
248     // Add a new tree node for this BasicBlock, and link it as a child of
249     // IDomNode
250     BBNode = new ETNode(BB);
251     BBNode->setFather(IDomNode);
252     return BBNode;
253   }
254 }
255
256 void PostETForest::calculate(const PostDominatorTree &DT) {
257   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
258     Nodes[Roots[i]] = new ETNode(Roots[i]); // Add a node for the root
259
260   // Iterate over all nodes in inverse depth first order.
261   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
262     for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
263            E = idf_end(Roots[i]); I != E; ++I) {
264     BasicBlock *BB = *I;
265     ETNode *&BBNode = Nodes[BB];
266     if (!BBNode) {  
267       ETNode *IDomNode =  NULL;
268       DomTreeNode *node = DT.getNode(BB);
269       if (node && node->getIDom())
270         IDomNode = getNodeForBlock(node->getIDom()->getBlock());
271
272       // Add a new ETNode for this BasicBlock, and set it's parent
273       // to it's immediate dominator.
274       BBNode = new ETNode(BB);
275       if (IDomNode)          
276         BBNode->setFather(IDomNode);
277     }
278   }
279
280   int dfsnum = 0;
281   // Iterate over all nodes in depth first order...
282   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
283     for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
284            E = idf_end(Roots[i]); I != E; ++I) {
285         if (!getNodeForBlock(*I)->hasFather())
286           getNodeForBlock(*I)->assignDFSNumber(dfsnum);
287     }
288   DFSInfoValid = true;
289 }
290
291 //===----------------------------------------------------------------------===//
292 //  PostDominanceFrontier Implementation
293 //===----------------------------------------------------------------------===//
294
295 static RegisterPass<PostDominanceFrontier>
296 H("postdomfrontier", "Post-Dominance Frontier Construction", true);
297
298 const DominanceFrontier::DomSetType &
299 PostDominanceFrontier::calculate(const PostDominatorTree &DT,
300                                  const DomTreeNode *Node) {
301   // Loop over CFG successors to calculate DFlocal[Node]
302   BasicBlock *BB = Node->getBlock();
303   DomSetType &S = Frontiers[BB];       // The new set to fill in...
304   if (getRoots().empty()) return S;
305
306   if (BB)
307     for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB);
308          SI != SE; ++SI) {
309       // Does Node immediately dominate this predecessor?
310       DomTreeNode *SINode = DT[*SI];
311       if (SINode && SINode->getIDom() != Node)
312         S.insert(*SI);
313     }
314
315   // At this point, S is DFlocal.  Now we union in DFup's of our children...
316   // Loop through and visit the nodes that Node immediately dominates (Node's
317   // children in the IDomTree)
318   //
319   for (DomTreeNode::const_iterator
320          NI = Node->begin(), NE = Node->end(); NI != NE; ++NI) {
321     DomTreeNode *IDominee = *NI;
322     const DomSetType &ChildDF = calculate(DT, IDominee);
323
324     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
325     for (; CDFI != CDFE; ++CDFI) {
326       if (!DT.properlyDominates(Node, DT[*CDFI]))
327         S.insert(*CDFI);
328     }
329   }
330
331   return S;
332 }
333
334 // Ensure that this .cpp file gets linked when PostDominators.h is used.
335 DEFINING_FILE_FOR(PostDominanceFrontier)