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 // neccesary 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 it's 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);
67 // Otherwise this block is unreachable. it doesn't really matter what
68 // we use for the dominator set for the node...
70 WorkingSet = Doms[Root];
72 } else if (BB != Root) {
73 // If this isn't the root basic block and it has no predecessors, it
74 // must be an unreachable block. Fib a bit by saying that the root node
75 // dominates this unreachable node. This isn't exactly true, because
76 // there is no path from the entry node to this node, but it is sorta
77 // true because any paths to this node would have to go through the
80 // This allows for dominator properties to be built for unreachable code
81 // in a reasonable manner.
83 WorkingSet = Doms[Root];
86 WorkingSet.insert(BB); // A block always dominates itself
87 DomSetType &BBSet = Doms[BB];
88 if (BBSet != WorkingSet) {
89 BBSet.swap(WorkingSet); // Constant time operation!
90 Changed = true; // The sets changed.
92 WorkingSet.clear(); // Clear out the set for next iteration
99 // runOnFunction - This method calculates the forward dominator sets for the
100 // specified function.
102 bool DominatorSet::runOnFunction(Function &F) {
103 Root = &F.getEntryNode();
104 assert(pred_begin(Root) == pred_end(Root) &&
105 "Root node has predecessors in function!");
110 void DominatorSet::recalculate() {
111 Doms.clear(); // Reset from the last time we were run...
113 // Calculate dominator sets for the reachable basic blocks...
114 calculateDominatorsFromBlock(Root);
116 // Every basic block in the function should at least dominate themselves, and
117 // thus every basic block should have an entry in Doms. The one case where we
118 // miss this is when a basic block is unreachable. To get these we now do an
119 // extra pass over the function, calculating dominator information for
120 // unreachable blocks.
122 Function *F = Root->getParent();
123 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
124 if (Doms[I].count(I) == 0)
125 calculateDominatorsFromBlock(I);
129 static std::ostream &operator<<(std::ostream &o,
130 const std::set<BasicBlock*> &BBs) {
131 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
134 WriteAsOperand(o, *I, false);
140 void DominatorSetBase::print(std::ostream &o) const {
141 for (const_iterator I = begin(), E = end(); I != E; ++I) {
142 o << "=============================--------------------------------\n"
143 << "\nDominator Set For Basic Block: ";
144 WriteAsOperand(o, I->first, false);
145 o << "\n-------------------------------\n" << I->second << "\n";
149 //===----------------------------------------------------------------------===//
150 // ImmediateDominators Implementation
151 //===----------------------------------------------------------------------===//
153 static RegisterAnalysis<ImmediateDominators>
154 C("idom", "Immediate Dominators Construction", true);
156 // calcIDoms - Calculate the immediate dominator mapping, given a set of
157 // dominators for every basic block.
158 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
159 // Loop over all of the nodes that have dominators... figuring out the IDOM
162 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
164 BasicBlock *BB = DI->first;
165 const DominatorSet::DomSetType &Dominators = DI->second;
166 unsigned DomSetSize = Dominators.size();
167 if (DomSetSize == 1) continue; // Root node... IDom = null
169 // Loop over all dominators of this node. This corresponds to looping over
170 // nodes in the dominator chain, looking for a node whose dominator set is
171 // equal to the current nodes, except that the current node does not exist
172 // in it. This means that it is one level higher in the dom chain than the
173 // current node, and it is our idom!
175 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
176 DominatorSet::DomSetType::const_iterator End = Dominators.end();
177 for (; I != End; ++I) { // Iterate over dominators...
178 // All of our dominators should form a chain, where the number of elements
179 // in the dominator set indicates what level the node is at in the chain.
180 // We want the node immediately above us, so it will have an identical
181 // dominator set, except that BB will not dominate it... therefore it's
182 // dominator set size will be one less than BB's...
184 if (DS.getDominators(*I).size() == DomSetSize - 1) {
192 void ImmediateDominatorsBase::print(std::ostream &o) const {
193 for (const_iterator I = begin(), E = end(); I != E; ++I) {
194 o << "=============================--------------------------------\n"
195 << "\nImmediate Dominator For Basic Block:";
196 WriteAsOperand(o, I->first, false);
198 WriteAsOperand(o, I->second, false);
204 //===----------------------------------------------------------------------===//
205 // DominatorTree Implementation
206 //===----------------------------------------------------------------------===//
208 static RegisterAnalysis<DominatorTree>
209 E("domtree", "Dominator Tree Construction", true);
211 // DominatorTreeBase::reset - Free all of the tree node memory.
213 void DominatorTreeBase::reset() {
214 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
219 void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
220 assert(IDom && "No immediate dominator?");
221 if (IDom != NewIDom) {
222 std::vector<Node*>::iterator I =
223 std::find(IDom->Children.begin(), IDom->Children.end(), this);
224 assert(I != IDom->Children.end() &&
225 "Not in immediate dominator children set!");
226 // I am no longer your child...
227 IDom->Children.erase(I);
229 // Switch to new dominator
231 IDom->Children.push_back(this);
237 void DominatorTree::calculate(const DominatorSet &DS) {
238 Nodes[Root] = new Node(Root, 0); // Add a node for the root...
240 // Iterate over all nodes in depth first order...
241 for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
244 const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
245 unsigned DomSetSize = Dominators.size();
246 if (DomSetSize == 1) continue; // Root node... IDom = null
248 // Loop over all dominators of this node. This corresponds to looping over
249 // nodes in the dominator chain, looking for a node whose dominator set is
250 // equal to the current nodes, except that the current node does not exist
251 // in it. This means that it is one level higher in the dom chain than the
252 // current node, and it is our idom! We know that we have already added
253 // a DominatorTree node for our idom, because the idom must be a
254 // predecessor in the depth first order that we are iterating through the
257 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
258 DominatorSet::DomSetType::const_iterator End = Dominators.end();
259 for (; I != End; ++I) { // Iterate over dominators...
260 // All of our dominators should form a chain, where the number of
261 // elements in the dominator set indicates what level the node is at in
262 // the chain. We want the node immediately above us, so it will have
263 // an identical dominator set, except that BB will not dominate it...
264 // therefore it's dominator set size will be one less than BB's...
266 if (DS.getDominators(*I).size() == DomSetSize - 1) {
267 // We know that the immediate dominator should already have a node,
268 // because we are traversing the CFG in depth first order!
270 Node *IDomNode = Nodes[*I];
271 assert(IDomNode && "No node for IDOM?");
273 // Add a new tree node for this BasicBlock, and link it as a child of
275 Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
283 static std::ostream &operator<<(std::ostream &o,
284 const DominatorTreeBase::Node *Node) {
285 return o << Node->getNode()
286 << "\n------------------------------------------\n";
289 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
291 o << "Level #" << Lev << ": " << N;
292 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
294 PrintDomTree(*I, o, Lev+1);
298 void DominatorTreeBase::print(std::ostream &o) const {
299 o << "=============================--------------------------------\n"
300 << "Inorder Dominator Tree:\n";
301 PrintDomTree(Nodes.find(getRoot())->second, o, 1);
305 //===----------------------------------------------------------------------===//
306 // DominanceFrontier Implementation
307 //===----------------------------------------------------------------------===//
309 static RegisterAnalysis<DominanceFrontier>
310 G("domfrontier", "Dominance Frontier Construction", true);
312 const DominanceFrontier::DomSetType &
313 DominanceFrontier::calculate(const DominatorTree &DT,
314 const DominatorTree::Node *Node) {
315 // Loop over CFG successors to calculate DFlocal[Node]
316 BasicBlock *BB = Node->getNode();
317 DomSetType &S = Frontiers[BB]; // The new set to fill in...
319 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
321 // Does Node immediately dominate this successor?
322 if (DT[*SI]->getIDom() != Node)
326 // At this point, S is DFlocal. Now we union in DFup's of our children...
327 // Loop through and visit the nodes that Node immediately dominates (Node's
328 // children in the IDomTree)
330 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
332 DominatorTree::Node *IDominee = *NI;
333 const DomSetType &ChildDF = calculate(DT, IDominee);
335 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
336 for (; CDFI != CDFE; ++CDFI) {
337 if (!Node->dominates(DT[*CDFI]))
345 void DominanceFrontierBase::print(std::ostream &o) const {
346 for (const_iterator I = begin(), E = end(); I != E; ++I) {
347 o << "=============================--------------------------------\n"
348 << "\nDominance Frontier For Basic Block\n";
349 WriteAsOperand(o, I->first, false);
350 o << " is: \n" << I->second << "\n";