rearrange some code, simplify handling of shifts.
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements simple dominator construction algorithms for finding
11 // forward dominators.  Postdominators are available in libanalysis, but are not
12 // included in libvmcore, because it's not needed.  Forward dominators are
13 // needed to support the Verifier pass.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "domtree"
18
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Support/CFG.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/SetOperations.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Analysis/DominatorInternals.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Support/Streams.h"
30 #include <algorithm>
31 using namespace llvm;
32
33 namespace llvm {
34 static std::ostream &operator<<(std::ostream &o,
35                                 const std::set<BasicBlock*> &BBs) {
36   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
37        I != E; ++I)
38     if (*I)
39       WriteAsOperand(o, *I, false);
40     else
41       o << " <<exit node>>";
42   return o;
43 }
44 }
45
46 //===----------------------------------------------------------------------===//
47 //  DominatorTree Implementation
48 //===----------------------------------------------------------------------===//
49 //
50 // Provide public access to DominatorTree information.  Implementation details
51 // can be found in DominatorCalculation.h.
52 //
53 //===----------------------------------------------------------------------===//
54
55 TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
56 TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
57
58 char DominatorTree::ID = 0;
59 static RegisterPass<DominatorTree>
60 E("domtree", "Dominator Tree Construction", true, true);
61
62 bool DominatorTree::runOnFunction(Function &F) {
63   DT->recalculate(F);
64   DEBUG(DT->dump());
65   return false;
66 }
67
68 //===----------------------------------------------------------------------===//
69 //  DominanceFrontier Implementation
70 //===----------------------------------------------------------------------===//
71
72 char DominanceFrontier::ID = 0;
73 static RegisterPass<DominanceFrontier>
74 G("domfrontier", "Dominance Frontier Construction", false, true);
75
76 // NewBB is split and now it has one successor. Update dominace frontier to
77 // reflect this change.
78 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
79   assert(NewBB->getTerminator()->getNumSuccessors() == 1
80          && "NewBB should have a single successor!");
81   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
82
83   std::vector<BasicBlock*> PredBlocks;
84   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
85        PI != PE; ++PI)
86       PredBlocks.push_back(*PI);  
87
88   if (PredBlocks.empty())
89     // If NewBB does not have any predecessors then it is a entry block.
90     // In this case, NewBB and its successor NewBBSucc dominates all
91     // other blocks.
92     return;
93
94   // NewBBSucc inherits original NewBB frontier.
95   DominanceFrontier::iterator NewBBI = find(NewBB);
96   if (NewBBI != end()) {
97     DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
98     DominanceFrontier::DomSetType NewBBSuccSet;
99     NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
100     addBasicBlock(NewBBSucc, NewBBSuccSet);
101   }
102
103   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
104   // DF(PredBlocks[0]) without the stuff that the new block does not dominate
105   // a predecessor of.
106   DominatorTree &DT = getAnalysis<DominatorTree>();
107   if (DT.dominates(NewBB, NewBBSucc)) {
108     DominanceFrontier::iterator DFI = find(PredBlocks[0]);
109     if (DFI != end()) {
110       DominanceFrontier::DomSetType Set = DFI->second;
111       // Filter out stuff in Set that we do not dominate a predecessor of.
112       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
113              E = Set.end(); SetI != E;) {
114         bool DominatesPred = false;
115         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
116              PI != E; ++PI)
117           if (DT.dominates(NewBB, *PI))
118             DominatesPred = true;
119         if (!DominatesPred)
120           Set.erase(SetI++);
121         else
122           ++SetI;
123       }
124
125       if (NewBBI != end()) {
126         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
127                E = Set.end(); SetI != E; ++SetI) {
128           BasicBlock *SB = *SetI;
129           addToFrontier(NewBBI, SB);
130         }
131       } else 
132         addBasicBlock(NewBB, Set);
133     }
134     
135   } else {
136     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
137     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
138     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
139     DominanceFrontier::DomSetType NewDFSet;
140     NewDFSet.insert(NewBBSucc);
141     addBasicBlock(NewBB, NewDFSet);
142   }
143   
144   // Now we must loop over all of the dominance frontiers in the function,
145   // replacing occurrences of NewBBSucc with NewBB in some cases.  All
146   // blocks that dominate a block in PredBlocks and contained NewBBSucc in
147   // their dominance frontier must be updated to contain NewBB instead.
148   //
149   for (Function::iterator FI = NewBB->getParent()->begin(),
150          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
151     DominanceFrontier::iterator DFI = find(FI);
152     if (DFI == end()) continue;  // unreachable block.
153     
154     // Only consider nodes that have NewBBSucc in their dominator frontier.
155     if (!DFI->second.count(NewBBSucc)) continue;
156
157     // Verify whether this block dominates a block in predblocks.  If not, do
158     // not update it.
159     bool BlockDominatesAny = false;
160     for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(), 
161            BE = PredBlocks.end(); BI != BE; ++BI) {
162       if (DT.dominates(FI, *BI)) {
163         BlockDominatesAny = true;
164         break;
165       }
166     }
167     
168     if (!BlockDominatesAny)
169       continue;
170     
171     // If NewBBSucc should not stay in our dominator frontier, remove it.
172     // We remove it unless there is a predecessor of NewBBSucc that we
173     // dominate, but we don't strictly dominate NewBBSucc.
174     bool ShouldRemove = true;
175     if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
176       // Okay, we know that PredDom does not strictly dominate NewBBSucc.
177       // Check to see if it dominates any predecessors of NewBBSucc.
178       for (pred_iterator PI = pred_begin(NewBBSucc),
179            E = pred_end(NewBBSucc); PI != E; ++PI)
180         if (DT.dominates(FI, *PI)) {
181           ShouldRemove = false;
182           break;
183         }
184     }
185     
186     if (ShouldRemove)
187       removeFromFrontier(DFI, NewBBSucc);
188     addToFrontier(DFI, NewBB);
189   }
190 }
191
192 namespace {
193   class DFCalculateWorkObject {
194   public:
195     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
196                           const DomTreeNode *N,
197                           const DomTreeNode *PN)
198     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
199     BasicBlock *currentBB;
200     BasicBlock *parentBB;
201     const DomTreeNode *Node;
202     const DomTreeNode *parentNode;
203   };
204 }
205
206 const DominanceFrontier::DomSetType &
207 DominanceFrontier::calculate(const DominatorTree &DT,
208                              const DomTreeNode *Node) {
209   BasicBlock *BB = Node->getBlock();
210   DomSetType *Result = NULL;
211
212   std::vector<DFCalculateWorkObject> workList;
213   SmallPtrSet<BasicBlock *, 32> visited;
214
215   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
216   do {
217     DFCalculateWorkObject *currentW = &workList.back();
218     assert (currentW && "Missing work object.");
219
220     BasicBlock *currentBB = currentW->currentBB;
221     BasicBlock *parentBB = currentW->parentBB;
222     const DomTreeNode *currentNode = currentW->Node;
223     const DomTreeNode *parentNode = currentW->parentNode;
224     assert (currentBB && "Invalid work object. Missing current Basic Block");
225     assert (currentNode && "Invalid work object. Missing current Node");
226     DomSetType &S = Frontiers[currentBB];
227
228     // Visit each block only once.
229     if (visited.count(currentBB) == 0) {
230       visited.insert(currentBB);
231
232       // Loop over CFG successors to calculate DFlocal[currentNode]
233       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
234            SI != SE; ++SI) {
235         // Does Node immediately dominate this successor?
236         if (DT[*SI]->getIDom() != currentNode)
237           S.insert(*SI);
238       }
239     }
240
241     // At this point, S is DFlocal.  Now we union in DFup's of our children...
242     // Loop through and visit the nodes that Node immediately dominates (Node's
243     // children in the IDomTree)
244     bool visitChild = false;
245     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
246            NE = currentNode->end(); NI != NE; ++NI) {
247       DomTreeNode *IDominee = *NI;
248       BasicBlock *childBB = IDominee->getBlock();
249       if (visited.count(childBB) == 0) {
250         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
251                                                  IDominee, currentNode));
252         visitChild = true;
253       }
254     }
255
256     // If all children are visited or there is any child then pop this block
257     // from the workList.
258     if (!visitChild) {
259
260       if (!parentBB) {
261         Result = &S;
262         break;
263       }
264
265       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
266       DomSetType &parentSet = Frontiers[parentBB];
267       for (; CDFI != CDFE; ++CDFI) {
268         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
269           parentSet.insert(*CDFI);
270       }
271       workList.pop_back();
272     }
273
274   } while (!workList.empty());
275
276   return *Result;
277 }
278
279 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
280   for (const_iterator I = begin(), E = end(); I != E; ++I) {
281     o << "  DomFrontier for BB";
282     if (I->first)
283       WriteAsOperand(o, I->first, false);
284     else
285       o << " <<exit node>>";
286     o << " is:\t" << I->second << "\n";
287   }
288 }
289
290 void DominanceFrontierBase::dump() {
291   print (llvm::cerr);
292 }