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