1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
3 // The LLVM Compiler Infrastructure
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.
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/Assembly/Writer.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/Instructions.h"
25 #include "llvm/Support/Streams.h"
26 #include "DominatorCalculation.h"
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();
36 WriteAsOperand(o, *I, false);
38 o << " <<exit node>>";
43 //===----------------------------------------------------------------------===//
44 // DominatorTree Implementation
45 //===----------------------------------------------------------------------===//
47 // Provide public access to DominatorTree information. Implementation details
48 // can be found in DominatorCalculation.h.
50 //===----------------------------------------------------------------------===//
52 char DominatorTree::ID = 0;
53 static RegisterPass<DominatorTree>
54 E("domtree", "Dominator Tree Construction", true);
56 unsigned DominatorTreeBase::DFSPass(BasicBlock *V, unsigned N) {
57 // This is more understandable as a recursive algorithm, but we can't use the
58 // recursive algorithm due to stack depth issues. Keep it here for
59 // documentation purposes.
61 InfoRec &VInfo = Info[Roots[i]];
65 Vertex.push_back(V); // Vertex[n] = V;
66 //Info[V].Ancestor = 0; // Ancestor[n] = 0
67 //Info[V].Child = 0; // Child[v] = 0
68 VInfo.Size = 1; // Size[v] = 1
70 for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
71 InfoRec &SuccVInfo = Info[*SI];
72 if (SuccVInfo.Semi == 0) {
78 std::vector<std::pair<BasicBlock*, unsigned> > Worklist;
79 Worklist.push_back(std::make_pair(V, 0U));
80 while (!Worklist.empty()) {
81 BasicBlock *BB = Worklist.back().first;
82 unsigned NextSucc = Worklist.back().second;
84 // First time we visited this BB?
86 InfoRec &BBInfo = Info[BB];
90 Vertex.push_back(BB); // Vertex[n] = V;
91 //BBInfo[V].Ancestor = 0; // Ancestor[n] = 0
92 //BBInfo[V].Child = 0; // Child[v] = 0
93 BBInfo.Size = 1; // Size[v] = 1
96 // If we are done with this block, remove it from the worklist.
97 if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
102 // Otherwise, increment the successor number for the next time we get to it.
103 ++Worklist.back().second;
105 // Visit the successor next, if it isn't already visited.
106 BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
108 InfoRec &SuccVInfo = Info[Succ];
109 if (SuccVInfo.Semi == 0) {
110 SuccVInfo.Parent = BB;
111 Worklist.push_back(std::make_pair(Succ, 0U));
118 // NewBB is split and now it has one successor. Update dominator tree to
119 // reflect this change.
120 void DominatorTree::splitBlock(BasicBlock *NewBB) {
121 assert(NewBB->getTerminator()->getNumSuccessors() == 1
122 && "NewBB should have a single successor!");
123 BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
125 std::vector<BasicBlock*> PredBlocks;
126 for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
128 PredBlocks.push_back(*PI);
130 assert(!PredBlocks.empty() && "No predblocks??");
132 // The newly inserted basic block will dominate existing basic blocks iff the
133 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
134 // the non-pred blocks, then they all must be the same block!
136 bool NewBBDominatesNewBBSucc = true;
138 BasicBlock *OnePred = PredBlocks[0];
139 unsigned i = 1, e = PredBlocks.size();
140 for (i = 1; !isReachableFromEntry(OnePred); ++i) {
141 assert(i != e && "Didn't find reachable pred?");
142 OnePred = PredBlocks[i];
146 if (PredBlocks[i] != OnePred && isReachableFromEntry(OnePred)) {
147 NewBBDominatesNewBBSucc = false;
151 if (NewBBDominatesNewBBSucc)
152 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
154 if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
155 NewBBDominatesNewBBSucc = false;
160 // The other scenario where the new block can dominate its successors are when
161 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
163 if (!NewBBDominatesNewBBSucc) {
164 NewBBDominatesNewBBSucc = true;
165 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
167 if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
168 NewBBDominatesNewBBSucc = false;
173 // Find NewBB's immediate dominator and create new dominator tree node for
175 BasicBlock *NewBBIDom = 0;
177 for (i = 0; i < PredBlocks.size(); ++i)
178 if (isReachableFromEntry(PredBlocks[i])) {
179 NewBBIDom = PredBlocks[i];
182 assert(i != PredBlocks.size() && "No reachable preds?");
183 for (i = i + 1; i < PredBlocks.size(); ++i) {
184 if (isReachableFromEntry(PredBlocks[i]))
185 NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
187 assert(NewBBIDom && "No immediate dominator found??");
189 // Create the new dominator tree node... and set the idom of NewBB.
190 DomTreeNode *NewBBNode = addNewBlock(NewBB, NewBBIDom);
192 // If NewBB strictly dominates other blocks, then it is now the immediate
193 // dominator of NewBBSucc. Update the dominator tree as appropriate.
194 if (NewBBDominatesNewBBSucc) {
195 DomTreeNode *NewBBSuccNode = getNode(NewBBSucc);
196 changeImmediateDominator(NewBBSuccNode, NewBBNode);
200 void DominatorTreeBase::updateDFSNumbers() {
203 SmallVector<std::pair<DomTreeNode*, DomTreeNode::iterator>, 32> WorkStack;
205 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
206 DomTreeNode *ThisRoot = getNode(Roots[i]);
207 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
208 ThisRoot->DFSNumIn = DFSNum++;
210 while (!WorkStack.empty()) {
211 DomTreeNode *Node = WorkStack.back().first;
212 DomTreeNode::iterator ChildIt = WorkStack.back().second;
214 // If we visited all of the children of this node, "recurse" back up the
215 // stack setting the DFOutNum.
216 if (ChildIt == Node->end()) {
217 Node->DFSNumOut = DFSNum++;
218 WorkStack.pop_back();
220 // Otherwise, recursively visit this child.
221 DomTreeNode *Child = *ChildIt;
222 ++WorkStack.back().second;
224 WorkStack.push_back(std::make_pair(Child, Child->begin()));
225 Child->DFSNumIn = DFSNum++;
234 /// isReachableFromEntry - Return true if A is dominated by the entry
235 /// block of the function containing it.
236 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
237 assert (!isPostDominator()
238 && "This is not implemented for post dominators");
239 return dominates(&A->getParent()->getEntryBlock(), A);
242 // dominates - Return true if A dominates B. THis performs the
243 // special checks necessary if A and B are in the same basic block.
244 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
245 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
246 if (BBA != BBB) return dominates(BBA, BBB);
248 // It is not possible to determine dominance between two PHI nodes
249 // based on their ordering.
250 if (isa<PHINode>(A) && isa<PHINode>(B))
253 // Loop through the basic block until we find A or B.
254 BasicBlock::iterator I = BBA->begin();
255 for (; &*I != A && &*I != B; ++I) /*empty*/;
257 if(!IsPostDominators) {
258 // A dominates B if it is found first in the basic block.
261 // A post-dominates B if B is found first in the basic block.
266 // DominatorTreeBase::reset - Free all of the tree node memory.
268 void DominatorTreeBase::reset() {
269 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(),
270 E = DomTreeNodes.end(); I != E; ++I)
272 DomTreeNodes.clear();
279 DomTreeNode *DominatorTreeBase::getNodeForBlock(BasicBlock *BB) {
280 if (DomTreeNode *BBNode = DomTreeNodes[BB])
283 // Haven't calculated this node yet? Get or calculate the node for the
284 // immediate dominator.
285 BasicBlock *IDom = getIDom(BB);
286 DomTreeNode *IDomNode = getNodeForBlock(IDom);
288 // Add a new tree node for this BasicBlock, and link it as a child of
290 DomTreeNode *C = new DomTreeNode(BB, IDomNode);
291 return DomTreeNodes[BB] = IDomNode->addChild(C);
294 /// findNearestCommonDominator - Find nearest common dominator basic block
295 /// for basic block A and B. If there is no such block then return NULL.
296 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A,
299 assert (!isPostDominator()
300 && "This is not implemented for post dominators");
301 assert (A->getParent() == B->getParent()
302 && "Two blocks are not in same function");
304 // If either A or B is a entry block then it is nearest common dominator.
305 BasicBlock &Entry = A->getParent()->getEntryBlock();
306 if (A == &Entry || B == &Entry)
309 // If B dominates A then B is nearest common dominator.
313 // If A dominates B then A is nearest common dominator.
317 DomTreeNode *NodeA = getNode(A);
318 DomTreeNode *NodeB = getNode(B);
320 // Collect NodeA dominators set.
321 SmallPtrSet<DomTreeNode*, 16> NodeADoms;
322 NodeADoms.insert(NodeA);
323 DomTreeNode *IDomA = NodeA->getIDom();
325 NodeADoms.insert(IDomA);
326 IDomA = IDomA->getIDom();
329 // Walk NodeB immediate dominators chain and find common dominator node.
330 DomTreeNode *IDomB = NodeB->getIDom();
332 if (NodeADoms.count(IDomB) != 0)
333 return IDomB->getBlock();
335 IDomB = IDomB->getIDom();
341 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
342 assert(IDom && "No immediate dominator?");
343 if (IDom != NewIDom) {
344 std::vector<DomTreeNode*>::iterator I =
345 std::find(IDom->Children.begin(), IDom->Children.end(), this);
346 assert(I != IDom->Children.end() &&
347 "Not in immediate dominator children set!");
348 // I am no longer your child...
349 IDom->Children.erase(I);
351 // Switch to new dominator
353 IDom->Children.push_back(this);
357 static std::ostream &operator<<(std::ostream &o, const DomTreeNode *Node) {
358 if (Node->getBlock())
359 WriteAsOperand(o, Node->getBlock(), false);
361 o << " <<exit node>>";
363 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
368 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
370 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
371 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
373 PrintDomTree(*I, o, Lev+1);
376 /// eraseNode - Removes a node from the domiantor tree. Block must not
377 /// domiante any other blocks. Removes node from its immediate dominator's
378 /// children list. Deletes dominator node associated with basic block BB.
379 void DominatorTreeBase::eraseNode(BasicBlock *BB) {
380 DomTreeNode *Node = getNode(BB);
381 assert (Node && "Removing node that isn't in dominator tree.");
382 assert (Node->getChildren().empty() && "Node is not a leaf node.");
384 // Remove node from immediate dominator's children list.
385 DomTreeNode *IDom = Node->getIDom();
387 std::vector<DomTreeNode*>::iterator I =
388 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
389 assert(I != IDom->Children.end() &&
390 "Not in immediate dominator children set!");
391 // I am no longer your child...
392 IDom->Children.erase(I);
395 DomTreeNodes.erase(BB);
399 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
400 o << "=============================--------------------------------\n";
401 o << "Inorder Dominator Tree: ";
403 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
406 PrintDomTree(getRootNode(), o, 1);
409 void DominatorTreeBase::dump() {
413 bool DominatorTree::runOnFunction(Function &F) {
414 reset(); // Reset from the last time we were run...
415 Roots.push_back(&F.getEntryBlock());
416 DTcalculate(*this, F);
420 //===----------------------------------------------------------------------===//
421 // DominanceFrontier Implementation
422 //===----------------------------------------------------------------------===//
424 char DominanceFrontier::ID = 0;
425 static RegisterPass<DominanceFrontier>
426 G("domfrontier", "Dominance Frontier Construction", true);
428 // NewBB is split and now it has one successor. Update dominace frontier to
429 // reflect this change.
430 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
431 assert(NewBB->getTerminator()->getNumSuccessors() == 1
432 && "NewBB should have a single successor!");
433 BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
435 std::vector<BasicBlock*> PredBlocks;
436 for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
438 PredBlocks.push_back(*PI);
440 if (PredBlocks.empty())
441 // If NewBB does not have any predecessors then it is a entry block.
442 // In this case, NewBB and its successor NewBBSucc dominates all
446 // NewBBSucc inherits original NewBB frontier.
447 DominanceFrontier::iterator NewBBI = find(NewBB);
448 if (NewBBI != end()) {
449 DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
450 DominanceFrontier::DomSetType NewBBSuccSet;
451 NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
452 addBasicBlock(NewBBSucc, NewBBSuccSet);
455 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
456 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
458 DominatorTree &DT = getAnalysis<DominatorTree>();
459 if (DT.dominates(NewBB, NewBBSucc)) {
460 DominanceFrontier::iterator DFI = find(PredBlocks[0]);
462 DominanceFrontier::DomSetType Set = DFI->second;
463 // Filter out stuff in Set that we do not dominate a predecessor of.
464 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
465 E = Set.end(); SetI != E;) {
466 bool DominatesPred = false;
467 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
469 if (DT.dominates(NewBB, *PI))
470 DominatesPred = true;
477 if (NewBBI != end()) {
478 DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
479 NewBBSet.insert(Set.begin(), Set.end());
481 addBasicBlock(NewBB, Set);
485 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
486 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
487 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
488 DominanceFrontier::DomSetType NewDFSet;
489 NewDFSet.insert(NewBBSucc);
490 addBasicBlock(NewBB, NewDFSet);
493 // Now we must loop over all of the dominance frontiers in the function,
494 // replacing occurrences of NewBBSucc with NewBB in some cases. All
495 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
496 // their dominance frontier must be updated to contain NewBB instead.
498 for (Function::iterator FI = NewBB->getParent()->begin(),
499 FE = NewBB->getParent()->end(); FI != FE; ++FI) {
500 DominanceFrontier::iterator DFI = find(FI);
501 if (DFI == end()) continue; // unreachable block.
503 // Only consider nodes that have NewBBSucc in their dominator frontier.
504 if (!DFI->second.count(NewBBSucc)) continue;
506 // Verify whether this block dominates a block in predblocks. If not, do
508 bool BlockDominatesAny = false;
509 for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(),
510 BE = PredBlocks.end(); BI != BE; ++BI) {
511 if (DT.dominates(FI, *BI)) {
512 BlockDominatesAny = true;
517 if (!BlockDominatesAny)
520 // If NewBBSucc should not stay in our dominator frontier, remove it.
521 // We remove it unless there is a predecessor of NewBBSucc that we
522 // dominate, but we don't strictly dominate NewBBSucc.
523 bool ShouldRemove = true;
524 if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
525 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
526 // Check to see if it dominates any predecessors of NewBBSucc.
527 for (pred_iterator PI = pred_begin(NewBBSucc),
528 E = pred_end(NewBBSucc); PI != E; ++PI)
529 if (DT.dominates(FI, *PI)) {
530 ShouldRemove = false;
536 removeFromFrontier(DFI, NewBBSucc);
537 addToFrontier(DFI, NewBB);
542 class DFCalculateWorkObject {
544 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
545 const DomTreeNode *N,
546 const DomTreeNode *PN)
547 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
548 BasicBlock *currentBB;
549 BasicBlock *parentBB;
550 const DomTreeNode *Node;
551 const DomTreeNode *parentNode;
555 const DominanceFrontier::DomSetType &
556 DominanceFrontier::calculate(const DominatorTree &DT,
557 const DomTreeNode *Node) {
558 BasicBlock *BB = Node->getBlock();
559 DomSetType *Result = NULL;
561 std::vector<DFCalculateWorkObject> workList;
562 SmallPtrSet<BasicBlock *, 32> visited;
564 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
566 DFCalculateWorkObject *currentW = &workList.back();
567 assert (currentW && "Missing work object.");
569 BasicBlock *currentBB = currentW->currentBB;
570 BasicBlock *parentBB = currentW->parentBB;
571 const DomTreeNode *currentNode = currentW->Node;
572 const DomTreeNode *parentNode = currentW->parentNode;
573 assert (currentBB && "Invalid work object. Missing current Basic Block");
574 assert (currentNode && "Invalid work object. Missing current Node");
575 DomSetType &S = Frontiers[currentBB];
577 // Visit each block only once.
578 if (visited.count(currentBB) == 0) {
579 visited.insert(currentBB);
581 // Loop over CFG successors to calculate DFlocal[currentNode]
582 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
584 // Does Node immediately dominate this successor?
585 if (DT[*SI]->getIDom() != currentNode)
590 // At this point, S is DFlocal. Now we union in DFup's of our children...
591 // Loop through and visit the nodes that Node immediately dominates (Node's
592 // children in the IDomTree)
593 bool visitChild = false;
594 for (DomTreeNode::const_iterator NI = currentNode->begin(),
595 NE = currentNode->end(); NI != NE; ++NI) {
596 DomTreeNode *IDominee = *NI;
597 BasicBlock *childBB = IDominee->getBlock();
598 if (visited.count(childBB) == 0) {
599 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
600 IDominee, currentNode));
605 // If all children are visited or there is any child then pop this block
606 // from the workList.
614 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
615 DomSetType &parentSet = Frontiers[parentBB];
616 for (; CDFI != CDFE; ++CDFI) {
617 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
618 parentSet.insert(*CDFI);
623 } while (!workList.empty());
628 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
629 for (const_iterator I = begin(), E = end(); I != E; ++I) {
630 o << " DomFrontier for BB";
632 WriteAsOperand(o, I->first, false);
634 o << " <<exit node>>";
635 o << " is:\t" << I->second << "\n";
639 void DominanceFrontierBase::dump() {