9c960e3b0d43ea9bb7233d75559f815c56ad905a
[oota-llvm.git] / lib / Analysis / PostDominators.cpp
1 //===- DominatorSet.cpp - Dominator Set Calculation --------------*- C++ -*--=//
2 //
3 // This file provides a simple class to calculate the dominator set of a
4 // function.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Analysis/Dominators.h"
9 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
10 #include "llvm/Support/CFG.h"
11 #include "llvm/Assembly/Writer.h"
12 #include "Support/DepthFirstIterator.h"
13 #include "Support/STLExtras.h"
14 #include "Support/SetOperations.h"
15 #include <algorithm>
16 using std::set;
17
18 //===----------------------------------------------------------------------===//
19 //  DominatorSet Implementation
20 //===----------------------------------------------------------------------===//
21
22 static RegisterAnalysis<DominatorSet>
23 A("domset", "Dominator Set Construction");
24 static RegisterAnalysis<PostDominatorSet>
25 B("postdomset", "Post-Dominator Set Construction");
26
27 AnalysisID DominatorSet::ID = A;
28 AnalysisID PostDominatorSet::ID = B;
29
30 // dominates - Return true if A dominates B.  This performs the special checks
31 // neccesary if A and B are in the same basic block.
32 //
33 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
34   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
35   if (BBA != BBB) return dominates(BBA, BBB);
36   
37   // Loop through the basic block until we find A or B.
38   BasicBlock::iterator I = BBA->begin();
39   for (; &*I != A && &*I != B; ++I) /*empty*/;
40   
41   // A dominates B if it is found first in the basic block...
42   return &*I == A;
43 }
44
45 // runOnFunction - This method calculates the forward dominator sets for the
46 // specified function.
47 //
48 bool DominatorSet::runOnFunction(Function &F) {
49   Doms.clear();   // Reset from the last time we were run...
50   Root = &F.getEntryNode();
51   assert(pred_begin(Root) == pred_end(Root) &&
52          "Root node has predecessors in function!");
53
54   bool Changed;
55   do {
56     Changed = false;
57
58     DomSetType WorkingSet;
59     df_iterator<Function*> It = df_begin(&F), End = df_end(&F);
60     for ( ; It != End; ++It) {
61       BasicBlock *BB = *It;
62       pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
63       if (PI != PEnd) {                // Is there SOME predecessor?
64         // Loop until we get to a predecessor that has had it's dom set filled
65         // in at least once.  We are guaranteed to have this because we are
66         // traversing the graph in DFO and have handled start nodes specially.
67         //
68         while (Doms[*PI].size() == 0) ++PI;
69         WorkingSet = Doms[*PI];
70
71         for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
72           DomSetType &PredSet = Doms[*PI];
73           if (PredSet.size())
74             set_intersect(WorkingSet, PredSet);
75         }
76       }
77         
78       WorkingSet.insert(BB);           // A block always dominates itself
79       DomSetType &BBSet = Doms[BB];
80       if (BBSet != WorkingSet) {
81         BBSet.swap(WorkingSet);        // Constant time operation!
82         Changed = true;                // The sets changed.
83       }
84       WorkingSet.clear();              // Clear out the set for next iteration
85     }
86   } while (Changed);
87   return false;
88 }
89
90
91 // Postdominator set construction.  This converts the specified function to only
92 // have a single exit node (return stmt), then calculates the post dominance
93 // sets for the function.
94 //
95 bool PostDominatorSet::runOnFunction(Function &F) {
96   Doms.clear();   // Reset from the last time we were run...
97   // Since we require that the unify all exit nodes pass has been run, we know
98   // that there can be at most one return instruction in the function left.
99   // Get it.
100   //
101   Root = getAnalysis<UnifyFunctionExitNodes>().getExitNode();
102
103   if (Root == 0) {  // No exit node for the function?  Postdomsets are all empty
104     for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
105       Doms[FI] = DomSetType();
106     return false;
107   }
108
109   bool Changed;
110   do {
111     Changed = false;
112
113     set<const BasicBlock*> Visited;
114     DomSetType WorkingSet;
115     idf_iterator<BasicBlock*> It = idf_begin(Root), End = idf_end(Root);
116     for ( ; It != End; ++It) {
117       BasicBlock *BB = *It;
118       succ_iterator PI = succ_begin(BB), PEnd = succ_end(BB);
119       if (PI != PEnd) {                // Is there SOME predecessor?
120         // Loop until we get to a successor that has had it's dom set filled
121         // in at least once.  We are guaranteed to have this because we are
122         // traversing the graph in DFO and have handled start nodes specially.
123         //
124         while (Doms[*PI].size() == 0) ++PI;
125         WorkingSet = Doms[*PI];
126
127         for (++PI; PI != PEnd; ++PI) { // Intersect all of the successor sets
128           DomSetType &PredSet = Doms[*PI];
129           if (PredSet.size())
130             set_intersect(WorkingSet, PredSet);
131         }
132       }
133         
134       WorkingSet.insert(BB);           // A block always dominates itself
135       DomSetType &BBSet = Doms[BB];
136       if (BBSet != WorkingSet) {
137         BBSet.swap(WorkingSet);        // Constant time operation!
138         Changed = true;                // The sets changed.
139       }
140       WorkingSet.clear();              // Clear out the set for next iteration
141     }
142   } while (Changed);
143   return false;
144 }
145
146 // getAnalysisUsage - This obviously provides a post-dominator set, but it also
147 // requires the UnifyFunctionExitNodes pass.
148 //
149 void PostDominatorSet::getAnalysisUsage(AnalysisUsage &AU) const {
150   AU.setPreservesAll();
151   AU.addProvided(ID);
152   AU.addRequired(UnifyFunctionExitNodes::ID);
153 }
154
155 static ostream &operator<<(ostream &o, const set<BasicBlock*> &BBs) {
156   for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
157        I != E; ++I) {
158     o << "  ";
159     WriteAsOperand(o, *I, false);
160     o << "\n";
161    }
162   return o;
163 }
164
165 void DominatorSetBase::print(std::ostream &o) const {
166   for (const_iterator I = begin(), E = end(); I != E; ++I)
167     o << "=============================--------------------------------\n"
168       << "\nDominator Set For Basic Block\n" << I->first
169       << "-------------------------------\n" << I->second << "\n";
170 }
171
172 //===----------------------------------------------------------------------===//
173 //  ImmediateDominators Implementation
174 //===----------------------------------------------------------------------===//
175
176 static RegisterAnalysis<ImmediateDominators>
177 C("idom", "Immediate Dominators Construction");
178 static RegisterAnalysis<ImmediatePostDominators>
179 D("postidom", "Immediate Post-Dominators Construction");
180
181 AnalysisID ImmediateDominators::ID = C;
182 AnalysisID ImmediatePostDominators::ID = D;
183
184 // calcIDoms - Calculate the immediate dominator mapping, given a set of
185 // dominators for every basic block.
186 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
187   // Loop over all of the nodes that have dominators... figuring out the IDOM
188   // for each node...
189   //
190   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end(); 
191        DI != DEnd; ++DI) {
192     BasicBlock *BB = DI->first;
193     const DominatorSet::DomSetType &Dominators = DI->second;
194     unsigned DomSetSize = Dominators.size();
195     if (DomSetSize == 1) continue;  // Root node... IDom = null
196
197     // Loop over all dominators of this node.  This corresponds to looping over
198     // nodes in the dominator chain, looking for a node whose dominator set is
199     // equal to the current nodes, except that the current node does not exist
200     // in it.  This means that it is one level higher in the dom chain than the
201     // current node, and it is our idom!
202     //
203     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
204     DominatorSet::DomSetType::const_iterator End = Dominators.end();
205     for (; I != End; ++I) {   // Iterate over dominators...
206       // All of our dominators should form a chain, where the number of elements
207       // in the dominator set indicates what level the node is at in the chain.
208       // We want the node immediately above us, so it will have an identical 
209       // dominator set, except that BB will not dominate it... therefore it's
210       // dominator set size will be one less than BB's...
211       //
212       if (DS.getDominators(*I).size() == DomSetSize - 1) {
213         IDoms[BB] = *I;
214         break;
215       }
216     }
217   }
218 }
219
220 void ImmediateDominatorsBase::print(ostream &o) const {
221   for (const_iterator I = begin(), E = end(); I != E; ++I)
222     o << "=============================--------------------------------\n"
223       << "\nImmediate Dominator For Basic Block\n" << *I->first
224       << "is: \n" << *I->second << "\n";
225 }
226
227
228 //===----------------------------------------------------------------------===//
229 //  DominatorTree Implementation
230 //===----------------------------------------------------------------------===//
231
232 static RegisterAnalysis<DominatorTree>
233 E("domtree", "Dominator Tree Construction");
234 static RegisterAnalysis<PostDominatorTree>
235 F("postdomtree", "Post-Dominator Tree Construction");
236
237 AnalysisID DominatorTree::ID = E;
238 AnalysisID PostDominatorTree::ID = F;
239
240 // DominatorTreeBase::reset - Free all of the tree node memory.
241 //
242 void DominatorTreeBase::reset() { 
243   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
244     delete I->second;
245   Nodes.clear();
246 }
247
248
249 void DominatorTree::calculate(const DominatorSet &DS) {
250   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
251
252   // Iterate over all nodes in depth first order...
253   for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
254        I != E; ++I) {
255     BasicBlock *BB = *I;
256     const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
257     unsigned DomSetSize = Dominators.size();
258     if (DomSetSize == 1) continue;  // Root node... IDom = null
259       
260     // Loop over all dominators of this node. This corresponds to looping over
261     // nodes in the dominator chain, looking for a node whose dominator set is
262     // equal to the current nodes, except that the current node does not exist
263     // in it. This means that it is one level higher in the dom chain than the
264     // current node, and it is our idom!  We know that we have already added
265     // a DominatorTree node for our idom, because the idom must be a
266     // predecessor in the depth first order that we are iterating through the
267     // function.
268     //
269     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
270     DominatorSet::DomSetType::const_iterator End = Dominators.end();
271     for (; I != End; ++I) {   // Iterate over dominators...
272       // All of our dominators should form a chain, where the number of
273       // elements in the dominator set indicates what level the node is at in
274       // the chain.  We want the node immediately above us, so it will have
275       // an identical dominator set, except that BB will not dominate it...
276       // therefore it's dominator set size will be one less than BB's...
277       //
278       if (DS.getDominators(*I).size() == DomSetSize - 1) {
279         // We know that the immediate dominator should already have a node, 
280         // because we are traversing the CFG in depth first order!
281         //
282         Node *IDomNode = Nodes[*I];
283         assert(IDomNode && "No node for IDOM?");
284         
285         // Add a new tree node for this BasicBlock, and link it as a child of
286         // IDomNode
287         Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
288         break;
289       }
290     }
291   }
292 }
293
294
295 void PostDominatorTree::calculate(const PostDominatorSet &DS) {
296   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
297
298   if (Root) {
299     // Iterate over all nodes in depth first order...
300     for (idf_iterator<BasicBlock*> I = idf_begin(Root), E = idf_end(Root);
301          I != E; ++I) {
302       BasicBlock *BB = *I;
303       const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
304       unsigned DomSetSize = Dominators.size();
305       if (DomSetSize == 1) continue;  // Root node... IDom = null
306       
307       // Loop over all dominators of this node.  This corresponds to looping
308       // over nodes in the dominator chain, looking for a node whose dominator
309       // set is equal to the current nodes, except that the current node does
310       // not exist in it.  This means that it is one level higher in the dom
311       // chain than the current node, and it is our idom!  We know that we have
312       // already added a DominatorTree node for our idom, because the idom must
313       // be a predecessor in the depth first order that we are iterating through
314       // the function.
315       //
316       DominatorSet::DomSetType::const_iterator I = Dominators.begin();
317       DominatorSet::DomSetType::const_iterator End = Dominators.end();
318       for (; I != End; ++I) {   // Iterate over dominators...
319         // All of our dominators should form a chain, where the number
320         // of elements in the dominator set indicates what level the
321         // node is at in the chain.  We want the node immediately
322         // above us, so it will have an identical dominator set,
323         // except that BB will not dominate it... therefore it's
324         // dominator set size will be one less than BB's...
325         //
326         if (DS.getDominators(*I).size() == DomSetSize - 1) {
327           // We know that the immediate dominator should already have a node, 
328           // because we are traversing the CFG in depth first order!
329           //
330           Node *IDomNode = Nodes[*I];
331           assert(IDomNode && "No node for IDOM?");
332           
333           // Add a new tree node for this BasicBlock, and link it as a child of
334           // IDomNode
335           Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
336           break;
337         }
338       }
339     }
340   }
341 }
342
343 static ostream &operator<<(ostream &o, const DominatorTreeBase::Node *Node) {
344   return o << Node->getNode()
345            << "\n------------------------------------------\n";
346 }
347
348 static void PrintDomTree(const DominatorTreeBase::Node *N, ostream &o,
349                          unsigned Lev) {
350   o << "Level #" << Lev << ":  " << N;
351   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
352        I != E; ++I) {
353     PrintDomTree(*I, o, Lev+1);
354   }
355 }
356
357 void DominatorTreeBase::print(std::ostream &o) const {
358   o << "=============================--------------------------------\n"
359     << "Inorder Dominator Tree:\n";
360   PrintDomTree(Nodes.find(getRoot())->second, o, 1);
361 }
362
363
364 //===----------------------------------------------------------------------===//
365 //  DominanceFrontier Implementation
366 //===----------------------------------------------------------------------===//
367
368 static RegisterAnalysis<DominanceFrontier>
369 G("domfrontier", "Dominance Frontier Construction");
370 static RegisterAnalysis<PostDominanceFrontier>
371 H("postdomfrontier", "Post-Dominance Frontier Construction");
372
373 AnalysisID DominanceFrontier::ID = G;
374 AnalysisID PostDominanceFrontier::ID = H;
375
376 const DominanceFrontier::DomSetType &
377 DominanceFrontier::calculate(const DominatorTree &DT, 
378                              const DominatorTree::Node *Node) {
379   // Loop over CFG successors to calculate DFlocal[Node]
380   BasicBlock *BB = Node->getNode();
381   DomSetType &S = Frontiers[BB];       // The new set to fill in...
382
383   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
384        SI != SE; ++SI) {
385     // Does Node immediately dominate this successor?
386     if (DT[*SI]->getIDom() != Node)
387       S.insert(*SI);
388   }
389
390   // At this point, S is DFlocal.  Now we union in DFup's of our children...
391   // Loop through and visit the nodes that Node immediately dominates (Node's
392   // children in the IDomTree)
393   //
394   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
395        NI != NE; ++NI) {
396     DominatorTree::Node *IDominee = *NI;
397     const DomSetType &ChildDF = calculate(DT, IDominee);
398
399     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
400     for (; CDFI != CDFE; ++CDFI) {
401       if (!Node->dominates(DT[*CDFI]))
402         S.insert(*CDFI);
403     }
404   }
405
406   return S;
407 }
408
409 const DominanceFrontier::DomSetType &
410 PostDominanceFrontier::calculate(const PostDominatorTree &DT, 
411                                  const DominatorTree::Node *Node) {
412   // Loop over CFG successors to calculate DFlocal[Node]
413   BasicBlock *BB = Node->getNode();
414   DomSetType &S = Frontiers[BB];       // The new set to fill in...
415   if (!Root) return S;
416
417   for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB);
418        SI != SE; ++SI) {
419     // Does Node immediately dominate this predeccessor?
420     if (DT[*SI]->getIDom() != Node)
421       S.insert(*SI);
422   }
423
424   // At this point, S is DFlocal.  Now we union in DFup's of our children...
425   // Loop through and visit the nodes that Node immediately dominates (Node's
426   // children in the IDomTree)
427   //
428   for (PostDominatorTree::Node::const_iterator
429          NI = Node->begin(), NE = Node->end(); NI != NE; ++NI) {
430     DominatorTree::Node *IDominee = *NI;
431     const DomSetType &ChildDF = calculate(DT, IDominee);
432
433     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
434     for (; CDFI != CDFE; ++CDFI) {
435       if (!Node->dominates(DT[*CDFI]))
436         S.insert(*CDFI);
437     }
438   }
439
440   return S;
441 }
442
443 void DominanceFrontierBase::print(std::ostream &o) const {
444   for (const_iterator I = begin(), E = end(); I != E; ++I) {
445     o << "=============================--------------------------------\n"
446       << "\nDominance Frontier For Basic Block\n";
447     WriteAsOperand(o, I->first, false);
448     o << " is: \n" << I->second << "\n";
449   }
450 }