Implement == and != correctly. Before they would incorrectly return !=
[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 namespace llvm {
24
25 //===----------------------------------------------------------------------===//
26 //  DominatorSet Implementation
27 //===----------------------------------------------------------------------===//
28
29 static RegisterAnalysis<DominatorSet>
30 A("domset", "Dominator Set Construction", true);
31
32 // dominates - Return true if A dominates B.  This performs the special checks
33 // necessary if A and B are in the same basic block.
34 //
35 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
36   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
37   if (BBA != BBB) return dominates(BBA, BBB);
38   
39   // Loop through the basic block until we find A or B.
40   BasicBlock::iterator I = BBA->begin();
41   for (; &*I != A && &*I != B; ++I) /*empty*/;
42   
43   // A dominates B if it is found first in the basic block...
44   return &*I == A;
45 }
46
47
48 void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
49   bool Changed;
50   Doms[RootBB].insert(RootBB);  // Root always dominates itself...
51   do {
52     Changed = false;
53
54     DomSetType WorkingSet;
55     df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
56     for ( ; It != End; ++It) {
57       BasicBlock *BB = *It;
58       pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
59       if (PI != PEnd) {                // Is there SOME predecessor?
60         // Loop until we get to a predecessor that has had its dom set filled
61         // in at least once.  We are guaranteed to have this because we are
62         // traversing the graph in DFO and have handled start nodes specially,
63         // except when there are unreachable blocks.
64         //
65         while (PI != PEnd && Doms[*PI].empty()) ++PI;
66         if (PI != PEnd) {     // Not unreachable code case?
67           WorkingSet = Doms[*PI];
68
69           // Intersect all of the predecessor sets
70           for (++PI; PI != PEnd; ++PI) {
71             DomSetType &PredSet = Doms[*PI];
72             if (PredSet.size())
73               set_intersect(WorkingSet, PredSet);
74           }
75         }
76       } else {
77         assert(Roots.size() == 1 && BB == Roots[0] &&
78                "We got into unreachable code somehow!");
79       }
80         
81       WorkingSet.insert(BB);           // A block always dominates itself
82       DomSetType &BBSet = Doms[BB];
83       if (BBSet != WorkingSet) {
84         //assert(WorkingSet.size() > BBSet.size() && "Must only grow sets!");
85         BBSet.swap(WorkingSet);        // Constant time operation!
86         Changed = true;                // The sets changed.
87       }
88       WorkingSet.clear();              // Clear out the set for next iteration
89     }
90   } while (Changed);
91 }
92
93
94
95 // runOnFunction - This method calculates the forward dominator sets for the
96 // specified function.
97 //
98 bool DominatorSet::runOnFunction(Function &F) {
99   BasicBlock *Root = &F.getEntryBlock();
100   Roots.clear();
101   Roots.push_back(Root);
102   assert(pred_begin(Root) == pred_end(Root) &&
103          "Root node has predecessors in function!");
104   recalculate();
105   return false;
106 }
107
108 void DominatorSet::recalculate() {
109   assert(Roots.size() == 1 && "DominatorSet should have single root block!");
110   Doms.clear();   // Reset from the last time we were run...
111
112   // Calculate dominator sets for the reachable basic blocks...
113   calculateDominatorsFromBlock(Roots[0]);
114
115
116   // Loop through the function, ensuring that every basic block has at least an
117   // empty set of nodes.  This is important for the case when there is
118   // unreachable blocks.
119   Function *F = Roots[0]->getParent();
120   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) Doms[I];
121 }
122
123
124 static std::ostream &operator<<(std::ostream &o,
125                                 const std::set<BasicBlock*> &BBs) {
126   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
127        I != E; ++I)
128     if (*I)
129       WriteAsOperand(o, *I, false);
130     else
131       o << " <<exit node>>";
132   return o;
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
364 } // End llvm namespace