Spell `necessary' correctly.
[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 it's 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         } else {
67           // Otherwise this block is unreachable.  it doesn't really matter what
68           // we use for the dominator set for the node...
69           //
70           WorkingSet = Doms[Root];
71         }
72       } else if (BB != Root) {
73         // If this isn't the root basic block and it has no predecessors, it
74         // must be an unreachable block.  Fib a bit by saying that the root node
75         // dominates this unreachable node.  This isn't exactly true, because
76         // there is no path from the entry node to this node, but it is sorta
77         // true because any paths to this node would have to go through the
78         // entry node.
79         //
80         // This allows for dominator properties to be built for unreachable code
81         // in a reasonable manner.
82         //
83         WorkingSet = Doms[Root];
84       }
85         
86       WorkingSet.insert(BB);           // A block always dominates itself
87       DomSetType &BBSet = Doms[BB];
88       if (BBSet != WorkingSet) {
89         BBSet.swap(WorkingSet);        // Constant time operation!
90         Changed = true;                // The sets changed.
91       }
92       WorkingSet.clear();              // Clear out the set for next iteration
93     }
94   } while (Changed);
95 }
96
97
98
99 // runOnFunction - This method calculates the forward dominator sets for the
100 // specified function.
101 //
102 bool DominatorSet::runOnFunction(Function &F) {
103   Root = &F.getEntryNode();
104   assert(pred_begin(Root) == pred_end(Root) &&
105          "Root node has predecessors in function!");
106   recalculate();
107   return false;
108 }
109
110 void DominatorSet::recalculate() {
111   Doms.clear();   // Reset from the last time we were run...
112
113   // Calculate dominator sets for the reachable basic blocks...
114   calculateDominatorsFromBlock(Root);
115
116   // Every basic block in the function should at least dominate themselves, and
117   // thus every basic block should have an entry in Doms.  The one case where we
118   // miss this is when a basic block is unreachable.  To get these we now do an
119   // extra pass over the function, calculating dominator information for
120   // unreachable blocks.
121   //
122   Function *F = Root->getParent();
123   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
124     if (Doms[I].count(I) == 0)
125       calculateDominatorsFromBlock(I);
126 }
127
128
129 static std::ostream &operator<<(std::ostream &o,
130                                 const std::set<BasicBlock*> &BBs) {
131   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
132        I != E; ++I) {
133     o << "  ";
134     WriteAsOperand(o, *I, false);
135     o << "\n";
136    }
137   return o;
138 }
139
140 void DominatorSetBase::print(std::ostream &o) const {
141   for (const_iterator I = begin(), E = end(); I != E; ++I) {
142     o << "=============================--------------------------------\n"
143       << "\nDominator Set For Basic Block: ";
144     WriteAsOperand(o, I->first, false);
145     o  << "\n-------------------------------\n" << I->second << "\n";
146   }
147 }
148
149 //===----------------------------------------------------------------------===//
150 //  ImmediateDominators Implementation
151 //===----------------------------------------------------------------------===//
152
153 static RegisterAnalysis<ImmediateDominators>
154 C("idom", "Immediate Dominators Construction", true);
155
156 // calcIDoms - Calculate the immediate dominator mapping, given a set of
157 // dominators for every basic block.
158 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
159   // Loop over all of the nodes that have dominators... figuring out the IDOM
160   // for each node...
161   //
162   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end(); 
163        DI != DEnd; ++DI) {
164     BasicBlock *BB = DI->first;
165     const DominatorSet::DomSetType &Dominators = DI->second;
166     unsigned DomSetSize = Dominators.size();
167     if (DomSetSize == 1) continue;  // Root node... IDom = null
168
169     // Loop over all dominators of this node.  This corresponds to looping over
170     // nodes in the dominator chain, looking for a node whose dominator set is
171     // equal to the current nodes, except that the current node does not exist
172     // in it.  This means that it is one level higher in the dom chain than the
173     // current node, and it is our idom!
174     //
175     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
176     DominatorSet::DomSetType::const_iterator End = Dominators.end();
177     for (; I != End; ++I) {   // Iterate over dominators...
178       // All of our dominators should form a chain, where the number of elements
179       // in the dominator set indicates what level the node is at in the chain.
180       // We want the node immediately above us, so it will have an identical 
181       // dominator set, except that BB will not dominate it... therefore it's
182       // dominator set size will be one less than BB's...
183       //
184       if (DS.getDominators(*I).size() == DomSetSize - 1) {
185         IDoms[BB] = *I;
186         break;
187       }
188     }
189   }
190 }
191
192 void ImmediateDominatorsBase::print(std::ostream &o) const {
193   for (const_iterator I = begin(), E = end(); I != E; ++I) {
194     o << "=============================--------------------------------\n"
195       << "\nImmediate Dominator For Basic Block:";
196     WriteAsOperand(o, I->first, false);
197     o << " is:";
198     WriteAsOperand(o, I->second, false);
199     o << "\n";
200   }
201 }
202
203
204 //===----------------------------------------------------------------------===//
205 //  DominatorTree Implementation
206 //===----------------------------------------------------------------------===//
207
208 static RegisterAnalysis<DominatorTree>
209 E("domtree", "Dominator Tree Construction", true);
210
211 // DominatorTreeBase::reset - Free all of the tree node memory.
212 //
213 void DominatorTreeBase::reset() { 
214   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
215     delete I->second;
216   Nodes.clear();
217 }
218
219 void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
220   assert(IDom && "No immediate dominator?");
221   if (IDom != NewIDom) {
222     std::vector<Node*>::iterator I =
223       std::find(IDom->Children.begin(), IDom->Children.end(), this);
224     assert(I != IDom->Children.end() &&
225            "Not in immediate dominator children set!");
226     // I am no longer your child...
227     IDom->Children.erase(I);
228
229     // Switch to new dominator
230     IDom = NewIDom;
231     IDom->Children.push_back(this);
232   }
233 }
234
235
236
237 void DominatorTree::calculate(const DominatorSet &DS) {
238   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
239
240   // Iterate over all nodes in depth first order...
241   for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
242        I != E; ++I) {
243     BasicBlock *BB = *I;
244     const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
245     unsigned DomSetSize = Dominators.size();
246     if (DomSetSize == 1) continue;  // Root node... IDom = null
247       
248     // Loop over all dominators of this node. This corresponds to looping over
249     // nodes in the dominator chain, looking for a node whose dominator set is
250     // equal to the current nodes, except that the current node does not exist
251     // in it. This means that it is one level higher in the dom chain than the
252     // current node, and it is our idom!  We know that we have already added
253     // a DominatorTree node for our idom, because the idom must be a
254     // predecessor in the depth first order that we are iterating through the
255     // function.
256     //
257     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
258     DominatorSet::DomSetType::const_iterator End = Dominators.end();
259     for (; I != End; ++I) {   // Iterate over dominators...
260       // All of our dominators should form a chain, where the number of
261       // elements in the dominator set indicates what level the node is at in
262       // the chain.  We want the node immediately above us, so it will have
263       // an identical dominator set, except that BB will not dominate it...
264       // therefore it's dominator set size will be one less than BB's...
265       //
266       if (DS.getDominators(*I).size() == DomSetSize - 1) {
267         // We know that the immediate dominator should already have a node, 
268         // because we are traversing the CFG in depth first order!
269         //
270         Node *IDomNode = Nodes[*I];
271         assert(IDomNode && "No node for IDOM?");
272         
273         // Add a new tree node for this BasicBlock, and link it as a child of
274         // IDomNode
275         Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
276         break;
277       }
278     }
279   }
280 }
281
282
283 static std::ostream &operator<<(std::ostream &o,
284                                 const DominatorTreeBase::Node *Node) {
285   return o << Node->getNode()
286            << "\n------------------------------------------\n";
287 }
288
289 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
290                          unsigned Lev) {
291   o << "Level #" << Lev << ":  " << N;
292   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
293        I != E; ++I) {
294     PrintDomTree(*I, o, Lev+1);
295   }
296 }
297
298 void DominatorTreeBase::print(std::ostream &o) const {
299   o << "=============================--------------------------------\n"
300     << "Inorder Dominator Tree:\n";
301   PrintDomTree(Nodes.find(getRoot())->second, o, 1);
302 }
303
304
305 //===----------------------------------------------------------------------===//
306 //  DominanceFrontier Implementation
307 //===----------------------------------------------------------------------===//
308
309 static RegisterAnalysis<DominanceFrontier>
310 G("domfrontier", "Dominance Frontier Construction", true);
311
312 const DominanceFrontier::DomSetType &
313 DominanceFrontier::calculate(const DominatorTree &DT, 
314                              const DominatorTree::Node *Node) {
315   // Loop over CFG successors to calculate DFlocal[Node]
316   BasicBlock *BB = Node->getNode();
317   DomSetType &S = Frontiers[BB];       // The new set to fill in...
318
319   for (succ_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 = calculate(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 void DominanceFrontierBase::print(std::ostream &o) const {
346   for (const_iterator I = begin(), E = end(); I != E; ++I) {
347     o << "=============================--------------------------------\n"
348       << "\nDominance Frontier For Basic Block\n";
349     WriteAsOperand(o, I->first, false);
350     o << " is: \n" << I->second << "\n";
351   }
352 }