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