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 "Support/DepthFirstIterator.h"
21 #include "Support/SetOperations.h"
23 //===----------------------------------------------------------------------===//
24 // DominatorSet Implementation
25 //===----------------------------------------------------------------------===//
27 static RegisterAnalysis<DominatorSet>
28 A("domset", "Dominator Set Construction", true);
30 // dominates - Return true if A dominates B. This performs the special checks
31 // necessary if A and B are in the same basic block.
33 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
34 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
35 if (BBA != BBB) return dominates(BBA, BBB);
37 // Loop through the basic block until we find A or B.
38 BasicBlock::iterator I = BBA->begin();
39 for (; &*I != A && &*I != B; ++I) /*empty*/;
41 // A dominates B if it is found first in the basic block...
46 void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
48 Doms[RootBB].insert(RootBB); // Root always dominates itself...
52 DomSetType WorkingSet;
53 df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
54 for ( ; It != End; ++It) {
56 pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
57 if (PI != PEnd) { // Is there SOME predecessor?
58 // Loop until we get to a predecessor that has had its dom set filled
59 // in at least once. We are guaranteed to have this because we are
60 // traversing the graph in DFO and have handled start nodes specially,
61 // except when there are unreachable blocks.
63 while (PI != PEnd && Doms[*PI].empty()) ++PI;
64 if (PI != PEnd) { // Not unreachable code case?
65 WorkingSet = Doms[*PI];
67 // Intersect all of the predecessor sets
68 for (++PI; PI != PEnd; ++PI) {
69 DomSetType &PredSet = Doms[*PI];
71 set_intersect(WorkingSet, PredSet);
75 assert(Roots.size() == 1 && BB == Roots[0] &&
76 "We got into unreachable code somehow!");
79 WorkingSet.insert(BB); // A block always dominates itself
80 DomSetType &BBSet = Doms[BB];
81 if (BBSet != WorkingSet) {
82 //assert(WorkingSet.size() > BBSet.size() && "Must only grow sets!");
83 BBSet.swap(WorkingSet); // Constant time operation!
84 Changed = true; // The sets changed.
86 WorkingSet.clear(); // Clear out the set for next iteration
93 // runOnFunction - This method calculates the forward dominator sets for the
94 // specified function.
96 bool DominatorSet::runOnFunction(Function &F) {
97 BasicBlock *Root = &F.getEntryBlock();
99 Roots.push_back(Root);
100 assert(pred_begin(Root) == pred_end(Root) &&
101 "Root node has predecessors in function!");
106 void DominatorSet::recalculate() {
107 assert(Roots.size() == 1 && "DominatorSet should have single root block!");
108 Doms.clear(); // Reset from the last time we were run...
110 // Calculate dominator sets for the reachable basic blocks...
111 calculateDominatorsFromBlock(Roots[0]);
114 // Loop through the function, ensuring that every basic block has at least an
115 // empty set of nodes. This is important for the case when there is
116 // unreachable blocks.
117 Function *F = Roots[0]->getParent();
118 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) Doms[I];
122 static std::ostream &operator<<(std::ostream &o,
123 const std::set<BasicBlock*> &BBs) {
124 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
127 WriteAsOperand(o, *I, false);
129 o << " <<exit node>>";
133 void DominatorSetBase::print(std::ostream &o) const {
134 for (const_iterator I = begin(), E = end(); I != E; ++I) {
135 o << " DomSet For BB: ";
137 WriteAsOperand(o, I->first, false);
139 o << " <<exit node>>";
140 o << " is:\t" << I->second << "\n";
144 //===----------------------------------------------------------------------===//
145 // ImmediateDominators Implementation
146 //===----------------------------------------------------------------------===//
148 static RegisterAnalysis<ImmediateDominators>
149 C("idom", "Immediate Dominators Construction", true);
151 // calcIDoms - Calculate the immediate dominator mapping, given a set of
152 // dominators for every basic block.
153 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
154 // Loop over all of the nodes that have dominators... figuring out the IDOM
157 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
159 BasicBlock *BB = DI->first;
160 const DominatorSet::DomSetType &Dominators = DI->second;
161 unsigned DomSetSize = Dominators.size();
162 if (DomSetSize == 1) continue; // Root node... IDom = null
164 // Loop over all dominators of this node. This corresponds to looping over
165 // nodes in the dominator chain, looking for a node whose dominator set is
166 // equal to the current nodes, except that the current node does not exist
167 // in it. This means that it is one level higher in the dom chain than the
168 // current node, and it is our idom!
170 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
171 DominatorSet::DomSetType::const_iterator End = Dominators.end();
172 for (; I != End; ++I) { // Iterate over dominators...
173 // All of our dominators should form a chain, where the number of elements
174 // in the dominator set indicates what level the node is at in the chain.
175 // We want the node immediately above us, so it will have an identical
176 // dominator set, except that BB will not dominate it... therefore it's
177 // dominator set size will be one less than BB's...
179 if (DS.getDominators(*I).size() == DomSetSize - 1) {
187 void ImmediateDominatorsBase::print(std::ostream &o) const {
188 for (const_iterator I = begin(), E = end(); I != E; ++I) {
189 o << " Immediate Dominator For Basic Block:";
191 WriteAsOperand(o, I->first, false);
193 o << " <<exit node>>";
196 WriteAsOperand(o, I->second, false);
198 o << " <<exit node>>";
205 //===----------------------------------------------------------------------===//
206 // DominatorTree Implementation
207 //===----------------------------------------------------------------------===//
209 static RegisterAnalysis<DominatorTree>
210 E("domtree", "Dominator Tree Construction", true);
212 // DominatorTreeBase::reset - Free all of the tree node memory.
214 void DominatorTreeBase::reset() {
215 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
221 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
222 assert(IDom && "No immediate dominator?");
223 if (IDom != NewIDom) {
224 std::vector<Node*>::iterator I =
225 std::find(IDom->Children.begin(), IDom->Children.end(), this);
226 assert(I != IDom->Children.end() &&
227 "Not in immediate dominator children set!");
228 // I am no longer your child...
229 IDom->Children.erase(I);
231 // Switch to new dominator
233 IDom->Children.push_back(this);
239 void DominatorTree::calculate(const DominatorSet &DS) {
240 assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
241 BasicBlock *Root = Roots[0];
242 Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
244 // Iterate over all nodes in depth first order...
245 for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
248 const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
249 unsigned DomSetSize = Dominators.size();
250 if (DomSetSize == 1) continue; // Root node... IDom = null
252 // Loop over all dominators of this node. This corresponds to looping over
253 // nodes in the dominator chain, looking for a node whose dominator set is
254 // equal to the current nodes, except that the current node does not exist
255 // in it. This means that it is one level higher in the dom chain than the
256 // current node, and it is our idom! We know that we have already added
257 // a DominatorTree node for our idom, because the idom must be a
258 // predecessor in the depth first order that we are iterating through the
261 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
262 DominatorSet::DomSetType::const_iterator End = Dominators.end();
263 for (; I != End; ++I) { // Iterate over dominators...
264 // All of our dominators should form a chain, where the number of
265 // elements in the dominator set indicates what level the node is at in
266 // the chain. We want the node immediately above us, so it will have
267 // an identical dominator set, except that BB will not dominate it...
268 // therefore it's dominator set size will be one less than BB's...
270 if (DS.getDominators(*I).size() == DomSetSize - 1) {
271 // We know that the immediate dominator should already have a node,
272 // because we are traversing the CFG in depth first order!
274 Node *IDomNode = Nodes[*I];
275 assert(IDomNode && "No node for IDOM?");
277 // Add a new tree node for this BasicBlock, and link it as a child of
279 Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
287 static std::ostream &operator<<(std::ostream &o,
288 const DominatorTreeBase::Node *Node) {
289 if (Node->getBlock())
290 WriteAsOperand(o, Node->getBlock(), false);
292 o << " <<exit node>>";
296 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
298 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
299 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
301 PrintDomTree(*I, o, Lev+1);
304 void DominatorTreeBase::print(std::ostream &o) const {
305 o << "=============================--------------------------------\n"
306 << "Inorder Dominator Tree:\n";
307 PrintDomTree(getRootNode(), o, 1);
311 //===----------------------------------------------------------------------===//
312 // DominanceFrontier Implementation
313 //===----------------------------------------------------------------------===//
315 static RegisterAnalysis<DominanceFrontier>
316 G("domfrontier", "Dominance Frontier Construction", true);
318 const DominanceFrontier::DomSetType &
319 DominanceFrontier::calculate(const DominatorTree &DT,
320 const DominatorTree::Node *Node) {
321 // Loop over CFG successors to calculate DFlocal[Node]
322 BasicBlock *BB = Node->getBlock();
323 DomSetType &S = Frontiers[BB]; // The new set to fill in...
325 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
327 // Does Node immediately dominate this successor?
328 if (DT[*SI]->getIDom() != Node)
332 // At this point, S is DFlocal. Now we union in DFup's of our children...
333 // Loop through and visit the nodes that Node immediately dominates (Node's
334 // children in the IDomTree)
336 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
338 DominatorTree::Node *IDominee = *NI;
339 const DomSetType &ChildDF = calculate(DT, IDominee);
341 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
342 for (; CDFI != CDFE; ++CDFI) {
343 if (!Node->dominates(DT[*CDFI]))
351 void DominanceFrontierBase::print(std::ostream &o) const {
352 for (const_iterator I = begin(), E = end(); I != E; ++I) {
353 o << " DomFrontier for BB";
355 WriteAsOperand(o, I->first, false);
357 o << " <<exit node>>";
358 o << " is:\t" << I->second << "\n";