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"
26 //===----------------------------------------------------------------------===//
27 // ImmediateDominators Implementation
28 //===----------------------------------------------------------------------===//
30 // Immediate Dominators construction - This pass constructs immediate dominator
31 // information for a flow-graph based on the algorithm described in this
34 // A Fast Algorithm for Finding Dominators in a Flowgraph
35 // T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
37 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
38 // LINK, but it turns out that the theoretically slower O(n*log(n))
39 // implementation is actually faster than the "efficient" algorithm (even for
40 // large CFGs) because the constant overheads are substantially smaller. The
41 // lower-complexity version can be enabled with the following #define:
43 #define BALANCE_IDOM_TREE 0
45 //===----------------------------------------------------------------------===//
47 static RegisterAnalysis<ImmediateDominators>
48 C("idom", "Immediate Dominators Construction", true);
50 unsigned ImmediateDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
55 Vertex.push_back(V); // Vertex[n] = V;
56 //Info[V].Ancestor = 0; // Ancestor[n] = 0
57 //Child[V] = 0; // Child[v] = 0
58 VInfo.Size = 1; // Size[v] = 1
60 for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
61 InfoRec &SuccVInfo = Info[*SI];
62 if (SuccVInfo.Semi == 0) {
64 N = DFSPass(*SI, SuccVInfo, N);
70 void ImmediateDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
71 BasicBlock *VAncestor = VInfo.Ancestor;
72 InfoRec &VAInfo = Info[VAncestor];
73 if (VAInfo.Ancestor == 0)
76 Compress(VAncestor, VAInfo);
78 BasicBlock *VAncestorLabel = VAInfo.Label;
79 BasicBlock *VLabel = VInfo.Label;
80 if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
81 VInfo.Label = VAncestorLabel;
83 VInfo.Ancestor = VAInfo.Ancestor;
86 BasicBlock *ImmediateDominators::Eval(BasicBlock *V) {
87 InfoRec &VInfo = Info[V];
88 #if !BALANCE_IDOM_TREE
89 // Higher-complexity but faster implementation
90 if (VInfo.Ancestor == 0)
95 // Lower-complexity but slower implementation
96 if (VInfo.Ancestor == 0)
99 BasicBlock *VLabel = VInfo.Label;
101 BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
102 if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
105 return VAncestorLabel;
109 void ImmediateDominators::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
110 #if !BALANCE_IDOM_TREE
111 // Higher-complexity but faster implementation
114 // Lower-complexity but slower implementation
115 BasicBlock *WLabel = WInfo.Label;
116 unsigned WLabelSemi = Info[WLabel].Semi;
118 InfoRec *SInfo = &Info[S];
120 BasicBlock *SChild = SInfo->Child;
121 InfoRec *SChildInfo = &Info[SChild];
123 while (WLabelSemi < Info[SChildInfo->Label].Semi) {
124 BasicBlock *SChildChild = SChildInfo->Child;
125 if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
126 SChildInfo->Ancestor = S;
127 SInfo->Child = SChild = SChildChild;
128 SChildInfo = &Info[SChild];
130 SChildInfo->Size = SInfo->Size;
131 S = SInfo->Ancestor = SChild;
133 SChild = SChildChild;
134 SChildInfo = &Info[SChild];
138 InfoRec &VInfo = Info[V];
139 SInfo->Label = WLabel;
141 assert(V != W && "The optimization here will not work in this case!");
142 unsigned WSize = WInfo.Size;
143 unsigned VSize = (VInfo.Size += WSize);
146 std::swap(S, VInfo.Child);
158 bool ImmediateDominators::runOnFunction(Function &F) {
159 IDoms.clear(); // Reset from the last time we were run...
160 BasicBlock *Root = &F.getEntryBlock();
162 Roots.push_back(Root);
166 // Step #1: Number blocks in depth-first order and initialize variables used
167 // in later stages of the algorithm.
169 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
170 N = DFSPass(Roots[i], Info[Roots[i]], 0);
172 for (unsigned i = N; i >= 2; --i) {
173 BasicBlock *W = Vertex[i];
174 InfoRec &WInfo = Info[W];
176 // Step #2: Calculate the semidominators of all vertices
177 for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
178 if (Info.count(*PI)) { // Only if this predecessor is reachable!
179 unsigned SemiU = Info[Eval(*PI)].Semi;
180 if (SemiU < WInfo.Semi)
184 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
186 BasicBlock *WParent = WInfo.Parent;
187 Link(WParent, W, WInfo);
189 // Step #3: Implicitly define the immediate dominator of vertices
190 std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
191 while (!WParentBucket.empty()) {
192 BasicBlock *V = WParentBucket.back();
193 WParentBucket.pop_back();
194 BasicBlock *U = Eval(V);
195 IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
199 // Step #4: Explicitly define the immediate dominator of each vertex
200 for (unsigned i = 2; i <= N; ++i) {
201 BasicBlock *W = Vertex[i];
202 BasicBlock *&WIDom = IDoms[W];
203 if (WIDom != Vertex[Info[W].Semi])
204 WIDom = IDoms[WIDom];
207 // Free temporary memory used to construct idom's
209 std::vector<BasicBlock*>().swap(Vertex);
214 void ImmediateDominatorsBase::print(std::ostream &o, const Module* ) const {
215 Function *F = getRoots()[0]->getParent();
216 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
217 o << " Immediate Dominator For Basic Block:";
218 WriteAsOperand(o, I, false);
220 if (BasicBlock *ID = get(I))
221 WriteAsOperand(o, ID, false);
223 o << " <<exit node>>";
231 //===----------------------------------------------------------------------===//
232 // DominatorSet Implementation
233 //===----------------------------------------------------------------------===//
235 static RegisterAnalysis<DominatorSet>
236 B("domset", "Dominator Set Construction", true);
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.
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);
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*/;
249 if(!IsPostDominators) {
250 // A dominates B if it is found first in the basic block.
253 // A post-dominates B if B is found first in the basic block.
259 // runOnFunction - This method calculates the forward dominator sets for the
260 // specified function.
262 bool DominatorSet::runOnFunction(Function &F) {
263 BasicBlock *Root = &F.getEntryBlock();
265 Roots.push_back(Root);
266 assert(pred_begin(Root) == pred_end(Root) &&
267 "Root node has predecessors in function!");
269 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
271 if (Roots.empty()) return false;
273 // Root nodes only dominate themselves.
274 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
275 Doms[Roots[i]].insert(Roots[i]);
277 // Loop over all of the blocks in the function, calculating dominator sets for
279 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
280 if (BasicBlock *IDom = ID[I]) { // Get idom if block is reachable
281 DomSetType &DS = Doms[I];
282 assert(DS.empty() && "Domset already filled in for this block?");
283 DS.insert(I); // Blocks always dominate themselves
285 // Insert all dominators into the set...
287 // If we have already computed the dominator sets for our immediate
288 // dominator, just use it instead of walking all the way up to the root.
289 DomSetType &IDS = Doms[IDom];
291 DS.insert(IDS.begin(), IDS.end());
299 // Ensure that every basic block has at least an empty set of nodes. This
300 // is important for the case when there is unreachable blocks.
307 void DominatorSet::stub() {}
310 static std::ostream &operator<<(std::ostream &o,
311 const std::set<BasicBlock*> &BBs) {
312 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
315 WriteAsOperand(o, *I, false);
317 o << " <<exit node>>";
322 void DominatorSetBase::print(std::ostream &o, const Module* ) const {
323 for (const_iterator I = begin(), E = end(); I != E; ++I) {
324 o << " DomSet For BB: ";
326 WriteAsOperand(o, I->first, false);
328 o << " <<exit node>>";
329 o << " is:\t" << I->second << "\n";
333 //===----------------------------------------------------------------------===//
334 // DominatorTree Implementation
335 //===----------------------------------------------------------------------===//
337 static RegisterAnalysis<DominatorTree>
338 E("domtree", "Dominator Tree Construction", true);
340 // DominatorTreeBase::reset - Free all of the tree node memory.
342 void DominatorTreeBase::reset() {
343 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
349 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
350 assert(IDom && "No immediate dominator?");
351 if (IDom != NewIDom) {
352 std::vector<Node*>::iterator I =
353 std::find(IDom->Children.begin(), IDom->Children.end(), this);
354 assert(I != IDom->Children.end() &&
355 "Not in immediate dominator children set!");
356 // I am no longer your child...
357 IDom->Children.erase(I);
359 // Switch to new dominator
361 IDom->Children.push_back(this);
365 DominatorTreeBase::Node *DominatorTree::getNodeForBlock(BasicBlock *BB) {
366 Node *&BBNode = Nodes[BB];
367 if (BBNode) return BBNode;
369 // Haven't calculated this node yet? Get or calculate the node for the
370 // immediate dominator.
371 BasicBlock *IDom = getAnalysis<ImmediateDominators>()[BB];
372 Node *IDomNode = getNodeForBlock(IDom);
374 // Add a new tree node for this BasicBlock, and link it as a child of
376 return BBNode = IDomNode->addChild(new Node(BB, IDomNode));
379 void DominatorTree::calculate(const ImmediateDominators &ID) {
380 assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
381 BasicBlock *Root = Roots[0];
382 Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
384 Function *F = Root->getParent();
385 // Loop over all of the reachable blocks in the function...
386 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
387 if (BasicBlock *ImmDom = ID.get(I)) { // Reachable block.
388 Node *&BBNode = Nodes[I];
389 if (!BBNode) { // Haven't calculated this node yet?
390 // Get or calculate the node for the immediate dominator
391 Node *IDomNode = getNodeForBlock(ImmDom);
393 // Add a new tree node for this BasicBlock, and link it as a child of
395 BBNode = IDomNode->addChild(new Node(I, IDomNode));
400 static std::ostream &operator<<(std::ostream &o,
401 const DominatorTreeBase::Node *Node) {
402 if (Node->getBlock())
403 WriteAsOperand(o, Node->getBlock(), false);
405 o << " <<exit node>>";
409 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
411 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
412 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
414 PrintDomTree(*I, o, Lev+1);
417 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
418 o << "=============================--------------------------------\n"
419 << "Inorder Dominator Tree:\n";
420 PrintDomTree(getRootNode(), o, 1);
424 //===----------------------------------------------------------------------===//
425 // DominanceFrontier Implementation
426 //===----------------------------------------------------------------------===//
428 static RegisterAnalysis<DominanceFrontier>
429 G("domfrontier", "Dominance Frontier Construction", true);
431 const DominanceFrontier::DomSetType &
432 DominanceFrontier::calculate(const DominatorTree &DT,
433 const DominatorTree::Node *Node) {
434 // Loop over CFG successors to calculate DFlocal[Node]
435 BasicBlock *BB = Node->getBlock();
436 DomSetType &S = Frontiers[BB]; // The new set to fill in...
438 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
440 // Does Node immediately dominate this successor?
441 if (DT[*SI]->getIDom() != Node)
445 // At this point, S is DFlocal. Now we union in DFup's of our children...
446 // Loop through and visit the nodes that Node immediately dominates (Node's
447 // children in the IDomTree)
449 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
451 DominatorTree::Node *IDominee = *NI;
452 const DomSetType &ChildDF = calculate(DT, IDominee);
454 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
455 for (; CDFI != CDFE; ++CDFI) {
456 if (!Node->properlyDominates(DT[*CDFI]))
464 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
465 for (const_iterator I = begin(), E = end(); I != E; ++I) {
466 o << " DomFrontier for BB";
468 WriteAsOperand(o, I->first, false);
470 o << " <<exit node>>";
471 o << " is:\t" << I->second << "\n";