Add missing #include
[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 #include <algorithm>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 //  ImmediateDominators Implementation
27 //===----------------------------------------------------------------------===//
28 //
29 // Immediate Dominators construction - This pass constructs immediate dominator
30 // information for a flow-graph based on the algorithm described in this
31 // document:
32 //
33 //   A Fast Algorithm for Finding Dominators in a Flowgraph
34 //   T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
35 //
36 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
37 // LINK, but it turns out that the theoretically slower O(n*log(n))
38 // implementation is actually faster than the "efficient" algorithm (even for
39 // large CFGs) because the constant overheads are substantially smaller.  The
40 // lower-complexity version can be enabled with the following #define:
41 //
42 #define BALANCE_IDOM_TREE 0
43 //
44 //===----------------------------------------------------------------------===//
45
46 static RegisterAnalysis<ImmediateDominators>
47 C("idom", "Immediate Dominators Construction", true);
48
49 unsigned ImmediateDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
50                                       unsigned N) {
51   VInfo.Semi = ++N;
52   VInfo.Label = V;
53
54   Vertex.push_back(V);        // Vertex[n] = V;
55   //Info[V].Ancestor = 0;     // Ancestor[n] = 0
56   //Child[V] = 0;             // Child[v] = 0
57   VInfo.Size = 1;             // Size[v] = 1
58
59   for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
60     InfoRec &SuccVInfo = Info[*SI];
61     if (SuccVInfo.Semi == 0) {
62       SuccVInfo.Parent = V;
63       N = DFSPass(*SI, SuccVInfo, N);
64     }
65   }
66   return N;
67 }
68
69 void ImmediateDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
70   BasicBlock *VAncestor = VInfo.Ancestor;
71   InfoRec &VAInfo = Info[VAncestor];
72   if (VAInfo.Ancestor == 0)
73     return;
74
75   Compress(VAncestor, VAInfo);
76
77   BasicBlock *VAncestorLabel = VAInfo.Label; 
78   BasicBlock *VLabel = VInfo.Label;
79   if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
80     VInfo.Label = VAncestorLabel;
81
82   VInfo.Ancestor = VAInfo.Ancestor;
83 }
84
85 BasicBlock *ImmediateDominators::Eval(BasicBlock *V) {
86   InfoRec &VInfo = Info[V];
87 #if !BALANCE_IDOM_TREE
88   // Higher-complexity but faster implementation
89   if (VInfo.Ancestor == 0)
90     return V;
91   Compress(V, VInfo);
92   return VInfo.Label;
93 #else
94   // Lower-complexity but slower implementation
95   if (VInfo.Ancestor == 0)
96     return VInfo.Label;
97   Compress(V, VInfo);
98   BasicBlock *VLabel = VInfo.Label;
99
100   BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
101   if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
102     return VLabel;
103   else
104     return VAncestorLabel;
105 #endif
106 }
107
108 void ImmediateDominators::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
109 #if !BALANCE_IDOM_TREE
110   // Higher-complexity but faster implementation
111   WInfo.Ancestor = V;
112 #else
113   // Lower-complexity but slower implementation
114   BasicBlock *WLabel = WInfo.Label;
115   unsigned WLabelSemi = Info[WLabel].Semi;
116   BasicBlock *S = W;
117   InfoRec *SInfo = &Info[S];
118   
119   BasicBlock *SChild = SInfo->Child;
120   InfoRec *SChildInfo = &Info[SChild];
121   
122   while (WLabelSemi < Info[SChildInfo->Label].Semi) {
123     BasicBlock *SChildChild = SChildInfo->Child;
124     if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
125       SChildInfo->Ancestor = S;
126       SInfo->Child = SChild = SChildChild;
127       SChildInfo = &Info[SChild];
128     } else {
129       SChildInfo->Size = SInfo->Size;
130       S = SInfo->Ancestor = SChild;
131       SInfo = SChildInfo;
132       SChild = SChildChild;
133       SChildInfo = &Info[SChild];
134     }
135   }
136   
137   InfoRec &VInfo = Info[V];
138   SInfo->Label = WLabel;
139   
140   assert(V != W && "The optimization here will not work in this case!");
141   unsigned WSize = WInfo.Size;
142   unsigned VSize = (VInfo.Size += WSize);
143   
144   if (VSize < 2*WSize)
145     std::swap(S, VInfo.Child);
146   
147   while (S) {
148     SInfo = &Info[S];
149     SInfo->Ancestor = V;
150     S = SInfo->Child;
151   }
152 #endif
153 }
154
155
156
157 bool ImmediateDominators::runOnFunction(Function &F) {
158   IDoms.clear();     // Reset from the last time we were run...
159   BasicBlock *Root = &F.getEntryBlock();
160   Roots.clear();
161   Roots.push_back(Root);
162
163   Vertex.push_back(0);
164   
165   // Step #1: Number blocks in depth-first order and initialize variables used
166   // in later stages of the algorithm.
167   unsigned N = 0;
168   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
169     N = DFSPass(Roots[i], Info[Roots[i]], 0);
170
171   for (unsigned i = N; i >= 2; --i) {
172     BasicBlock *W = Vertex[i];
173     InfoRec &WInfo = Info[W];
174
175     // Step #2: Calculate the semidominators of all vertices
176     for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
177       if (Info.count(*PI)) {  // Only if this predecessor is reachable!
178         unsigned SemiU = Info[Eval(*PI)].Semi;
179         if (SemiU < WInfo.Semi)
180           WInfo.Semi = SemiU;
181       }
182     
183     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
184
185     BasicBlock *WParent = WInfo.Parent;
186     Link(WParent, W, WInfo);
187
188     // Step #3: Implicitly define the immediate dominator of vertices
189     std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
190     while (!WParentBucket.empty()) {
191       BasicBlock *V = WParentBucket.back();
192       WParentBucket.pop_back();
193       BasicBlock *U = Eval(V);
194       IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
195     }
196   }
197
198   // Step #4: Explicitly define the immediate dominator of each vertex
199   for (unsigned i = 2; i <= N; ++i) {
200     BasicBlock *W = Vertex[i];
201     BasicBlock *&WIDom = IDoms[W];
202     if (WIDom != Vertex[Info[W].Semi])
203       WIDom = IDoms[WIDom];
204   }
205
206   // Free temporary memory used to construct idom's
207   Info.clear();
208   std::vector<BasicBlock*>().swap(Vertex);
209
210   return false;
211 }
212
213 void ImmediateDominatorsBase::print(std::ostream &o) const {
214   for (const_iterator I = begin(), E = end(); I != E; ++I) {
215     o << "  Immediate Dominator For Basic Block:";
216     if (I->first)
217       WriteAsOperand(o, I->first, false);
218     else
219       o << " <<exit node>>";
220     o << " is:";
221     if (I->second)
222       WriteAsOperand(o, I->second, false);
223     else
224       o << " <<exit node>>";
225     o << "\n";
226   }
227   o << "\n";
228 }
229
230
231
232 //===----------------------------------------------------------------------===//
233 //  DominatorSet Implementation
234 //===----------------------------------------------------------------------===//
235
236 static RegisterAnalysis<DominatorSet>
237 B("domset", "Dominator Set Construction", true);
238
239 // dominates - Return true if A dominates B.  This performs the special checks
240 // necessary if A and B are in the same basic block.
241 //
242 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
243   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
244   if (BBA != BBB) return dominates(BBA, BBB);
245   
246   // Loop through the basic block until we find A or B.
247   BasicBlock::iterator I = BBA->begin();
248   for (; &*I != A && &*I != B; ++I) /*empty*/;
249   
250   // A dominates B if it is found first in the basic block...
251   return &*I == A;
252 }
253
254
255 // runOnFunction - This method calculates the forward dominator sets for the
256 // specified function.
257 //
258 bool DominatorSet::runOnFunction(Function &F) {
259   BasicBlock *Root = &F.getEntryBlock();
260   Roots.clear();
261   Roots.push_back(Root);
262   assert(pred_begin(Root) == pred_end(Root) &&
263          "Root node has predecessors in function!");
264
265   ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
266   Doms.clear();
267   if (Roots.empty()) return false;
268
269   // Root nodes only dominate themselves.
270   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
271     Doms[Roots[i]].insert(Roots[i]);
272
273   // Loop over all of the blocks in the function, calculating dominator sets for
274   // each function.
275   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
276     if (BasicBlock *IDom = ID[I]) {   // Get idom if block is reachable
277       DomSetType &DS = Doms[I];
278       assert(DS.empty() && "Domset already filled in for this block?");
279       DS.insert(I);  // Blocks always dominate themselves
280       
281       // Insert all dominators into the set... 
282       while (IDom) {
283         // If we have already computed the dominator sets for our immediate
284         // dominator, just use it instead of walking all the way up to the root.
285         DomSetType &IDS = Doms[IDom];
286         if (!IDS.empty()) {
287           DS.insert(IDS.begin(), IDS.end());
288           break;
289         } else {
290           DS.insert(IDom);
291           IDom = ID[IDom];
292         }
293       }
294     } else {
295       // Ensure that every basic block has at least an empty set of nodes.  This
296       // is important for the case when there is unreachable blocks.
297       Doms[I];
298     }
299
300   return false;
301 }
302
303 namespace llvm {
304 static std::ostream &operator<<(std::ostream &o,
305                                 const std::set<BasicBlock*> &BBs) {
306   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
307        I != E; ++I)
308     if (*I)
309       WriteAsOperand(o, *I, false);
310     else
311       o << " <<exit node>>";
312   return o;
313 }
314 }
315
316 void DominatorSetBase::print(std::ostream &o) const {
317   for (const_iterator I = begin(), E = end(); I != E; ++I) {
318     o << "  DomSet For BB: ";
319     if (I->first)
320       WriteAsOperand(o, I->first, false);
321     else
322       o << " <<exit node>>";
323     o << " is:\t" << I->second << "\n";
324   }
325 }
326
327 //===----------------------------------------------------------------------===//
328 //  DominatorTree Implementation
329 //===----------------------------------------------------------------------===//
330
331 static RegisterAnalysis<DominatorTree>
332 E("domtree", "Dominator Tree Construction", true);
333
334 // DominatorTreeBase::reset - Free all of the tree node memory.
335 //
336 void DominatorTreeBase::reset() { 
337   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
338     delete I->second;
339   Nodes.clear();
340   RootNode = 0;
341 }
342
343 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
344   assert(IDom && "No immediate dominator?");
345   if (IDom != NewIDom) {
346     std::vector<Node*>::iterator I =
347       std::find(IDom->Children.begin(), IDom->Children.end(), this);
348     assert(I != IDom->Children.end() &&
349            "Not in immediate dominator children set!");
350     // I am no longer your child...
351     IDom->Children.erase(I);
352
353     // Switch to new dominator
354     IDom = NewIDom;
355     IDom->Children.push_back(this);
356   }
357 }
358
359 DominatorTreeBase::Node *DominatorTree::getNodeForBlock(BasicBlock *BB) {
360   Node *&BBNode = Nodes[BB];
361   if (BBNode) return BBNode;
362
363   // Haven't calculated this node yet?  Get or calculate the node for the
364   // immediate dominator.
365   BasicBlock *IDom = getAnalysis<ImmediateDominators>()[BB];
366   Node *IDomNode = getNodeForBlock(IDom);
367     
368   // Add a new tree node for this BasicBlock, and link it as a child of
369   // IDomNode
370   return BBNode = IDomNode->addChild(new Node(BB, IDomNode));
371 }
372
373 void DominatorTree::calculate(const ImmediateDominators &ID) {
374   assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
375   BasicBlock *Root = Roots[0];
376   Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
377
378   // Loop over all of the reachable blocks in the function...
379   for (ImmediateDominators::const_iterator I = ID.begin(), E = ID.end();
380        I != E; ++I) {
381     Node *&BBNode = Nodes[I->first];
382     if (!BBNode) {  // Haven't calculated this node yet?
383       // Get or calculate the node for the immediate dominator
384       Node *IDomNode = getNodeForBlock(I->second);
385
386       // Add a new tree node for this BasicBlock, and link it as a child of
387       // IDomNode
388       BBNode = IDomNode->addChild(new Node(I->first, IDomNode));
389     }
390   }
391 }
392
393 static std::ostream &operator<<(std::ostream &o,
394                                 const DominatorTreeBase::Node *Node) {
395   if (Node->getBlock())
396     WriteAsOperand(o, Node->getBlock(), false);
397   else
398     o << " <<exit node>>";
399   return o << "\n";
400 }
401
402 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
403                          unsigned Lev) {
404   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
405   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
406        I != E; ++I)
407     PrintDomTree(*I, o, Lev+1);
408 }
409
410 void DominatorTreeBase::print(std::ostream &o) const {
411   o << "=============================--------------------------------\n"
412     << "Inorder Dominator Tree:\n";
413   PrintDomTree(getRootNode(), o, 1);
414 }
415
416
417 //===----------------------------------------------------------------------===//
418 //  DominanceFrontier Implementation
419 //===----------------------------------------------------------------------===//
420
421 static RegisterAnalysis<DominanceFrontier>
422 G("domfrontier", "Dominance Frontier Construction", true);
423
424 const DominanceFrontier::DomSetType &
425 DominanceFrontier::calculate(const DominatorTree &DT, 
426                              const DominatorTree::Node *Node) {
427   // Loop over CFG successors to calculate DFlocal[Node]
428   BasicBlock *BB = Node->getBlock();
429   DomSetType &S = Frontiers[BB];       // The new set to fill in...
430
431   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
432        SI != SE; ++SI) {
433     // Does Node immediately dominate this successor?
434     if (DT[*SI]->getIDom() != Node)
435       S.insert(*SI);
436   }
437
438   // At this point, S is DFlocal.  Now we union in DFup's of our children...
439   // Loop through and visit the nodes that Node immediately dominates (Node's
440   // children in the IDomTree)
441   //
442   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
443        NI != NE; ++NI) {
444     DominatorTree::Node *IDominee = *NI;
445     const DomSetType &ChildDF = calculate(DT, IDominee);
446
447     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
448     for (; CDFI != CDFE; ++CDFI) {
449       if (!Node->dominates(DT[*CDFI]))
450         S.insert(*CDFI);
451     }
452   }
453
454   return S;
455 }
456
457 void DominanceFrontierBase::print(std::ostream &o) const {
458   for (const_iterator I = begin(), E = end(); I != E; ++I) {
459     o << "  DomFrontier for BB";
460     if (I->first)
461       WriteAsOperand(o, I->first, false);
462     else
463       o << " <<exit node>>";
464     o << " is:\t" << I->second << "\n";
465   }
466 }
467