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