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 inline BasicBlock *getBlock() const { return TheBB; }
80 inline DomTreeNode *getIDom() const { return IDom; }
81 inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
83 inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom)
84 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
85 inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
86 void setIDom(DomTreeNode *NewIDom);
89 // Return true if this node is dominated by other. Use this only if DFS info is valid.
90 bool DominatedBy(const DomTreeNode *other) const {
91 return this->DFSNumIn >= other->DFSNumIn &&
92 this->DFSNumOut <= other->DFSNumOut;
95 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
97 void assignDFSNumber(int num);
100 //===----------------------------------------------------------------------===//
101 /// DominatorTree - Calculate the immediate dominator tree for a function.
103 class DominatorTreeBase : public DominatorBase {
107 typedef DenseMap<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
108 DomTreeNodeMapType DomTreeNodes;
109 DomTreeNode *RootNode;
112 unsigned int SlowQueries;
113 // Information record used during immediate dominators computation.
117 BasicBlock *Label, *Parent, *Child, *Ancestor;
119 std::vector<BasicBlock*> Bucket;
121 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
124 DenseMap<BasicBlock*, BasicBlock*> IDoms;
126 // Vertex - Map the DFS number to the BasicBlock*
127 std::vector<BasicBlock*> Vertex;
129 // Info - Collection of information used during the computation of idoms.
130 std::map<BasicBlock*, InfoRec> Info;
132 void updateDFSNumbers();
135 DominatorTreeBase(intptr_t ID, bool isPostDom)
136 : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
137 ~DominatorTreeBase() { reset(); }
139 virtual void releaseMemory() { reset(); }
141 /// getNode - return the (Post)DominatorTree node for the specified basic
142 /// block. This is the same as using operator[] on this class.
144 inline DomTreeNode *getNode(BasicBlock *BB) const {
145 DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
146 return I != DomTreeNodes.end() ? I->second : 0;
149 inline DomTreeNode *operator[](BasicBlock *BB) const {
153 /// getRootNode - This returns the entry node for the CFG of the function. If
154 /// this tree represents the post-dominance relations for a function, however,
155 /// this root may be a node with the block == NULL. This is the case when
156 /// there are multiple exit nodes from a particular function. Consumers of
157 /// post-dominance information must be capable of dealing with this
160 DomTreeNode *getRootNode() { return RootNode; }
161 const DomTreeNode *getRootNode() const { return RootNode; }
163 /// properlyDominates - Returns true iff this dominates N and this != N.
164 /// Note that this is not a constant time operation!
166 bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
167 if (A == 0 || B == 0) return false;
168 return dominatedBySlowTreeWalk(A, B);
171 inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
172 return properlyDominates(getNode(A), getNode(B));
175 bool dominatedBySlowTreeWalk(const DomTreeNode *A,
176 const DomTreeNode *B) const {
177 const DomTreeNode *IDom;
178 if (A == 0 || B == 0) return false;
179 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
180 B = IDom; // Walk up the tree
185 /// isReachableFromEntry - Return true if A is dominated by the entry
186 /// block of the function containing it.
187 const bool isReachableFromEntry(BasicBlock* A);
189 /// dominates - Returns true iff A dominates B. Note that this is not a
190 /// constant time operation!
192 inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
194 return true; // A node trivially dominates itself.
196 if (A == 0 || B == 0)
200 return B->DominatedBy(A);
202 // If we end up with too many slow queries, just update the
203 // DFS numbers on the theory that we are going to keep querying.
205 if (SlowQueries > 32) {
207 return B->DominatedBy(A);
210 return dominatedBySlowTreeWalk(A, B);
213 inline bool dominates(BasicBlock *A, BasicBlock *B) {
217 return dominates(getNode(A), getNode(B));
220 /// findNearestCommonDominator - Find nearest common dominator basic block
221 /// for basic block A and B. If there is no such block then return NULL.
222 BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B);
224 // dominates - Return true if A dominates B. This performs the
225 // special checks necessary if A and B are in the same basic block.
226 bool dominates(Instruction *A, Instruction *B);
228 //===--------------------------------------------------------------------===//
229 // API to update (Post)DominatorTree information based on modifications to
232 /// addNewBlock - Add a new node to the dominator tree information. This
233 /// creates a new node as a child of DomBB dominator node,linking it into
234 /// the children list of the immediate dominator.
235 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
236 assert(getNode(BB) == 0 && "Block already in dominator tree!");
237 DomTreeNode *IDomNode = getNode(DomBB);
238 assert(IDomNode && "Not immediate dominator specified for block!");
239 DFSInfoValid = false;
240 return DomTreeNodes[BB] =
241 IDomNode->addChild(new DomTreeNode(BB, IDomNode));
244 /// changeImmediateDominator - This method is used to update the dominator
245 /// tree information when a node's immediate dominator changes.
247 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
248 assert(N && NewIDom && "Cannot change null node pointers!");
249 DFSInfoValid = false;
253 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
254 changeImmediateDominator(getNode(BB), getNode(NewBB));
257 /// removeNode - Removes a node from the dominator tree. Block must not
258 /// dominate any other blocks. Invalidates any node pointing to removed
260 void removeNode(BasicBlock *BB) {
261 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
262 DomTreeNodes.erase(BB);
265 /// print - Convert to human readable form
267 virtual void print(std::ostream &OS, const Module* = 0) const;
268 void print(std::ostream *OS, const Module* M = 0) const {
269 if (OS) print(*OS, M);
274 //===-------------------------------------
275 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
276 /// compute a normal dominator tree.
278 class DominatorTree : public DominatorTreeBase {
280 static char ID; // Pass ID, replacement for typeid
281 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
283 BasicBlock *getRoot() const {
284 assert(Roots.size() == 1 && "Should always have entry node!");
288 virtual bool runOnFunction(Function &F);
290 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
291 AU.setPreservesAll();
295 /// BB is split and now it has one successor. Update dominator tree to
296 /// reflect this change.
297 void splitBlock(BasicBlock *BB);
299 void calculate(Function& F);
300 DomTreeNode *getNodeForBlock(BasicBlock *BB);
301 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
302 void Compress(BasicBlock *V);
303 BasicBlock *Eval(BasicBlock *v);
304 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
305 inline BasicBlock *getIDom(BasicBlock *BB) const {
306 DenseMap<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
307 return I != IDoms.end() ? I->second : 0;
311 //===-------------------------------------
312 /// DominatorTree GraphTraits specialization so the DominatorTree can be
313 /// iterable by generic graph iterators.
315 template <> struct GraphTraits<DomTreeNode*> {
316 typedef DomTreeNode NodeType;
317 typedef NodeType::iterator ChildIteratorType;
319 static NodeType *getEntryNode(NodeType *N) {
322 static inline ChildIteratorType child_begin(NodeType* N) {
325 static inline ChildIteratorType child_end(NodeType* N) {
330 template <> struct GraphTraits<DominatorTree*>
331 : public GraphTraits<DomTreeNode*> {
332 static NodeType *getEntryNode(DominatorTree *DT) {
333 return DT->getRootNode();
338 //===----------------------------------------------------------------------===//
339 /// DominanceFrontierBase - Common base class for computing forward and inverse
340 /// dominance frontiers for a function.
342 class DominanceFrontierBase : public DominatorBase {
344 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
345 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
347 DomSetMapType Frontiers;
349 DominanceFrontierBase(intptr_t ID, bool isPostDom)
350 : DominatorBase(ID, isPostDom) {}
352 virtual void releaseMemory() { Frontiers.clear(); }
354 // Accessor interface:
355 typedef DomSetMapType::iterator iterator;
356 typedef DomSetMapType::const_iterator const_iterator;
357 iterator begin() { return Frontiers.begin(); }
358 const_iterator begin() const { return Frontiers.begin(); }
359 iterator end() { return Frontiers.end(); }
360 const_iterator end() const { return Frontiers.end(); }
361 iterator find(BasicBlock *B) { return Frontiers.find(B); }
362 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
364 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
365 assert(find(BB) == end() && "Block already in DominanceFrontier!");
366 Frontiers.insert(std::make_pair(BB, frontier));
369 void addToFrontier(iterator I, BasicBlock *Node) {
370 assert(I != end() && "BB is not in DominanceFrontier!");
371 I->second.insert(Node);
374 void removeFromFrontier(iterator I, BasicBlock *Node) {
375 assert(I != end() && "BB is not in DominanceFrontier!");
376 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
377 I->second.erase(Node);
380 /// print - Convert to human readable form
382 virtual void print(std::ostream &OS, const Module* = 0) const;
383 void print(std::ostream *OS, const Module* M = 0) const {
384 if (OS) print(*OS, M);
390 //===-------------------------------------
391 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
392 /// used to compute a forward dominator frontiers.
394 class DominanceFrontier : public DominanceFrontierBase {
396 static char ID; // Pass ID, replacement for typeid
397 DominanceFrontier() :
398 DominanceFrontierBase((intptr_t)& ID, false) {}
400 BasicBlock *getRoot() const {
401 assert(Roots.size() == 1 && "Should always have entry node!");
405 virtual bool runOnFunction(Function &) {
407 DominatorTree &DT = getAnalysis<DominatorTree>();
408 Roots = DT.getRoots();
409 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
410 calculate(DT, DT[Roots[0]]);
414 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
415 AU.setPreservesAll();
416 AU.addRequired<DominatorTree>();
420 /// BB is split and now it has one successor. Update dominace frontier to
421 /// reflect this change.
422 void splitBlock(BasicBlock *BB);
425 const DomSetType &calculate(const DominatorTree &DT,
426 const DomTreeNode *Node);
430 } // End llvm namespace