1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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/raw_ostream.h"
27 #include "llvm/Support/CommandLine.h"
31 // Always verify dominfo if expensive checking is enabled.
33 static bool VerifyDomInfo = true;
35 static bool VerifyDomInfo = false;
37 static cl::opt<bool,true>
38 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
39 cl::desc("Verify dominator info (time consuming)"));
41 //===----------------------------------------------------------------------===//
42 // DominatorTree Implementation
43 //===----------------------------------------------------------------------===//
45 // Provide public access to DominatorTree information. Implementation details
46 // can be found in DominatorCalculation.h.
48 //===----------------------------------------------------------------------===//
50 TEMPLATE_INSTANTIATION(class llvm::DomTreeNodeBase<BasicBlock>);
51 TEMPLATE_INSTANTIATION(class llvm::DominatorTreeBase<BasicBlock>);
53 char DominatorTree::ID = 0;
54 static RegisterPass<DominatorTree>
55 E("domtree", "Dominator Tree Construction", true, true);
57 bool DominatorTree::runOnFunction(Function &F) {
62 void DominatorTree::verifyAnalysis() const {
63 if (!VerifyDomInfo) return;
65 Function &F = *getRoot()->getParent();
67 DominatorTree OtherDT;
68 OtherDT.getBase().recalculate(F);
69 assert(!compare(OtherDT) && "Invalid DominatorTree info!");
72 void DominatorTree::print(raw_ostream &OS, const Module *) const {
76 // dominates - Return true if A dominates a use in B. This performs the
77 // special checks necessary if A and B are in the same basic block.
78 bool DominatorTree::dominates(const Instruction *A, const Instruction *B) const{
79 const BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
81 // If A is an invoke instruction, its value is only available in this normal
83 if (const InvokeInst *II = dyn_cast<InvokeInst>(A))
84 BBA = II->getNormalDest();
86 if (BBA != BBB) return dominates(BBA, BBB);
88 // It is not possible to determine dominance between two PHI nodes
89 // based on their ordering.
90 if (isa<PHINode>(A) && isa<PHINode>(B))
93 // Loop through the basic block until we find A or B.
94 BasicBlock::const_iterator I = BBA->begin();
95 for (; &*I != A && &*I != B; ++I)
103 //===----------------------------------------------------------------------===//
104 // DominanceFrontier Implementation
105 //===----------------------------------------------------------------------===//
107 char DominanceFrontier::ID = 0;
108 static RegisterPass<DominanceFrontier>
109 G("domfrontier", "Dominance Frontier Construction", true, true);
111 void DominanceFrontier::verifyAnalysis() const {
112 if (!VerifyDomInfo) return;
114 DominatorTree &DT = getAnalysis<DominatorTree>();
116 DominanceFrontier OtherDF;
117 const std::vector<BasicBlock*> &DTRoots = DT.getRoots();
118 OtherDF.calculate(DT, DT.getNode(DTRoots[0]));
119 assert(!compare(OtherDF) && "Invalid DominanceFrontier info!");
122 // NewBB is split and now it has one successor. Update dominance frontier to
123 // reflect this change.
124 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
125 assert(NewBB->getTerminator()->getNumSuccessors() == 1
126 && "NewBB should have a single successor!");
127 BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
129 SmallVector<BasicBlock*, 8> PredBlocks;
130 for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
132 PredBlocks.push_back(*PI);
134 if (PredBlocks.empty())
135 // If NewBB does not have any predecessors then it is a entry block.
136 // In this case, NewBB and its successor NewBBSucc dominates all
140 // NewBBSucc inherits original NewBB frontier.
141 DominanceFrontier::iterator NewBBI = find(NewBB);
142 if (NewBBI != end()) {
143 DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
144 DominanceFrontier::DomSetType NewBBSuccSet;
145 NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
146 addBasicBlock(NewBBSucc, NewBBSuccSet);
149 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
150 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
152 DominatorTree &DT = getAnalysis<DominatorTree>();
153 if (DT.dominates(NewBB, NewBBSucc)) {
154 DominanceFrontier::iterator DFI = find(PredBlocks[0]);
156 DominanceFrontier::DomSetType Set = DFI->second;
157 // Filter out stuff in Set that we do not dominate a predecessor of.
158 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
159 E = Set.end(); SetI != E;) {
160 bool DominatesPred = false;
161 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
163 if (DT.dominates(NewBB, *PI))
164 DominatesPred = true;
171 if (NewBBI != end()) {
172 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
173 E = Set.end(); SetI != E; ++SetI) {
174 BasicBlock *SB = *SetI;
175 addToFrontier(NewBBI, SB);
178 addBasicBlock(NewBB, Set);
182 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
183 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
184 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
185 DominanceFrontier::DomSetType NewDFSet;
186 NewDFSet.insert(NewBBSucc);
187 addBasicBlock(NewBB, NewDFSet);
190 // Now we must loop over all of the dominance frontiers in the function,
191 // replacing occurrences of NewBBSucc with NewBB in some cases. All
192 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
193 // their dominance frontier must be updated to contain NewBB instead.
195 for (Function::iterator FI = NewBB->getParent()->begin(),
196 FE = NewBB->getParent()->end(); FI != FE; ++FI) {
197 DominanceFrontier::iterator DFI = find(FI);
198 if (DFI == end()) continue; // unreachable block.
200 // Only consider nodes that have NewBBSucc in their dominator frontier.
201 if (!DFI->second.count(NewBBSucc)) continue;
203 // Verify whether this block dominates a block in predblocks. If not, do
205 bool BlockDominatesAny = false;
206 for (SmallVectorImpl<BasicBlock*>::const_iterator BI = PredBlocks.begin(),
207 BE = PredBlocks.end(); BI != BE; ++BI) {
208 if (DT.dominates(FI, *BI)) {
209 BlockDominatesAny = true;
214 // If NewBBSucc should not stay in our dominator frontier, remove it.
215 // We remove it unless there is a predecessor of NewBBSucc that we
216 // dominate, but we don't strictly dominate NewBBSucc.
217 bool ShouldRemove = true;
218 if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
219 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
220 // Check to see if it dominates any predecessors of NewBBSucc.
221 for (pred_iterator PI = pred_begin(NewBBSucc),
222 E = pred_end(NewBBSucc); PI != E; ++PI)
223 if (DT.dominates(FI, *PI)) {
224 ShouldRemove = false;
230 removeFromFrontier(DFI, NewBBSucc);
231 if (BlockDominatesAny && (&*FI == NewBB || !DT.dominates(FI, NewBB)))
232 addToFrontier(DFI, NewBB);
237 class DFCalculateWorkObject {
239 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
240 const DomTreeNode *N,
241 const DomTreeNode *PN)
242 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
243 BasicBlock *currentBB;
244 BasicBlock *parentBB;
245 const DomTreeNode *Node;
246 const DomTreeNode *parentNode;
250 const DominanceFrontier::DomSetType &
251 DominanceFrontier::calculate(const DominatorTree &DT,
252 const DomTreeNode *Node) {
253 BasicBlock *BB = Node->getBlock();
254 DomSetType *Result = NULL;
256 std::vector<DFCalculateWorkObject> workList;
257 SmallPtrSet<BasicBlock *, 32> visited;
259 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
261 DFCalculateWorkObject *currentW = &workList.back();
262 assert (currentW && "Missing work object.");
264 BasicBlock *currentBB = currentW->currentBB;
265 BasicBlock *parentBB = currentW->parentBB;
266 const DomTreeNode *currentNode = currentW->Node;
267 const DomTreeNode *parentNode = currentW->parentNode;
268 assert (currentBB && "Invalid work object. Missing current Basic Block");
269 assert (currentNode && "Invalid work object. Missing current Node");
270 DomSetType &S = Frontiers[currentBB];
272 // Visit each block only once.
273 if (visited.count(currentBB) == 0) {
274 visited.insert(currentBB);
276 // Loop over CFG successors to calculate DFlocal[currentNode]
277 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
279 // Does Node immediately dominate this successor?
280 if (DT[*SI]->getIDom() != currentNode)
285 // At this point, S is DFlocal. Now we union in DFup's of our children...
286 // Loop through and visit the nodes that Node immediately dominates (Node's
287 // children in the IDomTree)
288 bool visitChild = false;
289 for (DomTreeNode::const_iterator NI = currentNode->begin(),
290 NE = currentNode->end(); NI != NE; ++NI) {
291 DomTreeNode *IDominee = *NI;
292 BasicBlock *childBB = IDominee->getBlock();
293 if (visited.count(childBB) == 0) {
294 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
295 IDominee, currentNode));
300 // If all children are visited or there is any child then pop this block
301 // from the workList.
309 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
310 DomSetType &parentSet = Frontiers[parentBB];
311 for (; CDFI != CDFE; ++CDFI) {
312 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
313 parentSet.insert(*CDFI);
318 } while (!workList.empty());
323 void DominanceFrontierBase::print(raw_ostream &OS, const Module* ) const {
324 for (const_iterator I = begin(), E = end(); I != E; ++I) {
325 OS << " DomFrontier for BB ";
327 WriteAsOperand(OS, I->first, false);
329 OS << " <<exit node>>";
332 const std::set<BasicBlock*> &BBs = I->second;
334 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
338 WriteAsOperand(OS, *I, false);
340 OS << "<<exit node>>";