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"
17 //===----------------------------------------------------------------------===//
18 // DominatorSet Implementation
19 //===----------------------------------------------------------------------===//
21 static RegisterAnalysis<DominatorSet>
22 A("domset", "Dominator Set Construction", true);
24 // dominates - Return true if A dominates B. This performs the special checks
25 // neccesary if A and B are in the same basic block.
27 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
28 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
29 if (BBA != BBB) return dominates(BBA, BBB);
31 // Loop through the basic block until we find A or B.
32 BasicBlock::iterator I = BBA->begin();
33 for (; &*I != A && &*I != B; ++I) /*empty*/;
35 // A dominates B if it is found first in the basic block...
40 void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
42 Doms[RootBB].insert(RootBB); // Root always dominates itself...
46 DomSetType WorkingSet;
47 df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
48 for ( ; It != End; ++It) {
50 pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
51 if (PI != PEnd) { // Is there SOME predecessor?
52 // Loop until we get to a predecessor that has had it's dom set filled
53 // in at least once. We are guaranteed to have this because we are
54 // traversing the graph in DFO and have handled start nodes specially.
56 while (Doms[*PI].empty()) ++PI;
57 WorkingSet = Doms[*PI];
59 for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
60 DomSetType &PredSet = Doms[*PI];
62 set_intersect(WorkingSet, PredSet);
64 } else if (BB != Root) {
65 // If this isn't the root basic block and it has no predecessors, it
66 // must be an unreachable block. Fib a bit by saying that the root node
67 // dominates this unreachable node. This isn't exactly true, because
68 // there is no path from the entry node to this node, but it is sorta
69 // true because any paths to this node would have to go through the
72 // This allows for dominator properties to be built for unreachable code
73 // in a reasonable manner.
75 WorkingSet = Doms[Root];
78 WorkingSet.insert(BB); // A block always dominates itself
79 DomSetType &BBSet = Doms[BB];
80 if (BBSet != WorkingSet) {
81 BBSet.swap(WorkingSet); // Constant time operation!
82 Changed = true; // The sets changed.
84 WorkingSet.clear(); // Clear out the set for next iteration
91 // runOnFunction - This method calculates the forward dominator sets for the
92 // specified function.
94 bool DominatorSet::runOnFunction(Function &F) {
95 Root = &F.getEntryNode();
96 assert(pred_begin(Root) == pred_end(Root) &&
97 "Root node has predecessors in function!");
102 void DominatorSet::recalculate() {
103 Doms.clear(); // Reset from the last time we were run...
105 // Calculate dominator sets for the reachable basic blocks...
106 calculateDominatorsFromBlock(Root);
108 // Every basic block in the function should at least dominate themselves, and
109 // thus every basic block should have an entry in Doms. The one case where we
110 // miss this is when a basic block is unreachable. To get these we now do an
111 // extra pass over the function, calculating dominator information for
112 // unreachable blocks.
114 Function *F = Root->getParent();
115 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
116 if (Doms[I].count(I) == 0)
117 calculateDominatorsFromBlock(I);
121 static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
122 for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
125 WriteAsOperand(o, *I, false);
131 void DominatorSetBase::print(std::ostream &o) const {
132 for (const_iterator I = begin(), E = end(); I != E; ++I) {
133 o << "=============================--------------------------------\n"
134 << "\nDominator Set For Basic Block: ";
135 WriteAsOperand(o, I->first, false);
136 o << "\n-------------------------------\n" << I->second << "\n";
140 //===----------------------------------------------------------------------===//
141 // ImmediateDominators Implementation
142 //===----------------------------------------------------------------------===//
144 static RegisterAnalysis<ImmediateDominators>
145 C("idom", "Immediate Dominators Construction", true);
147 // calcIDoms - Calculate the immediate dominator mapping, given a set of
148 // dominators for every basic block.
149 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
150 // Loop over all of the nodes that have dominators... figuring out the IDOM
153 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
155 BasicBlock *BB = DI->first;
156 const DominatorSet::DomSetType &Dominators = DI->second;
157 unsigned DomSetSize = Dominators.size();
158 if (DomSetSize == 1) continue; // Root node... IDom = null
160 // Loop over all dominators of this node. This corresponds to looping over
161 // nodes in the dominator chain, looking for a node whose dominator set is
162 // equal to the current nodes, except that the current node does not exist
163 // in it. This means that it is one level higher in the dom chain than the
164 // current node, and it is our idom!
166 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
167 DominatorSet::DomSetType::const_iterator End = Dominators.end();
168 for (; I != End; ++I) { // Iterate over dominators...
169 // All of our dominators should form a chain, where the number of elements
170 // in the dominator set indicates what level the node is at in the chain.
171 // We want the node immediately above us, so it will have an identical
172 // dominator set, except that BB will not dominate it... therefore it's
173 // dominator set size will be one less than BB's...
175 if (DS.getDominators(*I).size() == DomSetSize - 1) {
183 void ImmediateDominatorsBase::print(std::ostream &o) const {
184 for (const_iterator I = begin(), E = end(); I != E; ++I) {
185 o << "=============================--------------------------------\n"
186 << "\nImmediate Dominator For Basic Block:";
187 WriteAsOperand(o, I->first, false);
189 WriteAsOperand(o, I->second, false);
195 //===----------------------------------------------------------------------===//
196 // DominatorTree Implementation
197 //===----------------------------------------------------------------------===//
199 static RegisterAnalysis<DominatorTree>
200 E("domtree", "Dominator Tree Construction", true);
202 // DominatorTreeBase::reset - Free all of the tree node memory.
204 void DominatorTreeBase::reset() {
205 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
210 void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
211 assert(IDom && "No immediate dominator?");
212 if (IDom != NewIDom) {
213 std::vector<Node*>::iterator I =
214 std::find(IDom->Children.begin(), IDom->Children.end(), this);
215 assert(I != IDom->Children.end() &&
216 "Not in immediate dominator children set!");
217 // I am no longer your child...
218 IDom->Children.erase(I);
220 // Switch to new dominator
222 IDom->Children.push_back(this);
228 void DominatorTree::calculate(const DominatorSet &DS) {
229 Nodes[Root] = new Node(Root, 0); // Add a node for the root...
231 // Iterate over all nodes in depth first order...
232 for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
235 const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
236 unsigned DomSetSize = Dominators.size();
237 if (DomSetSize == 1) continue; // Root node... IDom = null
239 // Loop over all dominators of this node. This corresponds to looping over
240 // nodes in the dominator chain, looking for a node whose dominator set is
241 // equal to the current nodes, except that the current node does not exist
242 // in it. This means that it is one level higher in the dom chain than the
243 // current node, and it is our idom! We know that we have already added
244 // a DominatorTree node for our idom, because the idom must be a
245 // predecessor in the depth first order that we are iterating through the
248 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
249 DominatorSet::DomSetType::const_iterator End = Dominators.end();
250 for (; I != End; ++I) { // Iterate over dominators...
251 // All of our dominators should form a chain, where the number of
252 // elements in the dominator set indicates what level the node is at in
253 // the chain. We want the node immediately above us, so it will have
254 // an identical dominator set, except that BB will not dominate it...
255 // therefore it's dominator set size will be one less than BB's...
257 if (DS.getDominators(*I).size() == DomSetSize - 1) {
258 // We know that the immediate dominator should already have a node,
259 // because we are traversing the CFG in depth first order!
261 Node *IDomNode = Nodes[*I];
262 assert(IDomNode && "No node for IDOM?");
264 // Add a new tree node for this BasicBlock, and link it as a child of
266 Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
274 static std::ostream &operator<<(std::ostream &o,
275 const DominatorTreeBase::Node *Node) {
276 return o << Node->getNode()
277 << "\n------------------------------------------\n";
280 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
282 o << "Level #" << Lev << ": " << N;
283 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
285 PrintDomTree(*I, o, Lev+1);
289 void DominatorTreeBase::print(std::ostream &o) const {
290 o << "=============================--------------------------------\n"
291 << "Inorder Dominator Tree:\n";
292 PrintDomTree(Nodes.find(getRoot())->second, o, 1);
296 //===----------------------------------------------------------------------===//
297 // DominanceFrontier Implementation
298 //===----------------------------------------------------------------------===//
300 static RegisterAnalysis<DominanceFrontier>
301 G("domfrontier", "Dominance Frontier Construction", true);
303 const DominanceFrontier::DomSetType &
304 DominanceFrontier::calculate(const DominatorTree &DT,
305 const DominatorTree::Node *Node) {
306 // Loop over CFG successors to calculate DFlocal[Node]
307 BasicBlock *BB = Node->getNode();
308 DomSetType &S = Frontiers[BB]; // The new set to fill in...
310 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
312 // Does Node immediately dominate this successor?
313 if (DT[*SI]->getIDom() != Node)
317 // At this point, S is DFlocal. Now we union in DFup's of our children...
318 // Loop through and visit the nodes that Node immediately dominates (Node's
319 // children in the IDomTree)
321 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
323 DominatorTree::Node *IDominee = *NI;
324 const DomSetType &ChildDF = calculate(DT, IDominee);
326 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
327 for (; CDFI != CDFE; ++CDFI) {
328 if (!Node->dominates(DT[*CDFI]))
336 void DominanceFrontierBase::print(std::ostream &o) const {
337 for (const_iterator I = begin(), E = end(); I != E; ++I) {
338 o << "=============================--------------------------------\n"
339 << "\nDominance Frontier For Basic Block\n";
340 WriteAsOperand(o, I->first, false);
341 o << " is: \n" << I->second << "\n";