Remove support for NOT instruction
[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 AnalysisID DominatorSet::ID = A;
24
25 // dominates - Return true if A dominates B.  This performs the special checks
26 // neccesary if A and B are in the same basic block.
27 //
28 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
29   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
30   if (BBA != BBB) return dominates(BBA, BBB);
31   
32   // Loop through the basic block until we find A or B.
33   BasicBlock::iterator I = BBA->begin();
34   for (; &*I != A && &*I != B; ++I) /*empty*/;
35   
36   // A dominates B if it is found first in the basic block...
37   return &*I == A;
38 }
39
40 // runOnFunction - This method calculates the forward dominator sets for the
41 // specified function.
42 //
43 bool DominatorSet::runOnFunction(Function &F) {
44   Doms.clear();   // Reset from the last time we were run...
45   Root = &F.getEntryNode();
46   assert(pred_begin(Root) == pred_end(Root) &&
47          "Root node has predecessors in function!");
48
49   bool Changed;
50   do {
51     Changed = false;
52
53     DomSetType WorkingSet;
54     df_iterator<Function*> It = df_begin(&F), End = df_end(&F);
55     for ( ; It != End; ++It) {
56       BasicBlock *BB = *It;
57       pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
58       if (PI != PEnd) {                // Is there SOME predecessor?
59         // Loop until we get to a predecessor that has had it's dom set filled
60         // in at least once.  We are guaranteed to have this because we are
61         // traversing the graph in DFO and have handled start nodes specially.
62         //
63         while (Doms[*PI].empty()) ++PI;
64         WorkingSet = Doms[*PI];
65
66         for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
67           DomSetType &PredSet = Doms[*PI];
68           if (PredSet.size())
69             set_intersect(WorkingSet, PredSet);
70         }
71       }
72         
73       WorkingSet.insert(BB);           // A block always dominates itself
74       DomSetType &BBSet = Doms[BB];
75       if (BBSet != WorkingSet) {
76         BBSet.swap(WorkingSet);        // Constant time operation!
77         Changed = true;                // The sets changed.
78       }
79       WorkingSet.clear();              // Clear out the set for next iteration
80     }
81   } while (Changed);
82
83   // Every basic block in the function should at least dominate themselves, and
84   // thus every basic block should have an entry in Doms.  The one case where we
85   // miss this is when a basic block is unreachable.  To get these we now do an
86   // extra pass adding self dominance info to the DomSet if the block doesn't
87   // already have an entry.
88   //
89   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
90     if (Doms[I].empty())
91       Doms[I].insert(I);
92
93   return false;
94 }
95
96
97 static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
98   for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
99        I != E; ++I) {
100     o << "  ";
101     WriteAsOperand(o, *I, false);
102     o << "\n";
103    }
104   return o;
105 }
106
107 void DominatorSetBase::print(std::ostream &o) const {
108   for (const_iterator I = begin(), E = end(); I != E; ++I)
109     o << "=============================--------------------------------\n"
110       << "\nDominator Set For Basic Block\n" << I->first
111       << "-------------------------------\n" << I->second << "\n";
112 }
113
114 //===----------------------------------------------------------------------===//
115 //  ImmediateDominators Implementation
116 //===----------------------------------------------------------------------===//
117
118 static RegisterAnalysis<ImmediateDominators>
119 C("idom", "Immediate Dominators Construction", true);
120 AnalysisID ImmediateDominators::ID = C;
121
122 // calcIDoms - Calculate the immediate dominator mapping, given a set of
123 // dominators for every basic block.
124 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
125   // Loop over all of the nodes that have dominators... figuring out the IDOM
126   // for each node...
127   //
128   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end(); 
129        DI != DEnd; ++DI) {
130     BasicBlock *BB = DI->first;
131     const DominatorSet::DomSetType &Dominators = DI->second;
132     unsigned DomSetSize = Dominators.size();
133     if (DomSetSize == 1) continue;  // Root node... IDom = null
134
135     // Loop over all dominators of this node.  This corresponds to looping over
136     // nodes in the dominator chain, looking for a node whose dominator set is
137     // equal to the current nodes, except that the current node does not exist
138     // in it.  This means that it is one level higher in the dom chain than the
139     // current node, and it is our idom!
140     //
141     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
142     DominatorSet::DomSetType::const_iterator End = Dominators.end();
143     for (; I != End; ++I) {   // Iterate over dominators...
144       // All of our dominators should form a chain, where the number of elements
145       // in the dominator set indicates what level the node is at in the chain.
146       // We want the node immediately above us, so it will have an identical 
147       // dominator set, except that BB will not dominate it... therefore it's
148       // dominator set size will be one less than BB's...
149       //
150       if (DS.getDominators(*I).size() == DomSetSize - 1) {
151         IDoms[BB] = *I;
152         break;
153       }
154     }
155   }
156 }
157
158 void ImmediateDominatorsBase::print(std::ostream &o) const {
159   for (const_iterator I = begin(), E = end(); I != E; ++I)
160     o << "=============================--------------------------------\n"
161       << "\nImmediate Dominator For Basic Block\n" << *I->first
162       << "is: \n" << *I->second << "\n";
163 }
164
165
166 //===----------------------------------------------------------------------===//
167 //  DominatorTree Implementation
168 //===----------------------------------------------------------------------===//
169
170 static RegisterAnalysis<DominatorTree>
171 E("domtree", "Dominator Tree Construction", true);
172 AnalysisID DominatorTree::ID = E;
173
174 // DominatorTreeBase::reset - Free all of the tree node memory.
175 //
176 void DominatorTreeBase::reset() { 
177   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
178     delete I->second;
179   Nodes.clear();
180 }
181
182
183 void DominatorTree::calculate(const DominatorSet &DS) {
184   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
185
186   // Iterate over all nodes in depth first order...
187   for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
188        I != E; ++I) {
189     BasicBlock *BB = *I;
190     const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
191     unsigned DomSetSize = Dominators.size();
192     if (DomSetSize == 1) continue;  // Root node... IDom = null
193       
194     // Loop over all dominators of this node. This corresponds to looping over
195     // nodes in the dominator chain, looking for a node whose dominator set is
196     // equal to the current nodes, except that the current node does not exist
197     // in it. This means that it is one level higher in the dom chain than the
198     // current node, and it is our idom!  We know that we have already added
199     // a DominatorTree node for our idom, because the idom must be a
200     // predecessor in the depth first order that we are iterating through the
201     // function.
202     //
203     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
204     DominatorSet::DomSetType::const_iterator End = Dominators.end();
205     for (; I != End; ++I) {   // Iterate over dominators...
206       // All of our dominators should form a chain, where the number of
207       // elements in the dominator set indicates what level the node is at in
208       // the chain.  We want the node immediately above us, so it will have
209       // an identical dominator set, except that BB will not dominate it...
210       // therefore it's dominator set size will be one less than BB's...
211       //
212       if (DS.getDominators(*I).size() == DomSetSize - 1) {
213         // We know that the immediate dominator should already have a node, 
214         // because we are traversing the CFG in depth first order!
215         //
216         Node *IDomNode = Nodes[*I];
217         assert(IDomNode && "No node for IDOM?");
218         
219         // Add a new tree node for this BasicBlock, and link it as a child of
220         // IDomNode
221         Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
222         break;
223       }
224     }
225   }
226 }
227
228
229 static std::ostream &operator<<(std::ostream &o,
230                                 const DominatorTreeBase::Node *Node) {
231   return o << Node->getNode()
232            << "\n------------------------------------------\n";
233 }
234
235 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
236                          unsigned Lev) {
237   o << "Level #" << Lev << ":  " << N;
238   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
239        I != E; ++I) {
240     PrintDomTree(*I, o, Lev+1);
241   }
242 }
243
244 void DominatorTreeBase::print(std::ostream &o) const {
245   o << "=============================--------------------------------\n"
246     << "Inorder Dominator Tree:\n";
247   PrintDomTree(Nodes.find(getRoot())->second, o, 1);
248 }
249
250
251 //===----------------------------------------------------------------------===//
252 //  DominanceFrontier Implementation
253 //===----------------------------------------------------------------------===//
254
255 static RegisterAnalysis<DominanceFrontier>
256 G("domfrontier", "Dominance Frontier Construction", true);
257 AnalysisID DominanceFrontier::ID = G;
258
259 const DominanceFrontier::DomSetType &
260 DominanceFrontier::calculate(const DominatorTree &DT, 
261                              const DominatorTree::Node *Node) {
262   // Loop over CFG successors to calculate DFlocal[Node]
263   BasicBlock *BB = Node->getNode();
264   DomSetType &S = Frontiers[BB];       // The new set to fill in...
265
266   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
267        SI != SE; ++SI) {
268     // Does Node immediately dominate this successor?
269     if (DT[*SI]->getIDom() != Node)
270       S.insert(*SI);
271   }
272
273   // At this point, S is DFlocal.  Now we union in DFup's of our children...
274   // Loop through and visit the nodes that Node immediately dominates (Node's
275   // children in the IDomTree)
276   //
277   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
278        NI != NE; ++NI) {
279     DominatorTree::Node *IDominee = *NI;
280     const DomSetType &ChildDF = calculate(DT, IDominee);
281
282     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
283     for (; CDFI != CDFE; ++CDFI) {
284       if (!Node->dominates(DT[*CDFI]))
285         S.insert(*CDFI);
286     }
287   }
288
289   return S;
290 }
291
292 void DominanceFrontierBase::print(std::ostream &o) const {
293   for (const_iterator I = begin(), E = end(); I != E; ++I) {
294     o << "=============================--------------------------------\n"
295       << "\nDominance Frontier For Basic Block\n";
296     WriteAsOperand(o, I->first, false);
297     o << " is: \n" << I->second << "\n";
298   }
299 }