Finegrainify namespacification
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - 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 simple dominator construction algorithms for finding
11 // forward dominators.  Postdominators are available in libanalysis, but are not
12 // included in libvmcore, because it's not needed.  Forward dominators are
13 // needed to support the Verifier pass.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "Support/DepthFirstIterator.h"
21 #include "Support/SetOperations.h"
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //  DominatorSet Implementation
26 //===----------------------------------------------------------------------===//
27
28 static RegisterAnalysis<DominatorSet>
29 A("domset", "Dominator Set Construction", true);
30
31 // dominates - Return true if A dominates B.  This performs the special checks
32 // necessary if A and B are in the same basic block.
33 //
34 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
35   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
36   if (BBA != BBB) return dominates(BBA, BBB);
37   
38   // Loop through the basic block until we find A or B.
39   BasicBlock::iterator I = BBA->begin();
40   for (; &*I != A && &*I != B; ++I) /*empty*/;
41   
42   // A dominates B if it is found first in the basic block...
43   return &*I == A;
44 }
45
46
47 void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
48   bool Changed;
49   Doms[RootBB].insert(RootBB);  // Root always dominates itself...
50   do {
51     Changed = false;
52
53     DomSetType WorkingSet;
54     df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
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 its 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         // except when there are unreachable blocks.
63         //
64         while (PI != PEnd && Doms[*PI].empty()) ++PI;
65         if (PI != PEnd) {     // Not unreachable code case?
66           WorkingSet = Doms[*PI];
67
68           // Intersect all of the predecessor sets
69           for (++PI; PI != PEnd; ++PI) {
70             DomSetType &PredSet = Doms[*PI];
71             if (PredSet.size())
72               set_intersect(WorkingSet, PredSet);
73           }
74         }
75       } else {
76         assert(Roots.size() == 1 && BB == Roots[0] &&
77                "We got into unreachable code somehow!");
78       }
79         
80       WorkingSet.insert(BB);           // A block always dominates itself
81       DomSetType &BBSet = Doms[BB];
82       if (BBSet != WorkingSet) {
83         //assert(WorkingSet.size() > BBSet.size() && "Must only grow sets!");
84         BBSet.swap(WorkingSet);        // Constant time operation!
85         Changed = true;                // The sets changed.
86       }
87       WorkingSet.clear();              // Clear out the set for next iteration
88     }
89   } while (Changed);
90 }
91
92
93
94 // runOnFunction - This method calculates the forward dominator sets for the
95 // specified function.
96 //
97 bool DominatorSet::runOnFunction(Function &F) {
98   BasicBlock *Root = &F.getEntryBlock();
99   Roots.clear();
100   Roots.push_back(Root);
101   assert(pred_begin(Root) == pred_end(Root) &&
102          "Root node has predecessors in function!");
103   recalculate();
104   return false;
105 }
106
107 void DominatorSet::recalculate() {
108   assert(Roots.size() == 1 && "DominatorSet should have single root block!");
109   Doms.clear();   // Reset from the last time we were run...
110
111   // Calculate dominator sets for the reachable basic blocks...
112   calculateDominatorsFromBlock(Roots[0]);
113
114
115   // Loop through the function, ensuring that every basic block has at least an
116   // empty set of nodes.  This is important for the case when there is
117   // unreachable blocks.
118   Function *F = Roots[0]->getParent();
119   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) Doms[I];
120 }
121
122 namespace llvm {
123 static std::ostream &operator<<(std::ostream &o,
124                                 const std::set<BasicBlock*> &BBs) {
125   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
126        I != E; ++I)
127     if (*I)
128       WriteAsOperand(o, *I, false);
129     else
130       o << " <<exit node>>";
131   return o;
132 }
133 }
134
135 void DominatorSetBase::print(std::ostream &o) const {
136   for (const_iterator I = begin(), E = end(); I != E; ++I) {
137     o << "  DomSet For BB: ";
138     if (I->first)
139       WriteAsOperand(o, I->first, false);
140     else
141       o << " <<exit node>>";
142     o << " is:\t" << I->second << "\n";
143   }
144 }
145
146 //===----------------------------------------------------------------------===//
147 //  ImmediateDominators Implementation
148 //===----------------------------------------------------------------------===//
149
150 static RegisterAnalysis<ImmediateDominators>
151 C("idom", "Immediate Dominators Construction", true);
152
153 // calcIDoms - Calculate the immediate dominator mapping, given a set of
154 // dominators for every basic block.
155 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
156   // Loop over all of the nodes that have dominators... figuring out the IDOM
157   // for each node...
158   //
159   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end(); 
160        DI != DEnd; ++DI) {
161     BasicBlock *BB = DI->first;
162     const DominatorSet::DomSetType &Dominators = DI->second;
163     unsigned DomSetSize = Dominators.size();
164     if (DomSetSize == 1) continue;  // Root node... IDom = null
165
166     // Loop over all dominators of this node.  This corresponds to looping over
167     // nodes in the dominator chain, looking for a node whose dominator set is
168     // equal to the current nodes, except that the current node does not exist
169     // in it.  This means that it is one level higher in the dom chain than the
170     // current node, and it is our idom!
171     //
172     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
173     DominatorSet::DomSetType::const_iterator End = Dominators.end();
174     for (; I != End; ++I) {   // Iterate over dominators...
175       // All of our dominators should form a chain, where the number of elements
176       // in the dominator set indicates what level the node is at in the chain.
177       // We want the node immediately above us, so it will have an identical 
178       // dominator set, except that BB will not dominate it... therefore it's
179       // dominator set size will be one less than BB's...
180       //
181       if (DS.getDominators(*I).size() == DomSetSize - 1) {
182         IDoms[BB] = *I;
183         break;
184       }
185     }
186   }
187 }
188
189 void ImmediateDominatorsBase::print(std::ostream &o) const {
190   for (const_iterator I = begin(), E = end(); I != E; ++I) {
191     o << "  Immediate Dominator For Basic Block:";
192     if (I->first)
193       WriteAsOperand(o, I->first, false);
194     else
195       o << " <<exit node>>";
196     o << " is:";
197     if (I->second)
198       WriteAsOperand(o, I->second, false);
199     else
200       o << " <<exit node>>";
201     o << "\n";
202   }
203   o << "\n";
204 }
205
206
207 //===----------------------------------------------------------------------===//
208 //  DominatorTree Implementation
209 //===----------------------------------------------------------------------===//
210
211 static RegisterAnalysis<DominatorTree>
212 E("domtree", "Dominator Tree Construction", true);
213
214 // DominatorTreeBase::reset - Free all of the tree node memory.
215 //
216 void DominatorTreeBase::reset() { 
217   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
218     delete I->second;
219   Nodes.clear();
220   RootNode = 0;
221 }
222
223 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
224   assert(IDom && "No immediate dominator?");
225   if (IDom != NewIDom) {
226     std::vector<Node*>::iterator I =
227       std::find(IDom->Children.begin(), IDom->Children.end(), this);
228     assert(I != IDom->Children.end() &&
229            "Not in immediate dominator children set!");
230     // I am no longer your child...
231     IDom->Children.erase(I);
232
233     // Switch to new dominator
234     IDom = NewIDom;
235     IDom->Children.push_back(this);
236   }
237 }
238
239
240
241 void DominatorTree::calculate(const DominatorSet &DS) {
242   assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
243   BasicBlock *Root = Roots[0];
244   Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
245
246   // Iterate over all nodes in depth first order...
247   for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
248        I != E; ++I) {
249     BasicBlock *BB = *I;
250     const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
251     unsigned DomSetSize = Dominators.size();
252     if (DomSetSize == 1) continue;  // Root node... IDom = null
253       
254     // Loop over all dominators of this node. This corresponds to looping over
255     // nodes in the dominator chain, looking for a node whose dominator set is
256     // equal to the current nodes, except that the current node does not exist
257     // in it. This means that it is one level higher in the dom chain than the
258     // current node, and it is our idom!  We know that we have already added
259     // a DominatorTree node for our idom, because the idom must be a
260     // predecessor in the depth first order that we are iterating through the
261     // function.
262     //
263     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
264     DominatorSet::DomSetType::const_iterator End = Dominators.end();
265     for (; I != End; ++I) {   // Iterate over dominators...
266       // All of our dominators should form a chain, where the number of
267       // elements in the dominator set indicates what level the node is at in
268       // the chain.  We want the node immediately above us, so it will have
269       // an identical dominator set, except that BB will not dominate it...
270       // therefore it's dominator set size will be one less than BB's...
271       //
272       if (DS.getDominators(*I).size() == DomSetSize - 1) {
273         // We know that the immediate dominator should already have a node, 
274         // because we are traversing the CFG in depth first order!
275         //
276         Node *IDomNode = Nodes[*I];
277         assert(IDomNode && "No node for IDOM?");
278         
279         // Add a new tree node for this BasicBlock, and link it as a child of
280         // IDomNode
281         Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
282         break;
283       }
284     }
285   }
286 }
287
288
289 static std::ostream &operator<<(std::ostream &o,
290                                 const DominatorTreeBase::Node *Node) {
291   if (Node->getBlock())
292     WriteAsOperand(o, Node->getBlock(), false);
293   else
294     o << " <<exit node>>";
295   return o << "\n";
296 }
297
298 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
299                          unsigned Lev) {
300   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
301   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
302        I != E; ++I)
303     PrintDomTree(*I, o, Lev+1);
304 }
305
306 void DominatorTreeBase::print(std::ostream &o) const {
307   o << "=============================--------------------------------\n"
308     << "Inorder Dominator Tree:\n";
309   PrintDomTree(getRootNode(), o, 1);
310 }
311
312
313 //===----------------------------------------------------------------------===//
314 //  DominanceFrontier Implementation
315 //===----------------------------------------------------------------------===//
316
317 static RegisterAnalysis<DominanceFrontier>
318 G("domfrontier", "Dominance Frontier Construction", true);
319
320 const DominanceFrontier::DomSetType &
321 DominanceFrontier::calculate(const DominatorTree &DT, 
322                              const DominatorTree::Node *Node) {
323   // Loop over CFG successors to calculate DFlocal[Node]
324   BasicBlock *BB = Node->getBlock();
325   DomSetType &S = Frontiers[BB];       // The new set to fill in...
326
327   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
328        SI != SE; ++SI) {
329     // Does Node immediately dominate this successor?
330     if (DT[*SI]->getIDom() != Node)
331       S.insert(*SI);
332   }
333
334   // At this point, S is DFlocal.  Now we union in DFup's of our children...
335   // Loop through and visit the nodes that Node immediately dominates (Node's
336   // children in the IDomTree)
337   //
338   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
339        NI != NE; ++NI) {
340     DominatorTree::Node *IDominee = *NI;
341     const DomSetType &ChildDF = calculate(DT, IDominee);
342
343     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
344     for (; CDFI != CDFE; ++CDFI) {
345       if (!Node->dominates(DT[*CDFI]))
346         S.insert(*CDFI);
347     }
348   }
349
350   return S;
351 }
352
353 void DominanceFrontierBase::print(std::ostream &o) const {
354   for (const_iterator I = begin(), E = end(); I != E; ++I) {
355     o << "  DomFrontier for BB";
356     if (I->first)
357       WriteAsOperand(o, I->first, false);
358     else
359       o << " <<exit node>>";
360     o << " is:\t" << I->second << "\n";
361   }
362 }
363