1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
3 // This file implements simple dominator construction algorithms for finding
4 // forward dominators. Postdominators are available in libanalysis, but are not
5 // included in libvmcore, because it's not needed. Forward dominators are
6 // needed to support the Verifier pass.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Analysis/Dominators.h"
11 #include "llvm/Support/CFG.h"
12 #include "llvm/Assembly/Writer.h"
13 #include "Support/DepthFirstIterator.h"
14 #include "Support/SetOperations.h"
16 //===----------------------------------------------------------------------===//
17 // DominatorSet Implementation
18 //===----------------------------------------------------------------------===//
20 static RegisterAnalysis<DominatorSet>
21 A("domset", "Dominator Set Construction", true);
23 // dominates - Return true if A dominates B. This performs the special checks
24 // necessary if A and B are in the same basic block.
26 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
27 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
28 if (BBA != BBB) return dominates(BBA, BBB);
30 // Loop through the basic block until we find A or B.
31 BasicBlock::iterator I = BBA->begin();
32 for (; &*I != A && &*I != B; ++I) /*empty*/;
34 // A dominates B if it is found first in the basic block...
39 void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
41 Doms[RootBB].insert(RootBB); // Root always dominates itself...
45 DomSetType WorkingSet;
46 df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
47 for ( ; It != End; ++It) {
49 pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
50 if (PI != PEnd) { // Is there SOME predecessor?
51 // Loop until we get to a predecessor that has had its dom set filled
52 // in at least once. We are guaranteed to have this because we are
53 // traversing the graph in DFO and have handled start nodes specially,
54 // except when there are unreachable blocks.
56 while (PI != PEnd && Doms[*PI].empty()) ++PI;
57 if (PI != PEnd) { // Not unreachable code case?
58 WorkingSet = Doms[*PI];
60 // Intersect all of the predecessor sets
61 for (++PI; PI != PEnd; ++PI) {
62 DomSetType &PredSet = Doms[*PI];
64 set_intersect(WorkingSet, PredSet);
68 assert(Roots.size() == 1 && BB == Roots[0] &&
69 "We got into unreachable code somehow!");
72 WorkingSet.insert(BB); // A block always dominates itself
73 DomSetType &BBSet = Doms[BB];
74 if (BBSet != WorkingSet) {
75 //assert(WorkingSet.size() > BBSet.size() && "Must only grow sets!");
76 BBSet.swap(WorkingSet); // Constant time operation!
77 Changed = true; // The sets changed.
79 WorkingSet.clear(); // Clear out the set for next iteration
86 // runOnFunction - This method calculates the forward dominator sets for the
87 // specified function.
89 bool DominatorSet::runOnFunction(Function &F) {
90 BasicBlock *Root = &F.getEntryNode();
92 Roots.push_back(Root);
93 assert(pred_begin(Root) == pred_end(Root) &&
94 "Root node has predecessors in function!");
99 void DominatorSet::recalculate() {
100 assert(Roots.size() == 1 && "DominatorSet should have single root block!");
101 Doms.clear(); // Reset from the last time we were run...
103 // Calculate dominator sets for the reachable basic blocks...
104 calculateDominatorsFromBlock(Roots[0]);
107 // Loop through the function, ensuring that every basic block has at least an
108 // empty set of nodes. This is important for the case when there is
109 // unreachable blocks.
110 Function *F = Roots[0]->getParent();
111 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) Doms[I];
115 static std::ostream &operator<<(std::ostream &o,
116 const std::set<BasicBlock*> &BBs) {
117 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
120 WriteAsOperand(o, *I, false);
122 o << " <<exit node>>";
126 void DominatorSetBase::print(std::ostream &o) const {
127 for (const_iterator I = begin(), E = end(); I != E; ++I) {
128 o << " DomSet For BB: ";
130 WriteAsOperand(o, I->first, false);
132 o << " <<exit node>>";
133 o << " is:\t" << I->second << "\n";
137 //===----------------------------------------------------------------------===//
138 // ImmediateDominators Implementation
139 //===----------------------------------------------------------------------===//
141 static RegisterAnalysis<ImmediateDominators>
142 C("idom", "Immediate Dominators Construction", true);
144 // calcIDoms - Calculate the immediate dominator mapping, given a set of
145 // dominators for every basic block.
146 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
147 // Loop over all of the nodes that have dominators... figuring out the IDOM
150 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
152 BasicBlock *BB = DI->first;
153 const DominatorSet::DomSetType &Dominators = DI->second;
154 unsigned DomSetSize = Dominators.size();
155 if (DomSetSize == 1) continue; // Root node... IDom = null
157 // Loop over all dominators of this node. This corresponds to looping over
158 // nodes in the dominator chain, looking for a node whose dominator set is
159 // equal to the current nodes, except that the current node does not exist
160 // in it. This means that it is one level higher in the dom chain than the
161 // current node, and it is our idom!
163 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
164 DominatorSet::DomSetType::const_iterator End = Dominators.end();
165 for (; I != End; ++I) { // Iterate over dominators...
166 // All of our dominators should form a chain, where the number of elements
167 // in the dominator set indicates what level the node is at in the chain.
168 // We want the node immediately above us, so it will have an identical
169 // dominator set, except that BB will not dominate it... therefore it's
170 // dominator set size will be one less than BB's...
172 if (DS.getDominators(*I).size() == DomSetSize - 1) {
180 void ImmediateDominatorsBase::print(std::ostream &o) const {
181 for (const_iterator I = begin(), E = end(); I != E; ++I) {
182 o << " Immediate Dominator For Basic Block:";
184 WriteAsOperand(o, I->first, false);
186 o << " <<exit node>>";
189 WriteAsOperand(o, I->second, false);
191 o << " <<exit node>>";
198 //===----------------------------------------------------------------------===//
199 // DominatorTree Implementation
200 //===----------------------------------------------------------------------===//
202 static RegisterAnalysis<DominatorTree>
203 E("domtree", "Dominator Tree Construction", true);
205 // DominatorTreeBase::reset - Free all of the tree node memory.
207 void DominatorTreeBase::reset() {
208 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
214 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
215 assert(IDom && "No immediate dominator?");
216 if (IDom != NewIDom) {
217 std::vector<Node*>::iterator I =
218 std::find(IDom->Children.begin(), IDom->Children.end(), this);
219 assert(I != IDom->Children.end() &&
220 "Not in immediate dominator children set!");
221 // I am no longer your child...
222 IDom->Children.erase(I);
224 // Switch to new dominator
226 IDom->Children.push_back(this);
232 void DominatorTree::calculate(const DominatorSet &DS) {
233 assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
234 BasicBlock *Root = Roots[0];
235 Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
237 // Iterate over all nodes in depth first order...
238 for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
241 const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
242 unsigned DomSetSize = Dominators.size();
243 if (DomSetSize == 1) continue; // Root node... IDom = null
245 // Loop over all dominators of this node. This corresponds to looping over
246 // nodes in the dominator chain, looking for a node whose dominator set is
247 // equal to the current nodes, except that the current node does not exist
248 // in it. This means that it is one level higher in the dom chain than the
249 // current node, and it is our idom! We know that we have already added
250 // a DominatorTree node for our idom, because the idom must be a
251 // predecessor in the depth first order that we are iterating through the
254 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
255 DominatorSet::DomSetType::const_iterator End = Dominators.end();
256 for (; I != End; ++I) { // Iterate over dominators...
257 // All of our dominators should form a chain, where the number of
258 // elements in the dominator set indicates what level the node is at in
259 // the chain. We want the node immediately above us, so it will have
260 // an identical dominator set, except that BB will not dominate it...
261 // therefore it's dominator set size will be one less than BB's...
263 if (DS.getDominators(*I).size() == DomSetSize - 1) {
264 // We know that the immediate dominator should already have a node,
265 // because we are traversing the CFG in depth first order!
267 Node *IDomNode = Nodes[*I];
268 assert(IDomNode && "No node for IDOM?");
270 // Add a new tree node for this BasicBlock, and link it as a child of
272 Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
280 static std::ostream &operator<<(std::ostream &o,
281 const DominatorTreeBase::Node *Node) {
282 if (Node->getBlock())
283 WriteAsOperand(o, Node->getBlock(), false);
285 o << " <<exit node>>";
289 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
291 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
292 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
294 PrintDomTree(*I, o, Lev+1);
297 void DominatorTreeBase::print(std::ostream &o) const {
298 o << "=============================--------------------------------\n"
299 << "Inorder Dominator Tree:\n";
300 PrintDomTree(getRootNode(), o, 1);
304 //===----------------------------------------------------------------------===//
305 // DominanceFrontier Implementation
306 //===----------------------------------------------------------------------===//
308 static RegisterAnalysis<DominanceFrontier>
309 G("domfrontier", "Dominance Frontier Construction", true);
311 const DominanceFrontier::DomSetType &
312 DominanceFrontier::calculate(const DominatorTree &DT,
313 const DominatorTree::Node *Node) {
314 // Loop over CFG successors to calculate DFlocal[Node]
315 BasicBlock *BB = Node->getBlock();
316 DomSetType &S = Frontiers[BB]; // The new set to fill in...
318 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
320 // Does Node immediately dominate this successor?
321 if (DT[*SI]->getIDom() != Node)
325 // At this point, S is DFlocal. Now we union in DFup's of our children...
326 // Loop through and visit the nodes that Node immediately dominates (Node's
327 // children in the IDomTree)
329 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
331 DominatorTree::Node *IDominee = *NI;
332 const DomSetType &ChildDF = calculate(DT, IDominee);
334 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
335 for (; CDFI != CDFE; ++CDFI) {
336 if (!Node->dominates(DT[*CDFI]))
344 void DominanceFrontierBase::print(std::ostream &o) const {
345 for (const_iterator I = begin(), E = end(); I != E; ++I) {
346 o << " DomFrontier for BB";
348 WriteAsOperand(o, I->first, false);
350 o << " <<exit node>>";
351 o << " is:\t" << I->second << "\n";