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. ETForest: Efficient data structure for dominance comparisons and
13 // nearest-common-ancestor queries.
14 // 3. DominanceFrontier: Calculate and hold the dominance frontier for a
17 // These data structures are listed in increasing order of complexity. It
18 // takes longer to calculate the dominator frontier, for example, than the
19 // DominatorTree mapping.
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_ANALYSIS_DOMINATORS_H
24 #define LLVM_ANALYSIS_DOMINATORS_H
26 #include "llvm/Analysis/ET-Forest.h"
27 #include "llvm/Pass.h"
34 template <typename GraphType> struct GraphTraits;
36 //===----------------------------------------------------------------------===//
37 /// DominatorBase - Base class that other, more interesting dominator analyses
40 class DominatorBase : public FunctionPass {
42 std::vector<BasicBlock*> Roots;
43 const bool IsPostDominators;
44 inline DominatorBase(intptr_t ID, bool isPostDom) :
45 FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {}
48 /// getRoots - Return the root blocks of the current CFG. This may include
49 /// multiple blocks if we are computing post dominators. For forward
50 /// dominators, this will always be a single block (the entry node).
52 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
54 /// isPostDominator - Returns true if analysis based of postdoms
56 bool isPostDominator() const { return IsPostDominators; }
60 //===----------------------------------------------------------------------===//
61 // DomTreeNode - Dominator Tree Node
64 friend class DominatorTree;
65 friend struct PostDominatorTree;
66 friend class DominatorTreeBase;
69 std::vector<DomTreeNode*> Children;
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 /// properlyDominates - Returns true iff this dominates N and this != N.
84 /// Note that this is not a constant time operation!
86 bool properlyDominates(const DomTreeNode *N) const {
87 const DomTreeNode *IDom;
88 if (this == 0 || N == 0) return false;
89 while ((IDom = N->getIDom()) != 0 && IDom != this)
90 N = IDom; // Walk up the tree
94 /// dominates - Returns true iff this dominates N. Note that this is not a
95 /// constant time operation!
97 inline bool dominates(const DomTreeNode *N) const {
98 if (N == this) return true; // A node trivially dominates itself.
99 return properlyDominates(N);
103 inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom) : TheBB(BB), IDom(iDom) {}
104 inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; }
106 void setIDom(DomTreeNode *NewIDom);
109 //===----------------------------------------------------------------------===//
110 /// DominatorTree - Calculate the immediate dominator tree for a function.
112 class DominatorTreeBase : public DominatorBase {
115 std::map<BasicBlock*, DomTreeNode*> DomTreeNodes;
117 typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType;
119 DomTreeNode *RootNode;
121 // Information record used during immediate dominators computation.
125 BasicBlock *Label, *Parent, *Child, *Ancestor;
127 std::vector<BasicBlock*> Bucket;
129 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
132 std::map<BasicBlock*, BasicBlock*> IDoms;
134 // Vertex - Map the DFS number to the BasicBlock*
135 std::vector<BasicBlock*> Vertex;
137 // Info - Collection of information used during the computation of idoms.
138 std::map<BasicBlock*, InfoRec> Info;
141 DominatorTreeBase(intptr_t ID, bool isPostDom)
142 : DominatorBase(ID, isPostDom) {}
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 //===--------------------------------------------------------------------===//
170 // API to update (Post)DominatorTree information based on modifications to
173 /// createNewNode - Add a new node to the dominator tree information. This
174 /// creates a new node as a child of IDomNode, linking it into the children
175 /// list of the immediate dominator.
177 DomTreeNode *createNewNode(BasicBlock *BB, DomTreeNode *IDomNode) {
178 assert(getNode(BB) == 0 && "Block already in dominator tree!");
179 assert(IDomNode && "Not immediate dominator specified for block!");
180 return DomTreeNodes[BB] = IDomNode->addChild(new DomTreeNode(BB, IDomNode));
183 void createNewNode(BasicBlock *BB, BasicBlock *DomBB) {
184 createNewNode(BB, getNode(DomBB));
187 /// changeImmediateDominator - This method is used to update the dominator
188 /// tree information when a node's immediate dominator changes.
190 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) {
191 assert(N && NewIDom && "Cannot change null node pointers!");
195 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) {
196 changeImmediateDominator(getNode(BB), getNode(NewBB));
200 /// removeNode - Removes a node from the dominator tree. Block must not
201 /// dominate any other blocks. Invalidates any node pointing to removed
203 void removeNode(BasicBlock *BB) {
204 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
205 DomTreeNodes.erase(BB);
208 /// print - Convert to human readable form
210 virtual void print(std::ostream &OS, const Module* = 0) const;
211 void print(std::ostream *OS, const Module* M = 0) const {
212 if (OS) print(*OS, M);
217 //===-------------------------------------
218 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
219 /// compute a normal dominator tree.
221 class DominatorTree : public DominatorTreeBase {
223 static char ID; // Pass ID, replacement for typeid
224 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
226 BasicBlock *getRoot() const {
227 assert(Roots.size() == 1 && "Should always have entry node!");
231 virtual bool runOnFunction(Function &F);
233 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
234 AU.setPreservesAll();
237 void calculate(Function& F);
238 DomTreeNode *getNodeForBlock(BasicBlock *BB);
239 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
240 void Compress(BasicBlock *V);
241 BasicBlock *Eval(BasicBlock *v);
242 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
243 inline BasicBlock *getIDom(BasicBlock *BB) const {
244 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
245 return I != IDoms.end() ? I->second : 0;
249 //===-------------------------------------
250 /// DominatorTree GraphTraits specialization so the DominatorTree can be
251 /// iterable by generic graph iterators.
253 template <> struct GraphTraits<DomTreeNode*> {
254 typedef DomTreeNode NodeType;
255 typedef NodeType::iterator ChildIteratorType;
257 static NodeType *getEntryNode(NodeType *N) {
260 static inline ChildIteratorType child_begin(NodeType* N) {
263 static inline ChildIteratorType child_end(NodeType* N) {
268 template <> struct GraphTraits<DominatorTree*>
269 : public GraphTraits<DomTreeNode*> {
270 static NodeType *getEntryNode(DominatorTree *DT) {
271 return DT->getRootNode();
276 //===-------------------------------------
277 /// ET-Forest Class - Class used to construct forwards and backwards
280 class ETForestBase : public DominatorBase {
282 ETForestBase(intptr_t ID, bool isPostDom)
283 : DominatorBase(ID, isPostDom), Nodes(),
284 DFSInfoValid(false), SlowQueries(0) {}
286 virtual void releaseMemory() { reset(); }
288 typedef std::map<BasicBlock*, ETNode*> ETMapType;
290 void updateDFSNumbers();
292 /// dominates - Return true if A dominates B.
294 inline bool dominates(BasicBlock *A, BasicBlock *B) {
298 ETNode *NodeA = getNode(A);
299 ETNode *NodeB = getNode(B);
302 return NodeB->DominatedBy(NodeA);
304 // If we end up with too many slow queries, just update the
305 // DFS numbers on the theory that we are going to keep querying.
307 if (SlowQueries > 32) {
309 return NodeB->DominatedBy(NodeA);
311 return NodeB->DominatedBySlow(NodeA);
315 // dominates - Return true if A dominates B. This performs the
316 // special checks necessary if A and B are in the same basic block.
317 bool dominates(Instruction *A, Instruction *B);
319 /// properlyDominates - Return true if A dominates B and A != B.
321 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
322 return dominates(A, B) && A != B;
325 /// isReachableFromEntry - Return true if A is dominated by the entry
326 /// block of the function containing it.
327 const bool isReachableFromEntry(BasicBlock* A);
329 /// Return the nearest common dominator of A and B.
330 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
331 ETNode *NodeA = getNode(A);
332 ETNode *NodeB = getNode(B);
334 ETNode *Common = NodeA->NCA(NodeB);
337 return Common->getData<BasicBlock>();
340 /// Return the immediate dominator of A.
341 BasicBlock *getIDom(BasicBlock *A) const {
342 ETNode *NodeA = getNode(A);
343 if (!NodeA) return 0;
344 const ETNode *idom = NodeA->getFather();
345 return idom ? idom->getData<BasicBlock>() : 0;
348 void getChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
349 ETNode *NodeA = getNode(A);
351 const ETNode* son = NodeA->getSon();
354 children.push_back(son->getData<BasicBlock>());
356 const ETNode* brother = son->getBrother();
357 while (brother != son) {
358 children.push_back(brother->getData<BasicBlock>());
359 brother = brother->getBrother();
363 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
364 AU.setPreservesAll();
365 AU.addRequired<DominatorTree>();
367 //===--------------------------------------------------------------------===//
368 // API to update Forest information based on modifications
371 /// addNewBlock - Add a new block to the CFG, with the specified immediate
374 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
376 /// setImmediateDominator - Update the immediate dominator information to
377 /// change the current immediate dominator for the specified block
378 /// to another block. This method requires that BB for NewIDom
379 /// already have an ETNode, otherwise just use addNewBlock.
381 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
382 /// print - Convert to human readable form
384 virtual void print(std::ostream &OS, const Module* = 0) const;
385 void print(std::ostream *OS, const Module* M = 0) const {
386 if (OS) print(*OS, M);
390 /// getNode - return the (Post)DominatorTree node for the specified basic
391 /// block. This is the same as using operator[] on this class.
393 inline ETNode *getNode(BasicBlock *BB) const {
394 ETMapType::const_iterator i = Nodes.find(BB);
395 return (i != Nodes.end()) ? i->second : 0;
398 inline ETNode *operator[](BasicBlock *BB) const {
405 unsigned int SlowQueries;
409 //==-------------------------------------
410 /// ETForest Class - Concrete subclass of ETForestBase that is used to
411 /// compute a forwards ET-Forest.
413 class ETForest : public ETForestBase {
415 static char ID; // Pass identification, replacement for typeid
417 ETForest() : ETForestBase((intptr_t)&ID, false) {}
419 BasicBlock *getRoot() const {
420 assert(Roots.size() == 1 && "Should always have entry node!");
424 virtual bool runOnFunction(Function &F) {
425 reset(); // Reset from the last time we were run...
426 DominatorTree &DT = getAnalysis<DominatorTree>();
427 Roots = DT.getRoots();
432 void calculate(const DominatorTree &DT);
433 ETNode *getNodeForBlock(BasicBlock *BB);
436 //===----------------------------------------------------------------------===//
437 /// DominanceFrontierBase - Common base class for computing forward and inverse
438 /// dominance frontiers for a function.
440 class DominanceFrontierBase : public DominatorBase {
442 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
443 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
445 DomSetMapType Frontiers;
447 DominanceFrontierBase(intptr_t ID, bool isPostDom)
448 : DominatorBase(ID, isPostDom) {}
450 virtual void releaseMemory() { Frontiers.clear(); }
452 // Accessor interface:
453 typedef DomSetMapType::iterator iterator;
454 typedef DomSetMapType::const_iterator const_iterator;
455 iterator begin() { return Frontiers.begin(); }
456 const_iterator begin() const { return Frontiers.begin(); }
457 iterator end() { return Frontiers.end(); }
458 const_iterator end() const { return Frontiers.end(); }
459 iterator find(BasicBlock *B) { return Frontiers.find(B); }
460 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
462 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
463 assert(find(BB) == end() && "Block already in DominanceFrontier!");
464 Frontiers.insert(std::make_pair(BB, frontier));
467 void addToFrontier(iterator I, BasicBlock *Node) {
468 assert(I != end() && "BB is not in DominanceFrontier!");
469 I->second.insert(Node);
472 void removeFromFrontier(iterator I, BasicBlock *Node) {
473 assert(I != end() && "BB is not in DominanceFrontier!");
474 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
475 I->second.erase(Node);
478 /// print - Convert to human readable form
480 virtual void print(std::ostream &OS, const Module* = 0) const;
481 void print(std::ostream *OS, const Module* M = 0) const {
482 if (OS) print(*OS, M);
488 //===-------------------------------------
489 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
490 /// used to compute a forward dominator frontiers.
492 class DominanceFrontier : public DominanceFrontierBase {
494 static char ID; // Pass ID, replacement for typeid
495 DominanceFrontier() :
496 DominanceFrontierBase((intptr_t)& ID, false) {}
498 BasicBlock *getRoot() const {
499 assert(Roots.size() == 1 && "Should always have entry node!");
503 virtual bool runOnFunction(Function &) {
505 DominatorTree &DT = getAnalysis<DominatorTree>();
506 Roots = DT.getRoots();
507 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
508 calculate(DT, DT[Roots[0]]);
512 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
513 AU.setPreservesAll();
514 AU.addRequired<DominatorTree>();
518 const DomSetType &calculate(const DominatorTree &DT,
519 const DomTreeNode *Node);
523 } // End llvm namespace