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