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