Split dominance calculation and post dominance calculation stuff
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2 //
3 // This file implements simple dominator construction algorithms for finding
4 // forward dominators.  Postdominators are available in libanalysis, but are not
5 // included in libvmcore, because it's not needed.  Forward dominators are
6 // needed to support the Verifier pass.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Analysis/Dominators.h"
11 #include "llvm/Support/CFG.h"
12 #include "llvm/Assembly/Writer.h"
13 #include "Support/DepthFirstIterator.h"
14 #include "Support/SetOperations.h"
15 using std::set;
16
17 //===----------------------------------------------------------------------===//
18 //  DominatorSet Implementation
19 //===----------------------------------------------------------------------===//
20
21 static RegisterAnalysis<DominatorSet>
22 A("domset", "Dominator Set Construction", true);
23 AnalysisID DominatorSet::ID = A;
24
25 // dominates - Return true if A dominates B.  This performs the special checks
26 // neccesary if A and B are in the same basic block.
27 //
28 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
29   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
30   if (BBA != BBB) return dominates(BBA, BBB);
31   
32   // Loop through the basic block until we find A or B.
33   BasicBlock::iterator I = BBA->begin();
34   for (; &*I != A && &*I != B; ++I) /*empty*/;
35   
36   // A dominates B if it is found first in the basic block...
37   return &*I == A;
38 }
39
40 // runOnFunction - This method calculates the forward dominator sets for the
41 // specified function.
42 //
43 bool DominatorSet::runOnFunction(Function &F) {
44   Doms.clear();   // Reset from the last time we were run...
45   Root = &F.getEntryNode();
46   assert(pred_begin(Root) == pred_end(Root) &&
47          "Root node has predecessors in function!");
48
49   bool Changed;
50   do {
51     Changed = false;
52
53     DomSetType WorkingSet;
54     df_iterator<Function*> It = df_begin(&F), End = df_end(&F);
55     for ( ; It != End; ++It) {
56       BasicBlock *BB = *It;
57       pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
58       if (PI != PEnd) {                // Is there SOME predecessor?
59         // Loop until we get to a predecessor that has had it's dom set filled
60         // in at least once.  We are guaranteed to have this because we are
61         // traversing the graph in DFO and have handled start nodes specially.
62         //
63         while (Doms[*PI].size() == 0) ++PI;
64         WorkingSet = Doms[*PI];
65
66         for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
67           DomSetType &PredSet = Doms[*PI];
68           if (PredSet.size())
69             set_intersect(WorkingSet, PredSet);
70         }
71       }
72         
73       WorkingSet.insert(BB);           // A block always dominates itself
74       DomSetType &BBSet = Doms[BB];
75       if (BBSet != WorkingSet) {
76         BBSet.swap(WorkingSet);        // Constant time operation!
77         Changed = true;                // The sets changed.
78       }
79       WorkingSet.clear();              // Clear out the set for next iteration
80     }
81   } while (Changed);
82   return false;
83 }
84
85
86 static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
87   for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
88        I != E; ++I) {
89     o << "  ";
90     WriteAsOperand(o, *I, false);
91     o << "\n";
92    }
93   return o;
94 }
95
96 void DominatorSetBase::print(std::ostream &o) const {
97   for (const_iterator I = begin(), E = end(); I != E; ++I)
98     o << "=============================--------------------------------\n"
99       << "\nDominator Set For Basic Block\n" << I->first
100       << "-------------------------------\n" << I->second << "\n";
101 }
102
103 //===----------------------------------------------------------------------===//
104 //  ImmediateDominators Implementation
105 //===----------------------------------------------------------------------===//
106
107 static RegisterAnalysis<ImmediateDominators>
108 C("idom", "Immediate Dominators Construction", true);
109 AnalysisID ImmediateDominators::ID = C;
110
111 // calcIDoms - Calculate the immediate dominator mapping, given a set of
112 // dominators for every basic block.
113 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
114   // Loop over all of the nodes that have dominators... figuring out the IDOM
115   // for each node...
116   //
117   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end(); 
118        DI != DEnd; ++DI) {
119     BasicBlock *BB = DI->first;
120     const DominatorSet::DomSetType &Dominators = DI->second;
121     unsigned DomSetSize = Dominators.size();
122     if (DomSetSize == 1) continue;  // Root node... IDom = null
123
124     // Loop over all dominators of this node.  This corresponds to looping over
125     // nodes in the dominator chain, looking for a node whose dominator set is
126     // equal to the current nodes, except that the current node does not exist
127     // in it.  This means that it is one level higher in the dom chain than the
128     // current node, and it is our idom!
129     //
130     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
131     DominatorSet::DomSetType::const_iterator End = Dominators.end();
132     for (; I != End; ++I) {   // Iterate over dominators...
133       // All of our dominators should form a chain, where the number of elements
134       // in the dominator set indicates what level the node is at in the chain.
135       // We want the node immediately above us, so it will have an identical 
136       // dominator set, except that BB will not dominate it... therefore it's
137       // dominator set size will be one less than BB's...
138       //
139       if (DS.getDominators(*I).size() == DomSetSize - 1) {
140         IDoms[BB] = *I;
141         break;
142       }
143     }
144   }
145 }
146
147 void ImmediateDominatorsBase::print(std::ostream &o) const {
148   for (const_iterator I = begin(), E = end(); I != E; ++I)
149     o << "=============================--------------------------------\n"
150       << "\nImmediate Dominator For Basic Block\n" << *I->first
151       << "is: \n" << *I->second << "\n";
152 }
153
154
155 //===----------------------------------------------------------------------===//
156 //  DominatorTree Implementation
157 //===----------------------------------------------------------------------===//
158
159 static RegisterAnalysis<DominatorTree>
160 E("domtree", "Dominator Tree Construction", true);
161 AnalysisID DominatorTree::ID = E;
162
163 // DominatorTreeBase::reset - Free all of the tree node memory.
164 //
165 void DominatorTreeBase::reset() { 
166   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
167     delete I->second;
168   Nodes.clear();
169 }
170
171
172 void DominatorTree::calculate(const DominatorSet &DS) {
173   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
174
175   // Iterate over all nodes in depth first order...
176   for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
177        I != E; ++I) {
178     BasicBlock *BB = *I;
179     const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
180     unsigned DomSetSize = Dominators.size();
181     if (DomSetSize == 1) continue;  // Root node... IDom = null
182       
183     // Loop over all dominators of this node. This corresponds to looping over
184     // nodes in the dominator chain, looking for a node whose dominator set is
185     // equal to the current nodes, except that the current node does not exist
186     // in it. This means that it is one level higher in the dom chain than the
187     // current node, and it is our idom!  We know that we have already added
188     // a DominatorTree node for our idom, because the idom must be a
189     // predecessor in the depth first order that we are iterating through the
190     // function.
191     //
192     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
193     DominatorSet::DomSetType::const_iterator End = Dominators.end();
194     for (; I != End; ++I) {   // Iterate over dominators...
195       // All of our dominators should form a chain, where the number of
196       // elements in the dominator set indicates what level the node is at in
197       // the chain.  We want the node immediately above us, so it will have
198       // an identical dominator set, except that BB will not dominate it...
199       // therefore it's dominator set size will be one less than BB's...
200       //
201       if (DS.getDominators(*I).size() == DomSetSize - 1) {
202         // We know that the immediate dominator should already have a node, 
203         // because we are traversing the CFG in depth first order!
204         //
205         Node *IDomNode = Nodes[*I];
206         assert(IDomNode && "No node for IDOM?");
207         
208         // Add a new tree node for this BasicBlock, and link it as a child of
209         // IDomNode
210         Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
211         break;
212       }
213     }
214   }
215 }
216
217
218 static std::ostream &operator<<(std::ostream &o,
219                                 const DominatorTreeBase::Node *Node) {
220   return o << Node->getNode()
221            << "\n------------------------------------------\n";
222 }
223
224 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
225                          unsigned Lev) {
226   o << "Level #" << Lev << ":  " << N;
227   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
228        I != E; ++I) {
229     PrintDomTree(*I, o, Lev+1);
230   }
231 }
232
233 void DominatorTreeBase::print(std::ostream &o) const {
234   o << "=============================--------------------------------\n"
235     << "Inorder Dominator Tree:\n";
236   PrintDomTree(Nodes.find(getRoot())->second, o, 1);
237 }
238
239
240 //===----------------------------------------------------------------------===//
241 //  DominanceFrontier Implementation
242 //===----------------------------------------------------------------------===//
243
244 static RegisterAnalysis<DominanceFrontier>
245 G("domfrontier", "Dominance Frontier Construction", true);
246 AnalysisID DominanceFrontier::ID = G;
247
248 const DominanceFrontier::DomSetType &
249 DominanceFrontier::calculate(const DominatorTree &DT, 
250                              const DominatorTree::Node *Node) {
251   // Loop over CFG successors to calculate DFlocal[Node]
252   BasicBlock *BB = Node->getNode();
253   DomSetType &S = Frontiers[BB];       // The new set to fill in...
254
255   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
256        SI != SE; ++SI) {
257     // Does Node immediately dominate this successor?
258     if (DT[*SI]->getIDom() != Node)
259       S.insert(*SI);
260   }
261
262   // At this point, S is DFlocal.  Now we union in DFup's of our children...
263   // Loop through and visit the nodes that Node immediately dominates (Node's
264   // children in the IDomTree)
265   //
266   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
267        NI != NE; ++NI) {
268     DominatorTree::Node *IDominee = *NI;
269     const DomSetType &ChildDF = calculate(DT, IDominee);
270
271     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
272     for (; CDFI != CDFE; ++CDFI) {
273       if (!Node->dominates(DT[*CDFI]))
274         S.insert(*CDFI);
275     }
276   }
277
278   return S;
279 }
280
281 void DominanceFrontierBase::print(std::ostream &o) const {
282   for (const_iterator I = begin(), E = end(); I != E; ++I) {
283     o << "=============================--------------------------------\n"
284       << "\nDominance Frontier For Basic Block\n";
285     WriteAsOperand(o, I->first, false);
286     o << " is: \n" << I->second << "\n";
287   }
288 }