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"
25 //===----------------------------------------------------------------------===//
26 // DominatorSet Implementation
27 //===----------------------------------------------------------------------===//
29 static RegisterAnalysis<DominatorSet>
30 A("domset", "Dominator Set Construction", true);
32 // dominates - Return true if A dominates B. This performs the special checks
33 // necessary if A and B are in the same basic block.
35 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
36 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
37 if (BBA != BBB) return dominates(BBA, BBB);
39 // Loop through the basic block until we find A or B.
40 BasicBlock::iterator I = BBA->begin();
41 for (; &*I != A && &*I != B; ++I) /*empty*/;
43 // A dominates B if it is found first in the basic block...
48 void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
50 Doms[RootBB].insert(RootBB); // Root always dominates itself...
54 DomSetType WorkingSet;
55 df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
56 for ( ; It != End; ++It) {
58 pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
59 if (PI != PEnd) { // Is there SOME predecessor?
60 // Loop until we get to a predecessor that has had its dom set filled
61 // in at least once. We are guaranteed to have this because we are
62 // traversing the graph in DFO and have handled start nodes specially,
63 // except when there are unreachable blocks.
65 while (PI != PEnd && Doms[*PI].empty()) ++PI;
66 if (PI != PEnd) { // Not unreachable code case?
67 WorkingSet = Doms[*PI];
69 // Intersect all of the predecessor sets
70 for (++PI; PI != PEnd; ++PI) {
71 DomSetType &PredSet = Doms[*PI];
73 set_intersect(WorkingSet, PredSet);
77 assert(Roots.size() == 1 && BB == Roots[0] &&
78 "We got into unreachable code somehow!");
81 WorkingSet.insert(BB); // A block always dominates itself
82 DomSetType &BBSet = Doms[BB];
83 if (BBSet != WorkingSet) {
84 //assert(WorkingSet.size() > BBSet.size() && "Must only grow sets!");
85 BBSet.swap(WorkingSet); // Constant time operation!
86 Changed = true; // The sets changed.
88 WorkingSet.clear(); // Clear out the set for next iteration
95 // runOnFunction - This method calculates the forward dominator sets for the
96 // specified function.
98 bool DominatorSet::runOnFunction(Function &F) {
99 BasicBlock *Root = &F.getEntryBlock();
101 Roots.push_back(Root);
102 assert(pred_begin(Root) == pred_end(Root) &&
103 "Root node has predecessors in function!");
108 void DominatorSet::recalculate() {
109 assert(Roots.size() == 1 && "DominatorSet should have single root block!");
110 Doms.clear(); // Reset from the last time we were run...
112 // Calculate dominator sets for the reachable basic blocks...
113 calculateDominatorsFromBlock(Roots[0]);
116 // Loop through the function, ensuring that every basic block has at least an
117 // empty set of nodes. This is important for the case when there is
118 // unreachable blocks.
119 Function *F = Roots[0]->getParent();
120 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) Doms[I];
124 static std::ostream &operator<<(std::ostream &o,
125 const std::set<BasicBlock*> &BBs) {
126 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
129 WriteAsOperand(o, *I, false);
131 o << " <<exit node>>";
135 void DominatorSetBase::print(std::ostream &o) const {
136 for (const_iterator I = begin(), E = end(); I != E; ++I) {
137 o << " DomSet For BB: ";
139 WriteAsOperand(o, I->first, false);
141 o << " <<exit node>>";
142 o << " is:\t" << I->second << "\n";
146 //===----------------------------------------------------------------------===//
147 // ImmediateDominators Implementation
148 //===----------------------------------------------------------------------===//
150 static RegisterAnalysis<ImmediateDominators>
151 C("idom", "Immediate Dominators Construction", true);
153 // calcIDoms - Calculate the immediate dominator mapping, given a set of
154 // dominators for every basic block.
155 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
156 // Loop over all of the nodes that have dominators... figuring out the IDOM
159 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
161 BasicBlock *BB = DI->first;
162 const DominatorSet::DomSetType &Dominators = DI->second;
163 unsigned DomSetSize = Dominators.size();
164 if (DomSetSize == 1) continue; // Root node... IDom = null
166 // Loop over all dominators of this node. This corresponds to looping over
167 // nodes in the dominator chain, looking for a node whose dominator set is
168 // equal to the current nodes, except that the current node does not exist
169 // in it. This means that it is one level higher in the dom chain than the
170 // current node, and it is our idom!
172 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
173 DominatorSet::DomSetType::const_iterator End = Dominators.end();
174 for (; I != End; ++I) { // Iterate over dominators...
175 // All of our dominators should form a chain, where the number of elements
176 // in the dominator set indicates what level the node is at in the chain.
177 // We want the node immediately above us, so it will have an identical
178 // dominator set, except that BB will not dominate it... therefore it's
179 // dominator set size will be one less than BB's...
181 if (DS.getDominators(*I).size() == DomSetSize - 1) {
189 void ImmediateDominatorsBase::print(std::ostream &o) const {
190 for (const_iterator I = begin(), E = end(); I != E; ++I) {
191 o << " Immediate Dominator For Basic Block:";
193 WriteAsOperand(o, I->first, false);
195 o << " <<exit node>>";
198 WriteAsOperand(o, I->second, false);
200 o << " <<exit node>>";
207 //===----------------------------------------------------------------------===//
208 // DominatorTree Implementation
209 //===----------------------------------------------------------------------===//
211 static RegisterAnalysis<DominatorTree>
212 E("domtree", "Dominator Tree Construction", true);
214 // DominatorTreeBase::reset - Free all of the tree node memory.
216 void DominatorTreeBase::reset() {
217 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
223 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
224 assert(IDom && "No immediate dominator?");
225 if (IDom != NewIDom) {
226 std::vector<Node*>::iterator I =
227 std::find(IDom->Children.begin(), IDom->Children.end(), this);
228 assert(I != IDom->Children.end() &&
229 "Not in immediate dominator children set!");
230 // I am no longer your child...
231 IDom->Children.erase(I);
233 // Switch to new dominator
235 IDom->Children.push_back(this);
241 void DominatorTree::calculate(const DominatorSet &DS) {
242 assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
243 BasicBlock *Root = Roots[0];
244 Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
246 // Iterate over all nodes in depth first order...
247 for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
250 const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
251 unsigned DomSetSize = Dominators.size();
252 if (DomSetSize == 1) continue; // Root node... IDom = null
254 // Loop over all dominators of this node. This corresponds to looping over
255 // nodes in the dominator chain, looking for a node whose dominator set is
256 // equal to the current nodes, except that the current node does not exist
257 // in it. This means that it is one level higher in the dom chain than the
258 // current node, and it is our idom! We know that we have already added
259 // a DominatorTree node for our idom, because the idom must be a
260 // predecessor in the depth first order that we are iterating through the
263 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
264 DominatorSet::DomSetType::const_iterator End = Dominators.end();
265 for (; I != End; ++I) { // Iterate over dominators...
266 // All of our dominators should form a chain, where the number of
267 // elements in the dominator set indicates what level the node is at in
268 // the chain. We want the node immediately above us, so it will have
269 // an identical dominator set, except that BB will not dominate it...
270 // therefore it's dominator set size will be one less than BB's...
272 if (DS.getDominators(*I).size() == DomSetSize - 1) {
273 // We know that the immediate dominator should already have a node,
274 // because we are traversing the CFG in depth first order!
276 Node *IDomNode = Nodes[*I];
277 assert(IDomNode && "No node for IDOM?");
279 // Add a new tree node for this BasicBlock, and link it as a child of
281 Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
289 static std::ostream &operator<<(std::ostream &o,
290 const DominatorTreeBase::Node *Node) {
291 if (Node->getBlock())
292 WriteAsOperand(o, Node->getBlock(), false);
294 o << " <<exit node>>";
298 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
300 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
301 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
303 PrintDomTree(*I, o, Lev+1);
306 void DominatorTreeBase::print(std::ostream &o) const {
307 o << "=============================--------------------------------\n"
308 << "Inorder Dominator Tree:\n";
309 PrintDomTree(getRootNode(), o, 1);
313 //===----------------------------------------------------------------------===//
314 // DominanceFrontier Implementation
315 //===----------------------------------------------------------------------===//
317 static RegisterAnalysis<DominanceFrontier>
318 G("domfrontier", "Dominance Frontier Construction", true);
320 const DominanceFrontier::DomSetType &
321 DominanceFrontier::calculate(const DominatorTree &DT,
322 const DominatorTree::Node *Node) {
323 // Loop over CFG successors to calculate DFlocal[Node]
324 BasicBlock *BB = Node->getBlock();
325 DomSetType &S = Frontiers[BB]; // The new set to fill in...
327 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
329 // Does Node immediately dominate this successor?
330 if (DT[*SI]->getIDom() != Node)
334 // At this point, S is DFlocal. Now we union in DFup's of our children...
335 // Loop through and visit the nodes that Node immediately dominates (Node's
336 // children in the IDomTree)
338 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
340 DominatorTree::Node *IDominee = *NI;
341 const DomSetType &ChildDF = calculate(DT, IDominee);
343 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
344 for (; CDFI != CDFE; ++CDFI) {
345 if (!Node->dominates(DT[*CDFI]))
353 void DominanceFrontierBase::print(std::ostream &o) const {
354 for (const_iterator I = begin(), E = end(); I != E; ++I) {
355 o << " DomFrontier for BB";
357 WriteAsOperand(o, I->first, false);
359 o << " <<exit node>>";
360 o << " is:\t" << I->second << "\n";
364 } // End llvm namespace