1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
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 defines the following classes:
11 // 1. DominatorTree: Represent dominators as an explicit tree structure.
12 // 2. DominanceFrontier: Calculate and hold the dominance frontier for a
15 // These data structures are listed in increasing order of complexity. It
16 // takes longer to calculate the dominator frontier, for example, than the
17 // DominatorTree mapping.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_ANALYSIS_DOMINATORS_H
22 #define LLVM_ANALYSIS_DOMINATORS_H
24 #include "llvm/Pass.h"
26 #include "llvm/ADT/DenseMap.h"
32 template <typename GraphType> struct GraphTraits;
34 //===----------------------------------------------------------------------===//
35 /// DominatorBase - Base class that other, more interesting dominator analyses
38 class DominatorBase : public FunctionPass {
40 std::vector<BasicBlock*> Roots;
41 const bool IsPostDominators;
42 inline DominatorBase(intptr_t ID, bool isPostDom) :
43 FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
46 /// getRoots - Return the root blocks of the current CFG. This may include
47 /// multiple blocks if we are computing post dominators. For forward
48 /// dominators, this will always be a single block (the entry node).
50 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
52 /// isPostDominator - Returns true if analysis based of postdoms
54 bool isPostDominator() const { return IsPostDominators; }
58 //===----------------------------------------------------------------------===//
59 // DomTreeNode - Dominator Tree Node
60 class DominatorTreeBase;
61 class PostDominatorTree;
65 std::vector<DomTreeNode*> Children;
66 int DFSNumIn, DFSNumOut;
68 friend class DominatorTreeBase;
69 friend class PostDominatorTree;
71 typedef std::vector<DomTreeNode*>::iterator iterator;
72 typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
74 iterator begin() { return Children.begin(); }
75 iterator end() { return Children.end(); }
76 const_iterator begin() const { return Children.begin(); }
77 const_iterator end() const { return Children.end(); }
79 BasicBlock *getBlock() const { return TheBB; }
80 DomTreeNode *getIDom() const { return IDom; }
81 const std::vector<DomTreeNode*> &getChildren() const { return Children; }
83 DomTreeNode(BasicBlock *BB, DomTreeNode *iDom)
84 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
85 DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
86 void setIDom(DomTreeNode *NewIDom);
89 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
91 unsigned getDFSNumIn() const { return DFSNumIn; }
92 unsigned getDFSNumOut() const { return DFSNumOut; }
94 // Return true if this node is dominated by other. Use this only if DFS info
96 bool DominatedBy(const DomTreeNode *other) const {
97 return this->DFSNumIn >= other->DFSNumIn &&
98 this->DFSNumOut <= other->DFSNumOut;
101 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
103 void assignDFSNumber(int num);
106 //===----------------------------------------------------------------------===//
107 /// DominatorTree - Calculate the immediate dominator tree for a function.
109 class DominatorTreeBase : public DominatorBase {
113 typedef DenseMap<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
114 DomTreeNodeMapType DomTreeNodes;
115 DomTreeNode *RootNode;
118 unsigned int SlowQueries;
119 // Information record used during immediate dominators computation.
123 BasicBlock *Label, *Parent, *Child, *Ancestor;
125 std::vector<BasicBlock*> Bucket;
127 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0) {}
130 DenseMap<BasicBlock*, BasicBlock*> IDoms;
132 // Vertex - Map the DFS number to the BasicBlock*
133 std::vector<BasicBlock*> Vertex;
135 // Info - Collection of information used during the computation of idoms.
136 DenseMap<BasicBlock*, InfoRec> Info;
138 void updateDFSNumbers();
141 DominatorTreeBase(intptr_t ID, bool isPostDom)
142 : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
143 ~DominatorTreeBase() { reset(); }
145 virtual void releaseMemory() { reset(); }
147 /// getNode - return the (Post)DominatorTree node for the specified basic
148 /// block. This is the same as using operator[] on this class.
150 inline DomTreeNode *getNode(BasicBlock *BB) const {
151 DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
152 return I != DomTreeNodes.end() ? I->second : 0;
155 inline DomTreeNode *operator[](BasicBlock *BB) const {
159 /// getRootNode - This returns the entry node for the CFG of the function. If
160 /// this tree represents the post-dominance relations for a function, however,
161 /// this root may be a node with the block == NULL. This is the case when
162 /// there are multiple exit nodes from a particular function. Consumers of
163 /// post-dominance information must be capable of dealing with this
166 DomTreeNode *getRootNode() { return RootNode; }
167 const DomTreeNode *getRootNode() const { return RootNode; }
169 /// properlyDominates - Returns true iff this dominates N and this != N.
170 /// Note that this is not a constant time operation!
172 bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
173 if (A == 0 || B == 0) return false;
174 return dominatedBySlowTreeWalk(A, B);
177 inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
178 return properlyDominates(getNode(A), getNode(B));
181 bool dominatedBySlowTreeWalk(const DomTreeNode *A,
182 const DomTreeNode *B) const {
183 const DomTreeNode *IDom;
184 if (A == 0 || B == 0) return false;
185 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
186 B = IDom; // Walk up the tree
191 /// isReachableFromEntry - Return true if A is dominated by the entry
192 /// block of the function containing it.
193 const bool isReachableFromEntry(BasicBlock* A);
195 /// dominates - Returns true iff A dominates B. Note that this is not a
196 /// constant time operation!
198 inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
200 return true; // A node trivially dominates itself.
202 if (A == 0 || B == 0)
206 return B->DominatedBy(A);
208 // If we end up with too many slow queries, just update the
209 // DFS numbers on the theory that we are going to keep querying.
211 if (SlowQueries > 32) {
213 return B->DominatedBy(A);
216 return dominatedBySlowTreeWalk(A, B);
219 inline bool dominates(BasicBlock *A, BasicBlock *B) {
223 return dominates(getNode(A), getNode(B));
226 /// findNearestCommonDominator - Find nearest common dominator basic block
227 /// for basic block A and B. If there is no such block then return NULL.
228 BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
230 // dominates - Return true if A dominates B. This performs the
231 // special checks necessary if A and B are in the same basic block.
232 bool dominates(Instruction *A, Instruction *B);
234 //===--------------------------------------------------------------------===//
235 // API to update (Post)DominatorTree information based on modifications to
238 /// addNewBlock - Add a new node to the dominator tree information. This
239 /// creates a new node as a child of DomBB dominator node,linking it into
240 /// the children list of the immediate dominator.
241 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
242 assert(getNode(BB) == 0 && "Block already in dominator tree!");
243 DomTreeNode *IDomNode = getNode(DomBB);
244 assert(IDomNode && "Not immediate dominator specified for block!");
245 DFSInfoValid = false;
246 return DomTreeNodes[BB] =
247 IDomNode->addChild(new DomTreeNode(BB, IDomNode));
250 /// changeImmediateDominator - This method is used to update the dominator
251 /// tree information when a node's immediate dominator changes.
253 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
254 assert(N && NewIDom && "Cannot change null node pointers!");
255 DFSInfoValid = false;
259 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
260 changeImmediateDominator(getNode(BB), getNode(NewBB));
263 /// removeNode - Removes a node from the dominator tree. Block must not
264 /// dominate any other blocks. Invalidates any node pointing to removed
266 void removeNode(BasicBlock *BB) {
267 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
268 DomTreeNodes.erase(BB);
271 /// print - Convert to human readable form
273 virtual void print(std::ostream &OS, const Module* = 0) const;
274 void print(std::ostream *OS, const Module* M = 0) const {
275 if (OS) print(*OS, M);
280 //===-------------------------------------
281 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
282 /// compute a normal dominator tree.
284 class DominatorTree : public DominatorTreeBase {
286 static char ID; // Pass ID, replacement for typeid
287 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
289 BasicBlock *getRoot() const {
290 assert(Roots.size() == 1 && "Should always have entry node!");
294 virtual bool runOnFunction(Function &F);
296 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
297 AU.setPreservesAll();
301 /// BB is split and now it has one successor. Update dominator tree to
302 /// reflect this change.
303 void splitBlock(BasicBlock *BB);
305 void calculate(Function& F);
306 DomTreeNode *getNodeForBlock(BasicBlock *BB);
307 unsigned DFSPass(BasicBlock *V, unsigned N);
308 void Compress(BasicBlock *V);
309 BasicBlock *Eval(BasicBlock *v);
310 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
311 inline BasicBlock *getIDom(BasicBlock *BB) const {
312 DenseMap<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
313 return I != IDoms.end() ? I->second : 0;
317 //===-------------------------------------
318 /// DominatorTree GraphTraits specialization so the DominatorTree can be
319 /// iterable by generic graph iterators.
321 template <> struct GraphTraits<DomTreeNode*> {
322 typedef DomTreeNode NodeType;
323 typedef NodeType::iterator ChildIteratorType;
325 static NodeType *getEntryNode(NodeType *N) {
328 static inline ChildIteratorType child_begin(NodeType* N) {
331 static inline ChildIteratorType child_end(NodeType* N) {
336 template <> struct GraphTraits<DominatorTree*>
337 : public GraphTraits<DomTreeNode*> {
338 static NodeType *getEntryNode(DominatorTree *DT) {
339 return DT->getRootNode();
344 //===----------------------------------------------------------------------===//
345 /// DominanceFrontierBase - Common base class for computing forward and inverse
346 /// dominance frontiers for a function.
348 class DominanceFrontierBase : public DominatorBase {
350 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
351 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
353 DomSetMapType Frontiers;
355 DominanceFrontierBase(intptr_t ID, bool isPostDom)
356 : DominatorBase(ID, isPostDom) {}
358 virtual void releaseMemory() { Frontiers.clear(); }
360 // Accessor interface:
361 typedef DomSetMapType::iterator iterator;
362 typedef DomSetMapType::const_iterator const_iterator;
363 iterator begin() { return Frontiers.begin(); }
364 const_iterator begin() const { return Frontiers.begin(); }
365 iterator end() { return Frontiers.end(); }
366 const_iterator end() const { return Frontiers.end(); }
367 iterator find(BasicBlock *B) { return Frontiers.find(B); }
368 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
370 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
371 assert(find(BB) == end() && "Block already in DominanceFrontier!");
372 Frontiers.insert(std::make_pair(BB, frontier));
375 void addToFrontier(iterator I, BasicBlock *Node) {
376 assert(I != end() && "BB is not in DominanceFrontier!");
377 I->second.insert(Node);
380 void removeFromFrontier(iterator I, BasicBlock *Node) {
381 assert(I != end() && "BB is not in DominanceFrontier!");
382 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
383 I->second.erase(Node);
386 /// print - Convert to human readable form
388 virtual void print(std::ostream &OS, const Module* = 0) const;
389 void print(std::ostream *OS, const Module* M = 0) const {
390 if (OS) print(*OS, M);
396 //===-------------------------------------
397 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
398 /// used to compute a forward dominator frontiers.
400 class DominanceFrontier : public DominanceFrontierBase {
402 static char ID; // Pass ID, replacement for typeid
403 DominanceFrontier() :
404 DominanceFrontierBase((intptr_t)& ID, false) {}
406 BasicBlock *getRoot() const {
407 assert(Roots.size() == 1 && "Should always have entry node!");
411 virtual bool runOnFunction(Function &) {
413 DominatorTree &DT = getAnalysis<DominatorTree>();
414 Roots = DT.getRoots();
415 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
416 calculate(DT, DT[Roots[0]]);
420 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
421 AU.setPreservesAll();
422 AU.addRequired<DominatorTree>();
425 /// splitBlock - BB is split and now it has one successor. Update dominance
426 /// frontier to reflect this change.
427 void splitBlock(BasicBlock *BB);
430 const DomSetType &calculate(const DominatorTree &DT,
431 const DomTreeNode *Node);
435 } // End llvm namespace