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