PHI nodes are not allowed to exist with zero incoming values, check that
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9
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"
15 using std::set;
16
17 //===----------------------------------------------------------------------===//
18 //  DominatorSet Implementation
19 //===----------------------------------------------------------------------===//
20
21 static RegisterAnalysis<DominatorSet>
22 A("domset", "Dominator Set Construction", true);
23
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.
26 //
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);
30   
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*/;
34   
35   // A dominates B if it is found first in the basic block...
36   return &*I == A;
37 }
38
39
40 void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
41   bool Changed;
42   Doms[RootBB].insert(RootBB);  // Root always dominates itself...
43   do {
44     Changed = false;
45
46     DomSetType WorkingSet;
47     df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
48     for ( ; It != End; ++It) {
49       BasicBlock *BB = *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.
55         //
56         while (Doms[*PI].empty()) ++PI;
57         WorkingSet = Doms[*PI];
58
59         for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
60           DomSetType &PredSet = Doms[*PI];
61           if (PredSet.size())
62             set_intersect(WorkingSet, PredSet);
63         }
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
70         // entry node.
71         //
72         // This allows for dominator properties to be built for unreachable code
73         // in a reasonable manner.
74         //
75         WorkingSet = Doms[Root];
76       }
77         
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.
83       }
84       WorkingSet.clear();              // Clear out the set for next iteration
85     }
86   } while (Changed);
87 }
88
89
90
91 // runOnFunction - This method calculates the forward dominator sets for the
92 // specified function.
93 //
94 bool DominatorSet::runOnFunction(Function &F) {
95   Doms.clear();   // Reset from the last time we were run...
96   Root = &F.getEntryNode();
97   assert(pred_begin(Root) == pred_end(Root) &&
98          "Root node has predecessors in function!");
99
100   // Calculate dominator sets for the reachable basic blocks...
101   calculateDominatorsFromBlock(Root);
102
103   // Every basic block in the function should at least dominate themselves, and
104   // thus every basic block should have an entry in Doms.  The one case where we
105   // miss this is when a basic block is unreachable.  To get these we now do an
106   // extra pass over the function, calculating dominator information for
107   // unreachable blocks.
108   //
109   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
110     if (Doms[I].count(I) == 0)
111       calculateDominatorsFromBlock(I);
112
113   return false;
114 }
115
116
117 static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
118   for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
119        I != E; ++I) {
120     o << "  ";
121     WriteAsOperand(o, *I, false);
122     o << "\n";
123    }
124   return o;
125 }
126
127 void DominatorSetBase::print(std::ostream &o) const {
128   for (const_iterator I = begin(), E = end(); I != E; ++I) {
129     o << "=============================--------------------------------\n"
130       << "\nDominator Set For Basic Block: ";
131     WriteAsOperand(o, I->first, false);
132     o  << "\n-------------------------------\n" << I->second << "\n";
133   }
134 }
135
136 //===----------------------------------------------------------------------===//
137 //  ImmediateDominators Implementation
138 //===----------------------------------------------------------------------===//
139
140 static RegisterAnalysis<ImmediateDominators>
141 C("idom", "Immediate Dominators Construction", true);
142
143 // calcIDoms - Calculate the immediate dominator mapping, given a set of
144 // dominators for every basic block.
145 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
146   // Loop over all of the nodes that have dominators... figuring out the IDOM
147   // for each node...
148   //
149   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end(); 
150        DI != DEnd; ++DI) {
151     BasicBlock *BB = DI->first;
152     const DominatorSet::DomSetType &Dominators = DI->second;
153     unsigned DomSetSize = Dominators.size();
154     if (DomSetSize == 1) continue;  // Root node... IDom = null
155
156     // Loop over all dominators of this node.  This corresponds to looping over
157     // nodes in the dominator chain, looking for a node whose dominator set is
158     // equal to the current nodes, except that the current node does not exist
159     // in it.  This means that it is one level higher in the dom chain than the
160     // current node, and it is our idom!
161     //
162     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
163     DominatorSet::DomSetType::const_iterator End = Dominators.end();
164     for (; I != End; ++I) {   // Iterate over dominators...
165       // All of our dominators should form a chain, where the number of elements
166       // in the dominator set indicates what level the node is at in the chain.
167       // We want the node immediately above us, so it will have an identical 
168       // dominator set, except that BB will not dominate it... therefore it's
169       // dominator set size will be one less than BB's...
170       //
171       if (DS.getDominators(*I).size() == DomSetSize - 1) {
172         IDoms[BB] = *I;
173         break;
174       }
175     }
176   }
177 }
178
179 void ImmediateDominatorsBase::print(std::ostream &o) const {
180   for (const_iterator I = begin(), E = end(); I != E; ++I) {
181     o << "=============================--------------------------------\n"
182       << "\nImmediate Dominator For Basic Block:";
183     WriteAsOperand(o, I->first, false);
184     o << " is:";
185     WriteAsOperand(o, I->second, false);
186     o << "\n";
187   }
188 }
189
190
191 //===----------------------------------------------------------------------===//
192 //  DominatorTree Implementation
193 //===----------------------------------------------------------------------===//
194
195 static RegisterAnalysis<DominatorTree>
196 E("domtree", "Dominator Tree Construction", true);
197
198 // DominatorTreeBase::reset - Free all of the tree node memory.
199 //
200 void DominatorTreeBase::reset() { 
201   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
202     delete I->second;
203   Nodes.clear();
204 }
205
206 void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
207   assert(IDom && "No immediate dominator?");
208   if (IDom != NewIDom) {
209     std::vector<Node*>::iterator I =
210       std::find(IDom->Children.begin(), IDom->Children.end(), this);
211     assert(I != IDom->Children.end() &&
212            "Not in immediate dominator children set!");
213     // I am no longer your child...
214     IDom->Children.erase(I);
215
216     // Switch to new dominator
217     IDom = NewIDom;
218     IDom->Children.push_back(this);
219   }
220 }
221
222
223
224 void DominatorTree::calculate(const DominatorSet &DS) {
225   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
226
227   // Iterate over all nodes in depth first order...
228   for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
229        I != E; ++I) {
230     BasicBlock *BB = *I;
231     const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
232     unsigned DomSetSize = Dominators.size();
233     if (DomSetSize == 1) continue;  // Root node... IDom = null
234       
235     // Loop over all dominators of this node. This corresponds to looping over
236     // nodes in the dominator chain, looking for a node whose dominator set is
237     // equal to the current nodes, except that the current node does not exist
238     // in it. This means that it is one level higher in the dom chain than the
239     // current node, and it is our idom!  We know that we have already added
240     // a DominatorTree node for our idom, because the idom must be a
241     // predecessor in the depth first order that we are iterating through the
242     // function.
243     //
244     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
245     DominatorSet::DomSetType::const_iterator End = Dominators.end();
246     for (; I != End; ++I) {   // Iterate over dominators...
247       // All of our dominators should form a chain, where the number of
248       // elements in the dominator set indicates what level the node is at in
249       // the chain.  We want the node immediately above us, so it will have
250       // an identical dominator set, except that BB will not dominate it...
251       // therefore it's dominator set size will be one less than BB's...
252       //
253       if (DS.getDominators(*I).size() == DomSetSize - 1) {
254         // We know that the immediate dominator should already have a node, 
255         // because we are traversing the CFG in depth first order!
256         //
257         Node *IDomNode = Nodes[*I];
258         assert(IDomNode && "No node for IDOM?");
259         
260         // Add a new tree node for this BasicBlock, and link it as a child of
261         // IDomNode
262         Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
263         break;
264       }
265     }
266   }
267 }
268
269
270 static std::ostream &operator<<(std::ostream &o,
271                                 const DominatorTreeBase::Node *Node) {
272   return o << Node->getNode()
273            << "\n------------------------------------------\n";
274 }
275
276 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
277                          unsigned Lev) {
278   o << "Level #" << Lev << ":  " << N;
279   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
280        I != E; ++I) {
281     PrintDomTree(*I, o, Lev+1);
282   }
283 }
284
285 void DominatorTreeBase::print(std::ostream &o) const {
286   o << "=============================--------------------------------\n"
287     << "Inorder Dominator Tree:\n";
288   PrintDomTree(Nodes.find(getRoot())->second, o, 1);
289 }
290
291
292 //===----------------------------------------------------------------------===//
293 //  DominanceFrontier Implementation
294 //===----------------------------------------------------------------------===//
295
296 static RegisterAnalysis<DominanceFrontier>
297 G("domfrontier", "Dominance Frontier Construction", true);
298
299 const DominanceFrontier::DomSetType &
300 DominanceFrontier::calculate(const DominatorTree &DT, 
301                              const DominatorTree::Node *Node) {
302   // Loop over CFG successors to calculate DFlocal[Node]
303   BasicBlock *BB = Node->getNode();
304   DomSetType &S = Frontiers[BB];       // The new set to fill in...
305
306   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
307        SI != SE; ++SI) {
308     // Does Node immediately dominate this successor?
309     if (DT[*SI]->getIDom() != Node)
310       S.insert(*SI);
311   }
312
313   // At this point, S is DFlocal.  Now we union in DFup's of our children...
314   // Loop through and visit the nodes that Node immediately dominates (Node's
315   // children in the IDomTree)
316   //
317   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
318        NI != NE; ++NI) {
319     DominatorTree::Node *IDominee = *NI;
320     const DomSetType &ChildDF = calculate(DT, IDominee);
321
322     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
323     for (; CDFI != CDFE; ++CDFI) {
324       if (!Node->dominates(DT[*CDFI]))
325         S.insert(*CDFI);
326     }
327   }
328
329   return S;
330 }
331
332 void DominanceFrontierBase::print(std::ostream &o) const {
333   for (const_iterator I = begin(), E = end(); I != E; ++I) {
334     o << "=============================--------------------------------\n"
335       << "\nDominance Frontier For Basic Block\n";
336     WriteAsOperand(o, I->first, false);
337     o << " is: \n" << I->second << "\n";
338   }
339 }