24ff43999427fa77e6d4d414253f9a1e0c7a1db5
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- DominatorSet.cpp - Dominator Set Calculation --------------*- C++ -*--=//
2 //
3 // This file provides a simple class to calculate the dominator set of a method.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Analysis/Dominators.h"
8 #include "llvm/Analysis/SimplifyCFG.h"   // To get cfg::UnifyAllExitNodes
9 #include "llvm/CFG.h"
10 #include "llvm/Support/STLExtras.h"
11 #include <algorithm>
12
13 //===----------------------------------------------------------------------===//
14 //  Helper Template
15 //===----------------------------------------------------------------------===//
16
17 // set_intersect - Identical to set_intersection, except that it works on 
18 // set<>'s and is nicer to use.  Functionally, this iterates through S1, 
19 // removing elements that are not contained in S2.
20 //
21 template <class Ty, class Ty2>
22 void set_intersect(set<Ty> &S1, const set<Ty2> &S2) {
23   for (typename set<Ty>::iterator I = S1.begin(); I != S1.end();) {
24     const Ty &E = *I;
25     ++I;
26     if (!S2.count(E)) S1.erase(E);   // Erase element if not in S2
27   }
28 }
29
30 //===----------------------------------------------------------------------===//
31 //  DominatorBase Implementation
32 //===----------------------------------------------------------------------===//
33
34 bool cfg::DominatorBase::isPostDominator() const { 
35   // Root can be null if there is no exit node from the CFG and is postdom set
36   return Root == 0 || Root != Root->getParent()->front();
37 }
38
39
40 //===----------------------------------------------------------------------===//
41 //  DominatorSet Implementation
42 //===----------------------------------------------------------------------===//
43
44 // DominatorSet ctor - Build either the dominator set or the post-dominator
45 // set for a method...
46 //
47 cfg::DominatorSet::DominatorSet(const Method *M) : DominatorBase(M->front()) {
48   calcForwardDominatorSet(M);
49 }
50
51 // calcForwardDominatorSet - This method calculates the forward dominator sets
52 // for the specified method.
53 //
54 void cfg::DominatorSet::calcForwardDominatorSet(const Method *M) {
55   assert(Root && M && "Can't build dominator set of null method!");
56   bool Changed;
57   do {
58     Changed = false;
59
60     DomSetType WorkingSet;
61     df_const_iterator It = df_begin(M), End = df_end(M);
62     for ( ; It != End; ++It) {
63       const BasicBlock *BB = *It;
64       pred_const_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
65       if (PI != PEnd) {                // Is there SOME predecessor?
66         // Loop until we get to a predecessor that has had it's dom set filled
67         // in at least once.  We are guaranteed to have this because we are
68         // traversing the graph in DFO and have handled start nodes specially.
69         //
70         while (Doms[*PI].size() == 0) ++PI;
71         WorkingSet = Doms[*PI];
72
73         for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
74           DomSetType &PredSet = Doms[*PI];
75           if (PredSet.size())
76             set_intersect(WorkingSet, PredSet);
77         }
78       }
79         
80       WorkingSet.insert(BB);           // A block always dominates itself
81       DomSetType &BBSet = Doms[BB];
82       if (BBSet != WorkingSet) {
83         BBSet.swap(WorkingSet);        // Constant time operation!
84         Changed = true;                // The sets changed.
85       }
86       WorkingSet.clear();              // Clear out the set for next iteration
87     }
88   } while (Changed);
89 }
90
91 // Postdominator set constructor.  This ctor converts the specified method to
92 // only have a single exit node (return stmt), then calculates the post
93 // dominance sets for the method.
94 //
95 cfg::DominatorSet::DominatorSet(Method *M, bool PostDomSet)
96   : DominatorBase(M->front()) {
97   if (!PostDomSet) { calcForwardDominatorSet(M); return; }
98
99   Root = cfg::UnifyAllExitNodes(M);
100   if (Root == 0) {  // No exit node for the method?  Postdomsets are all empty
101     for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
102       Doms[*MI] = DomSetType();
103     return;
104   }
105
106   bool Changed;
107   do {
108     Changed = false;
109
110     set<const BasicBlock*> Visited;
111     DomSetType WorkingSet;
112     idf_const_iterator It = idf_begin(Root), End = idf_end(Root);
113     for ( ; It != End; ++It) {
114       const BasicBlock *BB = *It;
115       succ_const_iterator PI = succ_begin(BB), PEnd = succ_end(BB);
116       if (PI != PEnd) {                // Is there SOME predecessor?
117         // Loop until we get to a successor that has had it's dom set filled
118         // in at least once.  We are guaranteed to have this because we are
119         // traversing the graph in DFO and have handled start nodes specially.
120         //
121         while (Doms[*PI].size() == 0) ++PI;
122         WorkingSet = Doms[*PI];
123
124         for (++PI; PI != PEnd; ++PI) { // Intersect all of the successor sets
125           DomSetType &PredSet = Doms[*PI];
126           if (PredSet.size())
127             set_intersect(WorkingSet, PredSet);
128         }
129       }
130         
131       WorkingSet.insert(BB);           // A block always dominates itself
132       DomSetType &BBSet = Doms[BB];
133       if (BBSet != WorkingSet) {
134         BBSet.swap(WorkingSet);        // Constant time operation!
135         Changed = true;                // The sets changed.
136       }
137       WorkingSet.clear();              // Clear out the set for next iteration
138     }
139   } while (Changed);
140 }
141
142
143 //===----------------------------------------------------------------------===//
144 //  ImmediateDominators Implementation
145 //===----------------------------------------------------------------------===//
146
147 // calcIDoms - Calculate the immediate dominator mapping, given a set of
148 // dominators for every basic block.
149 void cfg::ImmediateDominators::calcIDoms(const DominatorSet &DS) {
150   // Loop over all of the nodes that have dominators... figuring out the IDOM
151   // for each node...
152   //
153   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end(); 
154        DI != DEnd; ++DI) {
155     const BasicBlock *BB = DI->first;
156     const DominatorSet::DomSetType &Dominators = DI->second;
157     unsigned DomSetSize = Dominators.size();
158     if (DomSetSize == 1) continue;  // Root node... IDom = null
159
160     // Loop over all dominators of this node.  This corresponds to looping over
161     // nodes in the dominator chain, looking for a node whose dominator set is
162     // equal to the current nodes, except that the current node does not exist
163     // in it.  This means that it is one level higher in the dom chain than the
164     // current node, and it is our idom!
165     //
166     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
167     DominatorSet::DomSetType::const_iterator End = Dominators.end();
168     for (; I != End; ++I) {   // Iterate over dominators...
169       // All of our dominators should form a chain, where the number of elements
170       // in the dominator set indicates what level the node is at in the chain.
171       // We want the node immediately above us, so it will have an identical 
172       // dominator set, except that BB will not dominate it... therefore it's
173       // dominator set size will be one less than BB's...
174       //
175       if (DS.getDominators(*I).size() == DomSetSize - 1) {
176         IDoms[BB] = *I;
177         break;
178       }
179     }
180   }
181 }
182
183
184 //===----------------------------------------------------------------------===//
185 //  DominatorTree Implementation
186 //===----------------------------------------------------------------------===//
187
188 // DominatorTree dtor - Free all of the tree node memory.
189 //
190 cfg::DominatorTree::~DominatorTree() { 
191   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
192     delete I->second;
193 }
194
195
196 cfg::DominatorTree::DominatorTree(const ImmediateDominators &IDoms) 
197   : DominatorBase(IDoms.getRoot()) {
198   const Method *M = Root->getParent();
199
200   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
201
202   // Iterate over all nodes in depth first order...
203   for (df_const_iterator I = df_begin(M), E = df_end(M); I != E; ++I) {
204     const BasicBlock *BB = *I, *IDom = IDoms[*I];
205
206     if (IDom != 0) {   // Ignore the root node and other nasty nodes
207       // We know that the immediate dominator should already have a node, 
208       // because we are traversing the CFG in depth first order!
209       //
210       assert(Nodes[IDom] && "No node for IDOM?");
211       Node *IDomNode = Nodes[IDom];
212
213       // Add a new tree node for this BasicBlock, and link it as a child of
214       // IDomNode
215       Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
216     }
217   }
218 }
219
220 void cfg::DominatorTree::calculate(const DominatorSet &DS) {
221   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
222
223   if (!isPostDominator()) {
224     // Iterate over all nodes in depth first order...
225     for (df_const_iterator I = df_begin(Root), E = df_end(Root); I != E; ++I) {
226       const BasicBlock *BB = *I;
227       const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
228       unsigned DomSetSize = Dominators.size();
229       if (DomSetSize == 1) continue;  // Root node... IDom = null
230       
231       // Loop over all dominators of this node.  This corresponds to looping over
232       // nodes in the dominator chain, looking for a node whose dominator set is
233       // equal to the current nodes, except that the current node does not exist
234       // in it.  This means that it is one level higher in the dom chain than the
235       // current node, and it is our idom!  We know that we have already added
236       // a DominatorTree node for our idom, because the idom must be a
237       // predecessor in the depth first order that we are iterating through the
238       // method.
239       //
240       DominatorSet::DomSetType::const_iterator I = Dominators.begin();
241       DominatorSet::DomSetType::const_iterator End = Dominators.end();
242       for (; I != End; ++I) {   // Iterate over dominators...
243         // All of our dominators should form a chain, where the number of elements
244         // in the dominator set indicates what level the node is at in the chain.
245         // We want the node immediately above us, so it will have an identical 
246         // dominator set, except that BB will not dominate it... therefore it's
247         // dominator set size will be one less than BB's...
248         //
249         if (DS.getDominators(*I).size() == DomSetSize - 1) {
250           // We know that the immediate dominator should already have a node, 
251           // because we are traversing the CFG in depth first order!
252           //
253           Node *IDomNode = Nodes[*I];
254           assert(IDomNode && "No node for IDOM?");
255           
256           // Add a new tree node for this BasicBlock, and link it as a child of
257           // IDomNode
258           Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
259           break;
260         }
261       }
262     }
263   } else if (Root) {
264     // Iterate over all nodes in depth first order...
265     for (idf_const_iterator I = idf_begin(Root), E = idf_end(Root); I != E; ++I) {
266       const BasicBlock *BB = *I;
267       const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
268       unsigned DomSetSize = Dominators.size();
269       if (DomSetSize == 1) continue;  // Root node... IDom = null
270       
271       // Loop over all dominators of this node.  This corresponds to looping over
272       // nodes in the dominator chain, looking for a node whose dominator set is
273       // equal to the current nodes, except that the current node does not exist
274       // in it.  This means that it is one level higher in the dom chain than the
275       // current node, and it is our idom!  We know that we have already added
276       // a DominatorTree node for our idom, because the idom must be a
277       // predecessor in the depth first order that we are iterating through the
278       // method.
279       //
280       DominatorSet::DomSetType::const_iterator I = Dominators.begin();
281       DominatorSet::DomSetType::const_iterator End = Dominators.end();
282       for (; I != End; ++I) {   // Iterate over dominators...
283         // All of our dominators should form a chain, where the number of elements
284         // in the dominator set indicates what level the node is at in the chain.
285         // We want the node immediately above us, so it will have an identical 
286         // dominator set, except that BB will not dominate it... therefore it's
287         // dominator set size will be one less than BB's...
288         //
289         if (DS.getDominators(*I).size() == DomSetSize - 1) {
290           // We know that the immediate dominator should already have a node, 
291           // because we are traversing the CFG in depth first order!
292           //
293           Node *IDomNode = Nodes[*I];
294           assert(IDomNode && "No node for IDOM?");
295           
296           // Add a new tree node for this BasicBlock, and link it as a child of
297           // IDomNode
298           Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
299           break;
300         }
301       }
302     }
303   }
304 }
305
306
307
308 //===----------------------------------------------------------------------===//
309 //  DominanceFrontier Implementation
310 //===----------------------------------------------------------------------===//
311
312 const cfg::DominanceFrontier::DomSetType &
313 cfg::DominanceFrontier::calcDomFrontier(const DominatorTree &DT, 
314                                         const DominatorTree::Node *Node) {
315   // Loop over CFG successors to calculate DFlocal[Node]
316   const BasicBlock *BB = Node->getNode();
317   DomSetType &S = Frontiers[BB];       // The new set to fill in...
318
319   for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB); 
320        SI != SE; ++SI) {
321     // Does Node immediately dominate this successor?
322     if (DT[*SI]->getIDom() != Node)
323       S.insert(*SI);
324   }
325
326   // At this point, S is DFlocal.  Now we union in DFup's of our children...
327   // Loop through and visit the nodes that Node immediately dominates (Node's
328   // children in the IDomTree)
329   //
330   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
331        NI != NE; ++NI) {
332     DominatorTree::Node *IDominee = *NI;
333     const DomSetType &ChildDF = calcDomFrontier(DT, IDominee);
334
335     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
336     for (; CDFI != CDFE; ++CDFI) {
337       if (!Node->dominates(DT[*CDFI]))
338         S.insert(*CDFI);
339     }
340   }
341
342   return S;
343 }
344
345 const cfg::DominanceFrontier::DomSetType &
346 cfg::DominanceFrontier::calcPostDomFrontier(const DominatorTree &DT, 
347                                             const DominatorTree::Node *Node) {
348   // Loop over CFG successors to calculate DFlocal[Node]
349   const BasicBlock *BB = Node->getNode();
350   DomSetType &S = Frontiers[BB];       // The new set to fill in...
351   if (!Root) return S;
352
353   for (pred_const_iterator SI = pred_begin(BB), SE = pred_end(BB); 
354        SI != SE; ++SI) {
355     // Does Node immediately dominate this predeccessor?
356     if (DT[*SI]->getIDom() != Node)
357       S.insert(*SI);
358   }
359
360   // At this point, S is DFlocal.  Now we union in DFup's of our children...
361   // Loop through and visit the nodes that Node immediately dominates (Node's
362   // children in the IDomTree)
363   //
364   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
365        NI != NE; ++NI) {
366     DominatorTree::Node *IDominee = *NI;
367     const DomSetType &ChildDF = calcPostDomFrontier(DT, IDominee);
368
369     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
370     for (; CDFI != CDFE; ++CDFI) {
371       if (!Node->dominates(DT[*CDFI]))
372         S.insert(*CDFI);
373     }
374   }
375
376   return S;
377 }