Restore this patch now that the latent bug has been fixed
[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 "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/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 Module* ) const {
214   Function *F = getRoots()[0]->getParent();
215   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
216     o << "  Immediate Dominator For Basic Block:";
217     WriteAsOperand(o, I, false);
218     o << " is:";
219     if (BasicBlock *ID = get(I))
220       WriteAsOperand(o, ID, false);
221     else
222       o << " <<exit node>>";
223     o << "\n";
224   }
225   o << "\n";
226 }
227
228
229
230 //===----------------------------------------------------------------------===//
231 //  DominatorSet Implementation
232 //===----------------------------------------------------------------------===//
233
234 static RegisterAnalysis<DominatorSet>
235 B("domset", "Dominator Set Construction", true);
236
237 // dominates - Return true if A dominates B.  This performs the special checks
238 // necessary if A and B are in the same basic block.
239 //
240 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
241   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
242   if (BBA != BBB) return dominates(BBA, BBB);
243
244   // Loop through the basic block until we find A or B.
245   BasicBlock::iterator I = BBA->begin();
246   for (; &*I != A && &*I != B; ++I) /*empty*/;
247
248   if(!IsPostDominators) {
249     // A dominates B if it is found first in the basic block.
250     return &*I == A;
251   } else {
252     // A post-dominates B if B is found first in the basic block.
253     return &*I == B;
254   }
255 }
256
257
258 // runOnFunction - This method calculates the forward dominator sets for the
259 // specified function.
260 //
261 bool DominatorSet::runOnFunction(Function &F) {
262   BasicBlock *Root = &F.getEntryBlock();
263   Roots.clear();
264   Roots.push_back(Root);
265   assert(pred_begin(Root) == pred_end(Root) &&
266          "Root node has predecessors in function!");
267
268   ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
269   Doms.clear();
270   if (Roots.empty()) return false;
271
272   // Root nodes only dominate themselves.
273   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
274     Doms[Roots[i]].insert(Roots[i]);
275
276   // Loop over all of the blocks in the function, calculating dominator sets for
277   // each function.
278   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
279     if (BasicBlock *IDom = ID[I]) {   // Get idom if block is reachable
280       DomSetType &DS = Doms[I];
281       assert(DS.empty() && "Domset already filled in for this block?");
282       DS.insert(I);  // Blocks always dominate themselves
283
284       // Insert all dominators into the set...
285       while (IDom) {
286         // If we have already computed the dominator sets for our immediate
287         // dominator, just use it instead of walking all the way up to the root.
288         DomSetType &IDS = Doms[IDom];
289         if (!IDS.empty()) {
290           DS.insert(IDS.begin(), IDS.end());
291           break;
292         } else {
293           DS.insert(IDom);
294           IDom = ID[IDom];
295         }
296       }
297     } else {
298       // Ensure that every basic block has at least an empty set of nodes.  This
299       // is important for the case when there is unreachable blocks.
300       Doms[I];
301     }
302
303   return false;
304 }
305
306 void DominatorSet::stub() {}
307
308 namespace llvm {
309 static std::ostream &operator<<(std::ostream &o,
310                                 const std::set<BasicBlock*> &BBs) {
311   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
312        I != E; ++I)
313     if (*I)
314       WriteAsOperand(o, *I, false);
315     else
316       o << " <<exit node>>";
317   return o;
318 }
319 }
320
321 void DominatorSetBase::print(std::ostream &o, const Module* ) const {
322   for (const_iterator I = begin(), E = end(); I != E; ++I) {
323     o << "  DomSet For BB: ";
324     if (I->first)
325       WriteAsOperand(o, I->first, false);
326     else
327       o << " <<exit node>>";
328     o << " is:\t" << I->second << "\n";
329   }
330 }
331
332 //===----------------------------------------------------------------------===//
333 //  DominatorTree Implementation
334 //===----------------------------------------------------------------------===//
335
336 static RegisterAnalysis<DominatorTree>
337 E("domtree", "Dominator Tree Construction", true);
338
339 // DominatorTreeBase::reset - Free all of the tree node memory.
340 //
341 void DominatorTreeBase::reset() {
342   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
343     delete I->second;
344   Nodes.clear();
345   RootNode = 0;
346 }
347
348 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
349   assert(IDom && "No immediate dominator?");
350   if (IDom != NewIDom) {
351     std::vector<Node*>::iterator I =
352       std::find(IDom->Children.begin(), IDom->Children.end(), this);
353     assert(I != IDom->Children.end() &&
354            "Not in immediate dominator children set!");
355     // I am no longer your child...
356     IDom->Children.erase(I);
357
358     // Switch to new dominator
359     IDom = NewIDom;
360     IDom->Children.push_back(this);
361   }
362 }
363
364 DominatorTreeBase::Node *DominatorTree::getNodeForBlock(BasicBlock *BB) {
365   Node *&BBNode = Nodes[BB];
366   if (BBNode) return BBNode;
367
368   // Haven't calculated this node yet?  Get or calculate the node for the
369   // immediate dominator.
370   BasicBlock *IDom = getAnalysis<ImmediateDominators>()[BB];
371   Node *IDomNode = getNodeForBlock(IDom);
372
373   // Add a new tree node for this BasicBlock, and link it as a child of
374   // IDomNode
375   return BBNode = IDomNode->addChild(new Node(BB, IDomNode));
376 }
377
378 void DominatorTree::calculate(const ImmediateDominators &ID) {
379   assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
380   BasicBlock *Root = Roots[0];
381   Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
382
383   Function *F = Root->getParent();
384   // Loop over all of the reachable blocks in the function...
385   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
386     if (BasicBlock *ImmDom = ID.get(I)) {  // Reachable block.
387       Node *&BBNode = Nodes[I];
388       if (!BBNode) {  // Haven't calculated this node yet?
389         // Get or calculate the node for the immediate dominator
390         Node *IDomNode = getNodeForBlock(ImmDom);
391
392         // Add a new tree node for this BasicBlock, and link it as a child of
393         // IDomNode
394         BBNode = IDomNode->addChild(new Node(I, IDomNode));
395       }
396     }
397 }
398
399 static std::ostream &operator<<(std::ostream &o,
400                                 const DominatorTreeBase::Node *Node) {
401   if (Node->getBlock())
402     WriteAsOperand(o, Node->getBlock(), false);
403   else
404     o << " <<exit node>>";
405   return o << "\n";
406 }
407
408 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
409                          unsigned Lev) {
410   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
411   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
412        I != E; ++I)
413     PrintDomTree(*I, o, Lev+1);
414 }
415
416 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
417   o << "=============================--------------------------------\n"
418     << "Inorder Dominator Tree:\n";
419   PrintDomTree(getRootNode(), o, 1);
420 }
421
422
423 //===----------------------------------------------------------------------===//
424 //  DominanceFrontier Implementation
425 //===----------------------------------------------------------------------===//
426
427 static RegisterAnalysis<DominanceFrontier>
428 G("domfrontier", "Dominance Frontier Construction", true);
429
430 const DominanceFrontier::DomSetType &
431 DominanceFrontier::calculate(const DominatorTree &DT,
432                              const DominatorTree::Node *Node) {
433   // Loop over CFG successors to calculate DFlocal[Node]
434   BasicBlock *BB = Node->getBlock();
435   DomSetType &S = Frontiers[BB];       // The new set to fill in...
436
437   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
438        SI != SE; ++SI) {
439     // Does Node immediately dominate this successor?
440     if (DT[*SI]->getIDom() != Node)
441       S.insert(*SI);
442   }
443
444   // At this point, S is DFlocal.  Now we union in DFup's of our children...
445   // Loop through and visit the nodes that Node immediately dominates (Node's
446   // children in the IDomTree)
447   //
448   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
449        NI != NE; ++NI) {
450     DominatorTree::Node *IDominee = *NI;
451     const DomSetType &ChildDF = calculate(DT, IDominee);
452
453     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
454     for (; CDFI != CDFE; ++CDFI) {
455       if (!Node->dominates(DT[*CDFI]))
456         S.insert(*CDFI);
457     }
458   }
459
460   return S;
461 }
462
463 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
464   for (const_iterator I = begin(), E = end(); I != E; ++I) {
465     o << "  DomFrontier for BB";
466     if (I->first)
467       WriteAsOperand(o, I->first, false);
468     else
469       o << " <<exit node>>";
470     o << " is:\t" << I->second << "\n";
471   }
472 }
473