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;
102 //===----------------------------------------------------------------------===//
103 /// DominatorTree - Calculate the immediate dominator tree for a function.
105 class DominatorTreeBase : public DominatorBase {
108 typedef DenseMap<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
109 DomTreeNodeMapType DomTreeNodes;
110 DomTreeNode *RootNode;
113 unsigned int SlowQueries;
114 // Information record used during immediate dominators computation.
118 BasicBlock *Label, *Parent, *Child, *Ancestor;
120 std::vector<BasicBlock*> Bucket;
122 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0) {}
125 DenseMap<BasicBlock*, BasicBlock*> IDoms;
127 // Vertex - Map the DFS number to the BasicBlock*
128 std::vector<BasicBlock*> Vertex;
130 // Info - Collection of information used during the computation of idoms.
131 DenseMap<BasicBlock*, InfoRec> Info;
134 DominatorTreeBase(intptr_t ID, bool isPostDom)
135 : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
136 ~DominatorTreeBase() { reset(); }
138 virtual void releaseMemory() { reset(); }
140 /// getNode - return the (Post)DominatorTree node for the specified basic
141 /// block. This is the same as using operator[] on this class.
143 inline DomTreeNode *getNode(BasicBlock *BB) const {
144 DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
145 return I != DomTreeNodes.end() ? I->second : 0;
148 inline DomTreeNode *operator[](BasicBlock *BB) const {
152 /// getRootNode - This returns the entry node for the CFG of the function. If
153 /// this tree represents the post-dominance relations for a function, however,
154 /// this root may be a node with the block == NULL. This is the case when
155 /// there are multiple exit nodes from a particular function. Consumers of
156 /// post-dominance information must be capable of dealing with this
159 DomTreeNode *getRootNode() { return RootNode; }
160 const DomTreeNode *getRootNode() const { return RootNode; }
162 /// properlyDominates - Returns true iff this dominates N and this != N.
163 /// Note that this is not a constant time operation!
165 bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
166 if (A == 0 || B == 0) return false;
167 return dominatedBySlowTreeWalk(A, B);
170 inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
171 return properlyDominates(getNode(A), getNode(B));
174 bool dominatedBySlowTreeWalk(const DomTreeNode *A,
175 const DomTreeNode *B) const {
176 const DomTreeNode *IDom;
177 if (A == 0 || B == 0) return false;
178 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
179 B = IDom; // Walk up the tree
184 /// isReachableFromEntry - Return true if A is dominated by the entry
185 /// block of the function containing it.
186 const bool isReachableFromEntry(BasicBlock* A);
188 /// dominates - Returns true iff A dominates B. Note that this is not a
189 /// constant time operation!
191 inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
193 return true; // A node trivially dominates itself.
195 if (A == 0 || B == 0)
199 return B->DominatedBy(A);
201 // If we end up with too many slow queries, just update the
202 // DFS numbers on the theory that we are going to keep querying.
204 if (SlowQueries > 32) {
206 return B->DominatedBy(A);
209 return dominatedBySlowTreeWalk(A, B);
212 inline bool dominates(BasicBlock *A, BasicBlock *B) {
216 return dominates(getNode(A), getNode(B));
219 /// findNearestCommonDominator - Find nearest common dominator basic block
220 /// for basic block A and B. If there is no such block then return NULL.
221 BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
223 // dominates - Return true if A dominates B. This performs the
224 // special checks necessary if A and B are in the same basic block.
225 bool dominates(Instruction *A, Instruction *B);
227 //===--------------------------------------------------------------------===//
228 // API to update (Post)DominatorTree information based on modifications to
231 /// addNewBlock - Add a new node to the dominator tree information. This
232 /// creates a new node as a child of DomBB dominator node,linking it into
233 /// the children list of the immediate dominator.
234 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
235 assert(getNode(BB) == 0 && "Block already in dominator tree!");
236 DomTreeNode *IDomNode = getNode(DomBB);
237 assert(IDomNode && "Not immediate dominator specified for block!");
238 DFSInfoValid = false;
239 return DomTreeNodes[BB] =
240 IDomNode->addChild(new DomTreeNode(BB, IDomNode));
243 /// changeImmediateDominator - This method is used to update the dominator
244 /// tree information when a node's immediate dominator changes.
246 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
247 assert(N && NewIDom && "Cannot change null node pointers!");
248 DFSInfoValid = false;
252 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
253 changeImmediateDominator(getNode(BB), getNode(NewBB));
256 /// removeNode - Removes a node from the dominator tree. Block must not
257 /// dominate any other blocks. Invalidates any node pointing to removed
259 void removeNode(BasicBlock *BB) {
260 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
261 DomTreeNodes.erase(BB);
264 /// print - Convert to human readable form
266 virtual void print(std::ostream &OS, const Module* = 0) const;
267 void print(std::ostream *OS, const Module* M = 0) const {
268 if (OS) print(*OS, M);
273 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
274 /// dominator tree in dfs order.
275 void updateDFSNumbers();
278 //===-------------------------------------
279 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
280 /// compute a normal dominator tree.
282 class DominatorTree : public DominatorTreeBase {
284 static char ID; // Pass ID, replacement for typeid
285 DominatorTree() : DominatorTreeBase(intptr_t(&ID), false) {}
287 BasicBlock *getRoot() const {
288 assert(Roots.size() == 1 && "Should always have entry node!");
292 virtual bool runOnFunction(Function &F);
294 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
295 AU.setPreservesAll();
299 /// BB is split and now it has one successor. Update dominator tree to
300 /// reflect this change.
301 void splitBlock(BasicBlock *BB);
303 void calculate(Function& F);
304 DomTreeNode *getNodeForBlock(BasicBlock *BB);
305 unsigned DFSPass(BasicBlock *V, unsigned N);
306 void Compress(BasicBlock *V);
307 BasicBlock *Eval(BasicBlock *v);
308 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
309 inline BasicBlock *getIDom(BasicBlock *BB) const {
310 DenseMap<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
311 return I != IDoms.end() ? I->second : 0;
315 //===-------------------------------------
316 /// DominatorTree GraphTraits specialization so the DominatorTree can be
317 /// iterable by generic graph iterators.
319 template <> struct GraphTraits<DomTreeNode*> {
320 typedef DomTreeNode NodeType;
321 typedef NodeType::iterator ChildIteratorType;
323 static NodeType *getEntryNode(NodeType *N) {
326 static inline ChildIteratorType child_begin(NodeType* N) {
329 static inline ChildIteratorType child_end(NodeType* N) {
334 template <> struct GraphTraits<DominatorTree*>
335 : public GraphTraits<DomTreeNode*> {
336 static NodeType *getEntryNode(DominatorTree *DT) {
337 return DT->getRootNode();
342 //===----------------------------------------------------------------------===//
343 /// DominanceFrontierBase - Common base class for computing forward and inverse
344 /// dominance frontiers for a function.
346 class DominanceFrontierBase : public DominatorBase {
348 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
349 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
351 DomSetMapType Frontiers;
353 DominanceFrontierBase(intptr_t ID, bool isPostDom)
354 : DominatorBase(ID, isPostDom) {}
356 virtual void releaseMemory() { Frontiers.clear(); }
358 // Accessor interface:
359 typedef DomSetMapType::iterator iterator;
360 typedef DomSetMapType::const_iterator const_iterator;
361 iterator begin() { return Frontiers.begin(); }
362 const_iterator begin() const { return Frontiers.begin(); }
363 iterator end() { return Frontiers.end(); }
364 const_iterator end() const { return Frontiers.end(); }
365 iterator find(BasicBlock *B) { return Frontiers.find(B); }
366 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
368 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
369 assert(find(BB) == end() && "Block already in DominanceFrontier!");
370 Frontiers.insert(std::make_pair(BB, frontier));
373 void addToFrontier(iterator I, BasicBlock *Node) {
374 assert(I != end() && "BB is not in DominanceFrontier!");
375 I->second.insert(Node);
378 void removeFromFrontier(iterator I, BasicBlock *Node) {
379 assert(I != end() && "BB is not in DominanceFrontier!");
380 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
381 I->second.erase(Node);
384 /// print - Convert to human readable form
386 virtual void print(std::ostream &OS, const Module* = 0) const;
387 void print(std::ostream *OS, const Module* M = 0) const {
388 if (OS) print(*OS, M);
394 //===-------------------------------------
395 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
396 /// used to compute a forward dominator frontiers.
398 class DominanceFrontier : public DominanceFrontierBase {
400 static char ID; // Pass ID, replacement for typeid
401 DominanceFrontier() :
402 DominanceFrontierBase(intptr_t(&ID), false) {}
404 BasicBlock *getRoot() const {
405 assert(Roots.size() == 1 && "Should always have entry node!");
409 virtual bool runOnFunction(Function &) {
411 DominatorTree &DT = getAnalysis<DominatorTree>();
412 Roots = DT.getRoots();
413 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
414 calculate(DT, DT[Roots[0]]);
418 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
419 AU.setPreservesAll();
420 AU.addRequired<DominatorTree>();
423 /// splitBlock - BB is split and now it has one successor. Update dominance
424 /// frontier to reflect this change.
425 void splitBlock(BasicBlock *BB);
428 const DomSetType &calculate(const DominatorTree &DT,
429 const DomTreeNode *Node);
433 } // End llvm namespace