Dominators.h revision bef204db6fc6b2e69f93f23f644617a3c01968aa
1//===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
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
13//     function.
14//
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.
18//
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_ANALYSIS_DOMINATORS_H
22#define LLVM_ANALYSIS_DOMINATORS_H
23
24#include "llvm/Pass.h"
25#include <set>
26
27namespace llvm {
28
29class Instruction;
30
31template <typename GraphType> struct GraphTraits;
32
33//===----------------------------------------------------------------------===//
34/// DominatorBase - Base class that other, more interesting dominator analyses
35/// inherit from.
36///
37class DominatorBase : public FunctionPass {
38protected:
39  std::vector<BasicBlock*> Roots;
40  const bool IsPostDominators;
41  inline DominatorBase(intptr_t ID, bool isPostDom) :
42    FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
43public:
44
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).
48  ///
49  inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
50
51  /// isPostDominator - Returns true if analysis based of postdoms
52  ///
53  bool isPostDominator() const { return IsPostDominators; }
54};
55
56
57//===----------------------------------------------------------------------===//
58// DomTreeNode - Dominator Tree Node
59class DominatorTreeBase;
60class PostDominatorTree;
61class DomTreeNode {
62  BasicBlock *TheBB;
63  DomTreeNode *IDom;
64  std::vector<DomTreeNode*> Children;
65  int DFSNumIn, DFSNumOut;
66
67  friend class DominatorTreeBase;
68  friend class PostDominatorTree;
69public:
70  typedef std::vector<DomTreeNode*>::iterator iterator;
71  typedef std::vector<DomTreeNode*>::const_iterator const_iterator;
72
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(); }
77
78  inline BasicBlock *getBlock() const { return TheBB; }
79  inline DomTreeNode *getIDom() const { return IDom; }
80  inline const std::vector<DomTreeNode*> &getChildren() const { return Children; }
81
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);
86
87private:
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;
92  }
93
94  /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
95  /// in dfs order.
96  void assignDFSNumber(int num);
97};
98
99//===----------------------------------------------------------------------===//
100/// DominatorTree - Calculate the immediate dominator tree for a function.
101///
102class DominatorTreeBase : public DominatorBase {
103
104protected:
105  void reset();
106  typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
107  DomTreeNodeMapType DomTreeNodes;
108  DomTreeNode *RootNode;
109
110  bool DFSInfoValid;
111  unsigned int SlowQueries;
112  // Information record used during immediate dominators computation.
113  struct InfoRec {
114    unsigned Semi;
115    unsigned Size;
116    BasicBlock *Label, *Parent, *Child, *Ancestor;
117
118    std::vector<BasicBlock*> Bucket;
119
120    InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
121  };
122
123  std::map<BasicBlock*, BasicBlock*> IDoms;
124
125  // Vertex - Map the DFS number to the BasicBlock*
126  std::vector<BasicBlock*> Vertex;
127
128  // Info - Collection of information used during the computation of idoms.
129  std::map<BasicBlock*, InfoRec> Info;
130
131  void updateDFSNumbers();
132
133  public:
134  DominatorTreeBase(intptr_t ID, bool isPostDom)
135    : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {}
136  ~DominatorTreeBase() { reset(); }
137
138  virtual void releaseMemory() { reset(); }
139
140  /// getNode - return the (Post)DominatorTree node for the specified basic
141  /// block.  This is the same as using operator[] on this class.
142  ///
143  inline DomTreeNode *getNode(BasicBlock *BB) const {
144    DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB);
145    return (i != DomTreeNodes.end()) ? i->second : 0;
146  }
147
148  inline DomTreeNode *operator[](BasicBlock *BB) const {
149    return getNode(BB);
150  }
151
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
157  /// possibility.
158  ///
159  DomTreeNode *getRootNode() { return RootNode; }
160  const DomTreeNode *getRootNode() const { return RootNode; }
161
162  /// properlyDominates - Returns true iff this dominates N and this != N.
163  /// Note that this is not a constant time operation!
164  ///
165  bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const {
166    if (A == 0 || B == 0) return false;
167    return dominatedBySlowTreeWalk(A, B);
168  }
169
170  inline bool properlyDominates(BasicBlock *A, BasicBlock *B) {
171    return properlyDominates(getNode(A), getNode(B));
172  }
173
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
180    return IDom != 0;
181  }
182
183
184  /// isReachableFromEntry - Return true if A is dominated by the entry
185  /// block of the function containing it.
186  const bool isReachableFromEntry(BasicBlock* A);
187
188  /// dominates - Returns true iff A dominates B.  Note that this is not a
189  /// constant time operation!
190  ///
191  inline bool dominates(const DomTreeNode *A, DomTreeNode *B) {
192    if (B == A)
193      return true;  // A node trivially dominates itself.
194
195    if (A == 0 || B == 0)
196      return false;
197
198    if (DFSInfoValid)
199      return B->DominatedBy(A);
200
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.
203    SlowQueries++;
204    if (SlowQueries > 32) {
205      updateDFSNumbers();
206      return B->DominatedBy(A);
207    }
208
209    return dominatedBySlowTreeWalk(A, B);
210  }
211
212  inline bool dominates(BasicBlock *A, BasicBlock *B) {
213    if (A == B)
214      return true;
215
216    return dominates(getNode(A), getNode(B));
217  }
218
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);
222
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);
226
227  //===--------------------------------------------------------------------===//
228  // API to update (Post)DominatorTree information based on modifications to
229  // the CFG...
230
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));
241  }
242
243  /// changeImmediateDominator - This method is used to update the dominator
244  /// tree information when a node's immediate dominator changes.
245  ///
246  void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
247    assert(N && NewIDom && "Cannot change null node pointers!");
248    DFSInfoValid = false;
249    N->setIDom(NewIDom);
250  }
251
252  void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
253    changeImmediateDominator(getNode(BB), getNode(NewBB));
254  }
255
256  /// removeNode - Removes a node from the dominator tree.  Block must not
257  /// dominate any other blocks.  Invalidates any node pointing to removed
258  /// block.
259  void removeNode(BasicBlock *BB) {
260    assert(getNode(BB) && "Removing node that isn't in dominator tree.");
261    DomTreeNodes.erase(BB);
262  }
263
264  /// print - Convert to human readable form
265  ///
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);
269  }
270  virtual void dump();
271};
272
273//===-------------------------------------
274/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
275/// compute a normal dominator tree.
276///
277class DominatorTree : public DominatorTreeBase {
278public:
279  static char ID; // Pass ID, replacement for typeid
280  DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
281
282  BasicBlock *getRoot() const {
283    assert(Roots.size() == 1 && "Should always have entry node!");
284    return Roots[0];
285  }
286
287  virtual bool runOnFunction(Function &F);
288
289  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
290    AU.setPreservesAll();
291  }
292
293  /// splitBlock
294  /// BB is split and now it has one successor. Update dominator tree to
295  /// reflect this change.
296  void splitBlock(BasicBlock *BB);
297private:
298  void calculate(Function& F);
299  DomTreeNode *getNodeForBlock(BasicBlock *BB);
300  unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
301  void Compress(BasicBlock *V);
302  BasicBlock *Eval(BasicBlock *v);
303  void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
304  inline BasicBlock *getIDom(BasicBlock *BB) const {
305      std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
306      return I != IDoms.end() ? I->second : 0;
307    }
308};
309
310//===-------------------------------------
311/// DominatorTree GraphTraits specialization so the DominatorTree can be
312/// iterable by generic graph iterators.
313///
314template <> struct GraphTraits<DomTreeNode*> {
315  typedef DomTreeNode NodeType;
316  typedef NodeType::iterator  ChildIteratorType;
317
318  static NodeType *getEntryNode(NodeType *N) {
319    return N;
320  }
321  static inline ChildIteratorType child_begin(NodeType* N) {
322    return N->begin();
323  }
324  static inline ChildIteratorType child_end(NodeType* N) {
325    return N->end();
326  }
327};
328
329template <> struct GraphTraits<DominatorTree*>
330  : public GraphTraits<DomTreeNode*> {
331  static NodeType *getEntryNode(DominatorTree *DT) {
332    return DT->getRootNode();
333  }
334};
335
336
337//===----------------------------------------------------------------------===//
338/// DominanceFrontierBase - Common base class for computing forward and inverse
339/// dominance frontiers for a function.
340///
341class DominanceFrontierBase : public DominatorBase {
342public:
343  typedef std::set<BasicBlock*>             DomSetType;    // Dom set for a bb
344  typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
345protected:
346  DomSetMapType Frontiers;
347public:
348  DominanceFrontierBase(intptr_t ID, bool isPostDom)
349    : DominatorBase(ID, isPostDom) {}
350
351  virtual void releaseMemory() { Frontiers.clear(); }
352
353  // Accessor interface:
354  typedef DomSetMapType::iterator iterator;
355  typedef DomSetMapType::const_iterator const_iterator;
356  iterator       begin()       { return Frontiers.begin(); }
357  const_iterator begin() const { return Frontiers.begin(); }
358  iterator       end()         { return Frontiers.end(); }
359  const_iterator end()   const { return Frontiers.end(); }
360  iterator       find(BasicBlock *B)       { return Frontiers.find(B); }
361  const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
362
363  void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
364    assert(find(BB) == end() && "Block already in DominanceFrontier!");
365    Frontiers.insert(std::make_pair(BB, frontier));
366  }
367
368  void addToFrontier(iterator I, BasicBlock *Node) {
369    assert(I != end() && "BB is not in DominanceFrontier!");
370    I->second.insert(Node);
371  }
372
373  void removeFromFrontier(iterator I, BasicBlock *Node) {
374    assert(I != end() && "BB is not in DominanceFrontier!");
375    assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
376    I->second.erase(Node);
377  }
378
379  /// print - Convert to human readable form
380  ///
381  virtual void print(std::ostream &OS, const Module* = 0) const;
382  void print(std::ostream *OS, const Module* M = 0) const {
383    if (OS) print(*OS, M);
384  }
385  virtual void dump();
386};
387
388
389//===-------------------------------------
390/// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
391/// used to compute a forward dominator frontiers.
392///
393class DominanceFrontier : public DominanceFrontierBase {
394public:
395  static char ID; // Pass ID, replacement for typeid
396  DominanceFrontier() :
397    DominanceFrontierBase((intptr_t)& ID, false) {}
398
399  BasicBlock *getRoot() const {
400    assert(Roots.size() == 1 && "Should always have entry node!");
401    return Roots[0];
402  }
403
404  virtual bool runOnFunction(Function &) {
405    Frontiers.clear();
406    DominatorTree &DT = getAnalysis<DominatorTree>();
407    Roots = DT.getRoots();
408    assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
409    calculate(DT, DT[Roots[0]]);
410    return false;
411  }
412
413  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
414    AU.setPreservesAll();
415    AU.addRequired<DominatorTree>();
416  }
417
418  /// splitBlock
419  /// BB is split and now it has one successor. Update dominace frontier to
420  /// reflect this change.
421  void splitBlock(BasicBlock *BB);
422
423private:
424  const DomSetType &calculate(const DominatorTree &DT,
425                              const DomTreeNode *Node);
426};
427
428
429} // End llvm namespace
430
431#endif
432