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(BB == Root && "We got into unreachable code somehow!");
71 WorkingSet.insert(BB); // A block always dominates itself
72 DomSetType &BBSet = Doms[BB];
73 if (BBSet != WorkingSet) {
74 //assert(WorkingSet.size() > BBSet.size() && "Must only grow sets!");
75 BBSet.swap(WorkingSet); // Constant time operation!
76 Changed = true; // The sets changed.
78 WorkingSet.clear(); // Clear out the set for next iteration
85 // runOnFunction - This method calculates the forward dominator sets for the
86 // specified function.
88 bool DominatorSet::runOnFunction(Function &F) {
89 Root = &F.getEntryNode();
90 assert(pred_begin(Root) == pred_end(Root) &&
91 "Root node has predecessors in function!");
96 void DominatorSet::recalculate() {
97 Doms.clear(); // Reset from the last time we were run...
99 // Calculate dominator sets for the reachable basic blocks...
100 calculateDominatorsFromBlock(Root);
103 // Loop through the function, ensuring that every basic block has at least an
104 // empty set of nodes. This is important for the case when there is
105 // unreachable blocks.
106 Function *F = Root->getParent();
107 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) Doms[I];
111 static std::ostream &operator<<(std::ostream &o,
112 const std::set<BasicBlock*> &BBs) {
113 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
116 WriteAsOperand(o, *I, false);
122 void DominatorSetBase::print(std::ostream &o) const {
123 for (const_iterator I = begin(), E = end(); I != E; ++I) {
124 o << "=============================--------------------------------\n"
125 << "\nDominator Set For Basic Block: ";
126 WriteAsOperand(o, I->first, false);
127 o << "\n-------------------------------\n" << I->second << "\n";
131 //===----------------------------------------------------------------------===//
132 // ImmediateDominators Implementation
133 //===----------------------------------------------------------------------===//
135 static RegisterAnalysis<ImmediateDominators>
136 C("idom", "Immediate Dominators Construction", true);
138 // calcIDoms - Calculate the immediate dominator mapping, given a set of
139 // dominators for every basic block.
140 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
141 // Loop over all of the nodes that have dominators... figuring out the IDOM
144 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
146 BasicBlock *BB = DI->first;
147 const DominatorSet::DomSetType &Dominators = DI->second;
148 unsigned DomSetSize = Dominators.size();
149 if (DomSetSize == 1) continue; // Root node... IDom = null
151 // Loop over all dominators of this node. This corresponds to looping over
152 // nodes in the dominator chain, looking for a node whose dominator set is
153 // equal to the current nodes, except that the current node does not exist
154 // in it. This means that it is one level higher in the dom chain than the
155 // current node, and it is our idom!
157 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
158 DominatorSet::DomSetType::const_iterator End = Dominators.end();
159 for (; I != End; ++I) { // Iterate over dominators...
160 // All of our dominators should form a chain, where the number of elements
161 // in the dominator set indicates what level the node is at in the chain.
162 // We want the node immediately above us, so it will have an identical
163 // dominator set, except that BB will not dominate it... therefore it's
164 // dominator set size will be one less than BB's...
166 if (DS.getDominators(*I).size() == DomSetSize - 1) {
174 void ImmediateDominatorsBase::print(std::ostream &o) const {
175 for (const_iterator I = begin(), E = end(); I != E; ++I) {
176 o << "=============================--------------------------------\n"
177 << "\nImmediate Dominator For Basic Block:";
178 WriteAsOperand(o, I->first, false);
180 WriteAsOperand(o, I->second, false);
186 //===----------------------------------------------------------------------===//
187 // DominatorTree Implementation
188 //===----------------------------------------------------------------------===//
190 static RegisterAnalysis<DominatorTree>
191 E("domtree", "Dominator Tree Construction", true);
193 // DominatorTreeBase::reset - Free all of the tree node memory.
195 void DominatorTreeBase::reset() {
196 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
201 void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
202 assert(IDom && "No immediate dominator?");
203 if (IDom != NewIDom) {
204 std::vector<Node*>::iterator I =
205 std::find(IDom->Children.begin(), IDom->Children.end(), this);
206 assert(I != IDom->Children.end() &&
207 "Not in immediate dominator children set!");
208 // I am no longer your child...
209 IDom->Children.erase(I);
211 // Switch to new dominator
213 IDom->Children.push_back(this);
219 void DominatorTree::calculate(const DominatorSet &DS) {
220 Nodes[Root] = new Node(Root, 0); // Add a node for the root...
222 // Iterate over all nodes in depth first order...
223 for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
226 const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
227 unsigned DomSetSize = Dominators.size();
228 if (DomSetSize == 1) continue; // Root node... IDom = null
230 // Loop over all dominators of this node. This corresponds to looping over
231 // nodes in the dominator chain, looking for a node whose dominator set is
232 // equal to the current nodes, except that the current node does not exist
233 // in it. This means that it is one level higher in the dom chain than the
234 // current node, and it is our idom! We know that we have already added
235 // a DominatorTree node for our idom, because the idom must be a
236 // predecessor in the depth first order that we are iterating through the
239 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
240 DominatorSet::DomSetType::const_iterator End = Dominators.end();
241 for (; I != End; ++I) { // Iterate over dominators...
242 // All of our dominators should form a chain, where the number of
243 // elements in the dominator set indicates what level the node is at in
244 // the chain. We want the node immediately above us, so it will have
245 // an identical dominator set, except that BB will not dominate it...
246 // therefore it's dominator set size will be one less than BB's...
248 if (DS.getDominators(*I).size() == DomSetSize - 1) {
249 // We know that the immediate dominator should already have a node,
250 // because we are traversing the CFG in depth first order!
252 Node *IDomNode = Nodes[*I];
253 assert(IDomNode && "No node for IDOM?");
255 // Add a new tree node for this BasicBlock, and link it as a child of
257 Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
265 static std::ostream &operator<<(std::ostream &o,
266 const DominatorTreeBase::Node *Node) {
267 return o << Node->getNode()
268 << "\n------------------------------------------\n";
271 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
273 o << "Level #" << Lev << ": " << N;
274 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
276 PrintDomTree(*I, o, Lev+1);
280 void DominatorTreeBase::print(std::ostream &o) const {
281 o << "=============================--------------------------------\n"
282 << "Inorder Dominator Tree:\n";
283 PrintDomTree(Nodes.find(getRoot())->second, o, 1);
287 //===----------------------------------------------------------------------===//
288 // DominanceFrontier Implementation
289 //===----------------------------------------------------------------------===//
291 static RegisterAnalysis<DominanceFrontier>
292 G("domfrontier", "Dominance Frontier Construction", true);
294 const DominanceFrontier::DomSetType &
295 DominanceFrontier::calculate(const DominatorTree &DT,
296 const DominatorTree::Node *Node) {
297 // Loop over CFG successors to calculate DFlocal[Node]
298 BasicBlock *BB = Node->getNode();
299 DomSetType &S = Frontiers[BB]; // The new set to fill in...
301 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
303 // Does Node immediately dominate this successor?
304 if (DT[*SI]->getIDom() != Node)
308 // At this point, S is DFlocal. Now we union in DFup's of our children...
309 // Loop through and visit the nodes that Node immediately dominates (Node's
310 // children in the IDomTree)
312 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
314 DominatorTree::Node *IDominee = *NI;
315 const DomSetType &ChildDF = calculate(DT, IDominee);
317 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
318 for (; CDFI != CDFE; ++CDFI) {
319 if (!Node->dominates(DT[*CDFI]))
327 void DominanceFrontierBase::print(std::ostream &o) const {
328 for (const_iterator I = begin(), E = end(); I != E; ++I) {
329 o << "=============================--------------------------------\n"
330 << "\nDominance Frontier For Basic Block\n";
331 WriteAsOperand(o, I->first, false);
332 o << " is: \n" << I->second << "\n";