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