1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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"
25 //===----------------------------------------------------------------------===//
26 // ImmediateDominators Implementation
27 //===----------------------------------------------------------------------===//
29 // Immediate Dominators construction - This pass constructs immediate dominator
30 // information for a flow-graph based on the algorithm described in this
33 // A Fast Algorithm for Finding Dominators in a Flowgraph
34 // T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
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:
42 #define BALANCE_IDOM_TREE 0
44 //===----------------------------------------------------------------------===//
46 static RegisterAnalysis<ImmediateDominators>
47 C("idom", "Immediate Dominators Construction", true);
49 unsigned ImmediateDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
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
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) {
63 N = DFSPass(*SI, SuccVInfo, N);
69 void ImmediateDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
70 BasicBlock *VAncestor = VInfo.Ancestor;
71 InfoRec &VAInfo = Info[VAncestor];
72 if (VAInfo.Ancestor == 0)
75 Compress(VAncestor, VAInfo);
77 BasicBlock *VAncestorLabel = VAInfo.Label;
78 BasicBlock *VLabel = VInfo.Label;
79 if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
80 VInfo.Label = VAncestorLabel;
82 VInfo.Ancestor = VAInfo.Ancestor;
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)
94 // Lower-complexity but slower implementation
95 if (VInfo.Ancestor == 0)
98 BasicBlock *VLabel = VInfo.Label;
100 BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
101 if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
104 return VAncestorLabel;
108 void ImmediateDominators::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
109 #if !BALANCE_IDOM_TREE
110 // Higher-complexity but faster implementation
113 // Lower-complexity but slower implementation
114 BasicBlock *WLabel = WInfo.Label;
115 unsigned WLabelSemi = Info[WLabel].Semi;
117 InfoRec *SInfo = &Info[S];
119 BasicBlock *SChild = SInfo->Child;
120 InfoRec *SChildInfo = &Info[SChild];
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];
129 SChildInfo->Size = SInfo->Size;
130 S = SInfo->Ancestor = SChild;
132 SChild = SChildChild;
133 SChildInfo = &Info[SChild];
137 InfoRec &VInfo = Info[V];
138 SInfo->Label = WLabel;
140 assert(V != W && "The optimization here will not work in this case!");
141 unsigned WSize = WInfo.Size;
142 unsigned VSize = (VInfo.Size += WSize);
145 std::swap(S, VInfo.Child);
157 bool ImmediateDominators::runOnFunction(Function &F) {
158 IDoms.clear(); // Reset from the last time we were run...
159 BasicBlock *Root = &F.getEntryBlock();
161 Roots.push_back(Root);
165 // Step #1: Number blocks in depth-first order and initialize variables used
166 // in later stages of the algorithm.
168 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
169 N = DFSPass(Roots[i], Info[Roots[i]], 0);
171 for (unsigned i = N; i >= 2; --i) {
172 BasicBlock *W = Vertex[i];
173 InfoRec &WInfo = Info[W];
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)
183 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
185 BasicBlock *WParent = WInfo.Parent;
186 Link(WParent, W, WInfo);
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;
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];
206 // Free temporary memory used to construct idom's
208 std::vector<BasicBlock*>().swap(Vertex);
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);
219 if (BasicBlock *ID = get(I))
220 WriteAsOperand(o, ID, false);
222 o << " <<exit node>>";
230 //===----------------------------------------------------------------------===//
231 // DominatorSet Implementation
232 //===----------------------------------------------------------------------===//
234 static RegisterAnalysis<DominatorSet>
235 B("domset", "Dominator Set Construction", true);
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.
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);
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*/;
248 if(!IsPostDominators) {
249 // A dominates B if it is found first in the basic block.
252 // A post-dominates B if B is found first in the basic block.
258 // runOnFunction - This method calculates the forward dominator sets for the
259 // specified function.
261 bool DominatorSet::runOnFunction(Function &F) {
262 BasicBlock *Root = &F.getEntryBlock();
264 Roots.push_back(Root);
265 assert(pred_begin(Root) == pred_end(Root) &&
266 "Root node has predecessors in function!");
268 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
270 if (Roots.empty()) return false;
272 // Root nodes only dominate themselves.
273 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
274 Doms[Roots[i]].insert(Roots[i]);
276 // Loop over all of the blocks in the function, calculating dominator sets for
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
284 // Insert all dominators into the set...
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];
290 DS.insert(IDS.begin(), IDS.end());
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.
306 void DominatorSet::stub() {}
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();
314 WriteAsOperand(o, *I, false);
316 o << " <<exit node>>";
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: ";
325 WriteAsOperand(o, I->first, false);
327 o << " <<exit node>>";
328 o << " is:\t" << I->second << "\n";
332 //===----------------------------------------------------------------------===//
333 // DominatorTree Implementation
334 //===----------------------------------------------------------------------===//
336 static RegisterAnalysis<DominatorTree>
337 E("domtree", "Dominator Tree Construction", true);
339 // DominatorTreeBase::reset - Free all of the tree node memory.
341 void DominatorTreeBase::reset() {
342 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
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);
358 // Switch to new dominator
360 IDom->Children.push_back(this);
364 DominatorTreeBase::Node *DominatorTree::getNodeForBlock(BasicBlock *BB) {
365 Node *&BBNode = Nodes[BB];
366 if (BBNode) return BBNode;
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);
373 // Add a new tree node for this BasicBlock, and link it as a child of
375 return BBNode = IDomNode->addChild(new Node(BB, IDomNode));
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...
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);
392 // Add a new tree node for this BasicBlock, and link it as a child of
394 BBNode = IDomNode->addChild(new Node(I, IDomNode));
399 static std::ostream &operator<<(std::ostream &o,
400 const DominatorTreeBase::Node *Node) {
401 if (Node->getBlock())
402 WriteAsOperand(o, Node->getBlock(), false);
404 o << " <<exit node>>";
408 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
410 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
411 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
413 PrintDomTree(*I, o, Lev+1);
416 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
417 o << "=============================--------------------------------\n"
418 << "Inorder Dominator Tree:\n";
419 PrintDomTree(getRootNode(), o, 1);
423 //===----------------------------------------------------------------------===//
424 // DominanceFrontier Implementation
425 //===----------------------------------------------------------------------===//
427 static RegisterAnalysis<DominanceFrontier>
428 G("domfrontier", "Dominance Frontier Construction", true);
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...
437 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
439 // Does Node immediately dominate this successor?
440 if (DT[*SI]->getIDom() != Node)
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)
448 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
450 DominatorTree::Node *IDominee = *NI;
451 const DomSetType &ChildDF = calculate(DT, IDominee);
453 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
454 for (; CDFI != CDFE; ++CDFI) {
455 if (!Node->dominates(DT[*CDFI]))
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";
467 WriteAsOperand(o, I->first, false);
469 o << " <<exit node>>";
470 o << " is:\t" << I->second << "\n";