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"
31 template <typename GraphType> struct GraphTraits;
33 //===----------------------------------------------------------------------===//
34 /// DominatorBase - Base class that other, more interesting dominator analyses
37 class DominatorBase : public FunctionPass {
39 std::vector<BasicBlock*> Roots;
40 const bool IsPostDominators;
41 inline DominatorBase(intptr_t ID, bool isPostDom) :
42 FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
45 /// getRoots - Return the root blocks of the current CFG. This may include
46 /// multiple blocks if we are computing post dominators. For forward
47 /// dominators, this will always be a single block (the entry node).
49 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
51 /// isPostDominator - Returns true if analysis based of postdoms
53 bool isPostDominator() const { return IsPostDominators; }
57 //===----------------------------------------------------------------------===//
58 // DomTreeNode - Dominator Tree Node
59 class DominatorTreeBase;
60 class PostDominatorTree;
64 std::vector<DomTreeNode*> Children;
65 int DFSNumIn, DFSNumOut;
67 friend class DominatorTreeBase;
68 friend class PostDominatorTree;
70 typedef std::vector<DomTreeNode*>::iterator iterator;
71 typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
73 iterator begin() { return Children.begin(); }
74 iterator end() { return Children.end(); }
75 const_iterator begin() const { return Children.begin(); }
76 const_iterator end() const { return Children.end(); }
78 inline BasicBlock *getBlock() const { return TheBB; }
79 inline DomTreeNode *getIDom() const { return IDom; }
80 inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
82 inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom)
83 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
84 inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
85 void setIDom(DomTreeNode *NewIDom);
88 // Return true if this node is dominated by other. Use this only if DFS info is valid.
89 bool DominatedBy(const DomTreeNode *other) const {
90 return this->DFSNumIn >= other->DFSNumIn &&
91 this->DFSNumOut <= other->DFSNumOut;
94 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
96 void assignDFSNumber(int num);
99 //===----------------------------------------------------------------------===//
100 /// DominatorTree - Calculate the immediate dominator tree for a function.
102 class DominatorTreeBase : public DominatorBase {
106 typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
107 DomTreeNodeMapType DomTreeNodes;
108 DomTreeNode *RootNode;
111 unsigned int SlowQueries;
112 // Information record used during immediate dominators computation.
116 BasicBlock *Label, *Parent, *Child, *Ancestor;
118 std::vector<BasicBlock*> Bucket;
120 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
123 std::map<BasicBlock*, BasicBlock*> IDoms;
125 // Vertex - Map the DFS number to the BasicBlock*
126 std::vector<BasicBlock*> Vertex;
128 // Info - Collection of information used during the computation of idoms.
129 std::map<BasicBlock*, InfoRec> Info;
131 void updateDFSNumbers();
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 /// getIDomBlock - return basic block BB's immediate dominator basic block.
154 BasicBlock *getIDomBlock(BasicBlock *BB) {
155 DomTreeNode *N = getNode(BB);
156 assert (N && "Missing dominator tree node");
157 DomTreeNode *I = N->getIDom();
158 assert (N && "Missing immediate dominator");
159 return I->getBlock();
162 /// getRootNode - This returns the entry node for the CFG of the function. If
163 /// this tree represents the post-dominance relations for a function, however,
164 /// this root may be a node with the block == NULL. This is the case when
165 /// there are multiple exit nodes from a particular function. Consumers of
166 /// post-dominance information must be capable of dealing with this
169 DomTreeNode *getRootNode() { return RootNode; }
170 const DomTreeNode *getRootNode() const { return RootNode; }
172 /// properlyDominates - Returns true iff this dominates N and this != N.
173 /// Note that this is not a constant time operation!
175 bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
176 if (A == 0 || B == 0) return false;
177 return dominatedBySlowTreeWalk(A, B);
180 inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
181 return properlyDominates(getNode(A), getNode(B));
184 bool dominatedBySlowTreeWalk(const DomTreeNode *A,
185 const DomTreeNode *B) const {
186 const DomTreeNode *IDom;
187 if (A == 0 || B == 0) return false;
188 while ((IDom = B->getIDom()) != 0 && IDom != A)
189 B = IDom; // Walk up the tree
194 /// isReachableFromEntry - Return true if A is dominated by the entry
195 /// block of the function containing it.
196 const bool isReachableFromEntry(BasicBlock* A);
198 /// dominates - Returns true iff A dominates B. Note that this is not a
199 /// constant time operation!
201 inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
203 return true; // A node trivially dominates itself.
205 if (A == 0 || B == 0)
209 return B->DominatedBy(A);
211 // If we end up with too many slow queries, just update the
212 // DFS numbers on the theory that we are going to keep querying.
214 if (SlowQueries > 32) {
216 return B->DominatedBy(A);
219 return dominatedBySlowTreeWalk(A, B);
222 inline bool dominates(BasicBlock *A, BasicBlock *B) {
226 return dominates(getNode(A), getNode(B));
229 /// findNearestCommonDominator - Find nearest common dominator basic block
230 /// for basic block A and B. If there is no such block then return NULL.
231 BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
233 // dominates - Return true if A dominates B. This performs the
234 // special checks necessary if A and B are in the same basic block.
235 bool dominates(Instruction *A, Instruction *B);
237 //===--------------------------------------------------------------------===//
238 // API to update (Post)DominatorTree information based on modifications to
241 /// addNewBlock - Add a new node to the dominator tree information. This
242 /// creates a new node as a child of DomBB dominator node,linking it into
243 /// the children list of the immediate dominator.
244 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
245 assert(getNode(BB) == 0 && "Block already in dominator tree!");
246 DomTreeNode *IDomNode = getNode(DomBB);
247 assert(IDomNode && "Not immediate dominator specified for block!");
248 DFSInfoValid = false;
249 return DomTreeNodes[BB] =
250 IDomNode->addChild(new DomTreeNode(BB, IDomNode));
253 /// changeImmediateDominator - This method is used to update the dominator
254 /// tree information when a node's immediate dominator changes.
256 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
257 assert(N && NewIDom && "Cannot change null node pointers!");
258 DFSInfoValid = false;
262 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
263 changeImmediateDominator(getNode(BB), getNode(NewBB));
266 /// removeNode - Removes a node from the dominator tree. Block must not
267 /// dominate any other blocks. Invalidates any node pointing to removed
269 void removeNode(BasicBlock *BB) {
270 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
271 DomTreeNodes.erase(BB);
274 /// print - Convert to human readable form
276 virtual void print(std::ostream &OS, const Module* = 0) const;
277 void print(std::ostream *OS, const Module* M = 0) const {
278 if (OS) print(*OS, M);
283 //===-------------------------------------
284 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
285 /// compute a normal dominator tree.
287 class DominatorTree : public DominatorTreeBase {
289 static char ID; // Pass ID, replacement for typeid
290 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
292 BasicBlock *getRoot() const {
293 assert(Roots.size() == 1 && "Should always have entry node!");
297 virtual bool runOnFunction(Function &F);
299 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
300 AU.setPreservesAll();
304 /// BB is split and now it has one successor. Update dominator tree to
305 /// reflect this change.
306 void splitBlock(BasicBlock *BB);
308 void calculate(Function& F);
309 DomTreeNode *getNodeForBlock(BasicBlock *BB);
310 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
311 void Compress(BasicBlock *V);
312 BasicBlock *Eval(BasicBlock *v);
313 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
314 inline BasicBlock *getIDom(BasicBlock *BB) const {
315 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
316 return I != IDoms.end() ? I->second : 0;
320 //===-------------------------------------
321 /// DominatorTree GraphTraits specialization so the DominatorTree can be
322 /// iterable by generic graph iterators.
324 template <> struct GraphTraits<DomTreeNode*> {
325 typedef DomTreeNode NodeType;
326 typedef NodeType::iterator ChildIteratorType;
328 static NodeType *getEntryNode(NodeType *N) {
331 static inline ChildIteratorType child_begin(NodeType* N) {
334 static inline ChildIteratorType child_end(NodeType* N) {
339 template <> struct GraphTraits<DominatorTree*>
340 : public GraphTraits<DomTreeNode*> {
341 static NodeType *getEntryNode(DominatorTree *DT) {
342 return DT->getRootNode();
347 //===----------------------------------------------------------------------===//
348 /// DominanceFrontierBase - Common base class for computing forward and inverse
349 /// dominance frontiers for a function.
351 class DominanceFrontierBase : public DominatorBase {
353 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
354 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
356 DomSetMapType Frontiers;
358 DominanceFrontierBase(intptr_t ID, bool isPostDom)
359 : DominatorBase(ID, isPostDom) {}
361 virtual void releaseMemory() { Frontiers.clear(); }
363 // Accessor interface:
364 typedef DomSetMapType::iterator iterator;
365 typedef DomSetMapType::const_iterator const_iterator;
366 iterator begin() { return Frontiers.begin(); }
367 const_iterator begin() const { return Frontiers.begin(); }
368 iterator end() { return Frontiers.end(); }
369 const_iterator end() const { return Frontiers.end(); }
370 iterator find(BasicBlock *B) { return Frontiers.find(B); }
371 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
373 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
374 assert(find(BB) == end() && "Block already in DominanceFrontier!");
375 Frontiers.insert(std::make_pair(BB, frontier));
378 void addToFrontier(iterator I, BasicBlock *Node) {
379 assert(I != end() && "BB is not in DominanceFrontier!");
380 I->second.insert(Node);
383 void removeFromFrontier(iterator I, BasicBlock *Node) {
384 assert(I != end() && "BB is not in DominanceFrontier!");
385 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
386 I->second.erase(Node);
389 /// print - Convert to human readable form
391 virtual void print(std::ostream &OS, const Module* = 0) const;
392 void print(std::ostream *OS, const Module* M = 0) const {
393 if (OS) print(*OS, M);
399 //===-------------------------------------
400 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
401 /// used to compute a forward dominator frontiers.
403 class DominanceFrontier : public DominanceFrontierBase {
405 static char ID; // Pass ID, replacement for typeid
406 DominanceFrontier() :
407 DominanceFrontierBase((intptr_t)& ID, false) {}
409 BasicBlock *getRoot() const {
410 assert(Roots.size() == 1 && "Should always have entry node!");
414 virtual bool runOnFunction(Function &) {
416 DominatorTree &DT = getAnalysis<DominatorTree>();
417 Roots = DT.getRoots();
418 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
419 calculate(DT, DT[Roots[0]]);
423 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
424 AU.setPreservesAll();
425 AU.addRequired<DominatorTree>();
429 /// BB is split and now it has one successor. Update dominace frontier to
430 /// reflect this change.
431 void splitBlock(BasicBlock *BB);
434 const DomSetType &calculate(const DominatorTree &DT,
435 const DomTreeNode *Node);
439 } // End llvm namespace