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);
66 WorkingSet.insert(BB); // A block always dominates itself
67 DomSetType &BBSet = Doms[BB];
68 if (BBSet != WorkingSet) {
69 BBSet.swap(WorkingSet); // Constant time operation!
70 Changed = true; // The sets changed.
72 WorkingSet.clear(); // Clear out the set for next iteration
79 // runOnFunction - This method calculates the forward dominator sets for the
80 // specified function.
82 bool DominatorSet::runOnFunction(Function &F) {
83 Doms.clear(); // Reset from the last time we were run...
84 Root = &F.getEntryNode();
85 assert(pred_begin(Root) == pred_end(Root) &&
86 "Root node has predecessors in function!");
88 // Calculate dominator sets for the reachable basic blocks...
89 calculateDominatorsFromBlock(Root);
91 // Every basic block in the function should at least dominate themselves, and
92 // thus every basic block should have an entry in Doms. The one case where we
93 // miss this is when a basic block is unreachable. To get these we now do an
94 // extra pass over the function, calculating dominator information for
95 // unreachable blocks.
97 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
98 if (Doms[I].empty()) {
99 calculateDominatorsFromBlock(I);
106 static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
107 for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
110 WriteAsOperand(o, *I, false);
116 void DominatorSetBase::print(std::ostream &o) const {
117 for (const_iterator I = begin(), E = end(); I != E; ++I)
118 o << "=============================--------------------------------\n"
119 << "\nDominator Set For Basic Block\n" << I->first
120 << "-------------------------------\n" << I->second << "\n";
123 //===----------------------------------------------------------------------===//
124 // ImmediateDominators Implementation
125 //===----------------------------------------------------------------------===//
127 static RegisterAnalysis<ImmediateDominators>
128 C("idom", "Immediate Dominators Construction", true);
130 // calcIDoms - Calculate the immediate dominator mapping, given a set of
131 // dominators for every basic block.
132 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
133 // Loop over all of the nodes that have dominators... figuring out the IDOM
136 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
138 BasicBlock *BB = DI->first;
139 const DominatorSet::DomSetType &Dominators = DI->second;
140 unsigned DomSetSize = Dominators.size();
141 if (DomSetSize == 1) continue; // Root node... IDom = null
143 // Loop over all dominators of this node. This corresponds to looping over
144 // nodes in the dominator chain, looking for a node whose dominator set is
145 // equal to the current nodes, except that the current node does not exist
146 // in it. This means that it is one level higher in the dom chain than the
147 // current node, and it is our idom!
149 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
150 DominatorSet::DomSetType::const_iterator End = Dominators.end();
151 for (; I != End; ++I) { // Iterate over dominators...
152 // All of our dominators should form a chain, where the number of elements
153 // in the dominator set indicates what level the node is at in the chain.
154 // We want the node immediately above us, so it will have an identical
155 // dominator set, except that BB will not dominate it... therefore it's
156 // dominator set size will be one less than BB's...
158 if (DS.getDominators(*I).size() == DomSetSize - 1) {
166 void ImmediateDominatorsBase::print(std::ostream &o) const {
167 for (const_iterator I = begin(), E = end(); I != E; ++I)
168 o << "=============================--------------------------------\n"
169 << "\nImmediate Dominator For Basic Block\n" << *I->first
170 << "is: \n" << *I->second << "\n";
174 //===----------------------------------------------------------------------===//
175 // DominatorTree Implementation
176 //===----------------------------------------------------------------------===//
178 static RegisterAnalysis<DominatorTree>
179 E("domtree", "Dominator Tree Construction", true);
181 // DominatorTreeBase::reset - Free all of the tree node memory.
183 void DominatorTreeBase::reset() {
184 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
190 void DominatorTree::calculate(const DominatorSet &DS) {
191 Nodes[Root] = new Node(Root, 0); // Add a node for the root...
193 // Iterate over all nodes in depth first order...
194 for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
197 const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
198 unsigned DomSetSize = Dominators.size();
199 if (DomSetSize == 1) continue; // Root node... IDom = null
201 // Loop over all dominators of this node. This corresponds to looping over
202 // nodes in the dominator chain, looking for a node whose dominator set is
203 // equal to the current nodes, except that the current node does not exist
204 // in it. This means that it is one level higher in the dom chain than the
205 // current node, and it is our idom! We know that we have already added
206 // a DominatorTree node for our idom, because the idom must be a
207 // predecessor in the depth first order that we are iterating through the
210 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
211 DominatorSet::DomSetType::const_iterator End = Dominators.end();
212 for (; I != End; ++I) { // Iterate over dominators...
213 // All of our dominators should form a chain, where the number of
214 // elements in the dominator set indicates what level the node is at in
215 // the chain. We want the node immediately above us, so it will have
216 // an identical dominator set, except that BB will not dominate it...
217 // therefore it's dominator set size will be one less than BB's...
219 if (DS.getDominators(*I).size() == DomSetSize - 1) {
220 // We know that the immediate dominator should already have a node,
221 // because we are traversing the CFG in depth first order!
223 Node *IDomNode = Nodes[*I];
224 assert(IDomNode && "No node for IDOM?");
226 // Add a new tree node for this BasicBlock, and link it as a child of
228 Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
236 static std::ostream &operator<<(std::ostream &o,
237 const DominatorTreeBase::Node *Node) {
238 return o << Node->getNode()
239 << "\n------------------------------------------\n";
242 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
244 o << "Level #" << Lev << ": " << N;
245 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
247 PrintDomTree(*I, o, Lev+1);
251 void DominatorTreeBase::print(std::ostream &o) const {
252 o << "=============================--------------------------------\n"
253 << "Inorder Dominator Tree:\n";
254 PrintDomTree(Nodes.find(getRoot())->second, o, 1);
258 //===----------------------------------------------------------------------===//
259 // DominanceFrontier Implementation
260 //===----------------------------------------------------------------------===//
262 static RegisterAnalysis<DominanceFrontier>
263 G("domfrontier", "Dominance Frontier Construction", true);
265 const DominanceFrontier::DomSetType &
266 DominanceFrontier::calculate(const DominatorTree &DT,
267 const DominatorTree::Node *Node) {
268 // Loop over CFG successors to calculate DFlocal[Node]
269 BasicBlock *BB = Node->getNode();
270 DomSetType &S = Frontiers[BB]; // The new set to fill in...
272 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
274 // Does Node immediately dominate this successor?
275 if (DT[*SI]->getIDom() != Node)
279 // At this point, S is DFlocal. Now we union in DFup's of our children...
280 // Loop through and visit the nodes that Node immediately dominates (Node's
281 // children in the IDomTree)
283 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
285 DominatorTree::Node *IDominee = *NI;
286 const DomSetType &ChildDF = calculate(DT, IDominee);
288 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
289 for (; CDFI != CDFE; ++CDFI) {
290 if (!Node->dominates(DT[*CDFI]))
298 void DominanceFrontierBase::print(std::ostream &o) const {
299 for (const_iterator I = begin(), E = end(); I != E; ++I) {
300 o << "=============================--------------------------------\n"
301 << "\nDominance Frontier For Basic Block\n";
302 WriteAsOperand(o, I->first, false);
303 o << " is: \n" << I->second << "\n";