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; }
59 //===----------------------------------------------------------------------===//
60 /// DominatorTree - Calculate the immediate dominator tree for a function.
62 class DominatorTreeBase : public DominatorBase {
66 std::map<BasicBlock*, Node*> Nodes;
68 typedef std::map<BasicBlock*, Node*> NodeMapType;
75 BasicBlock *Label, *Parent, *Child, *Ancestor;
77 std::vector<BasicBlock*> Bucket;
79 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
82 std::map<BasicBlock*, BasicBlock*> IDoms;
84 // Vertex - Map the DFS number to the BasicBlock*
85 std::vector<BasicBlock*> Vertex;
87 // Info - Collection of information used during the computation of idoms.
88 std::map<BasicBlock*, InfoRec> Info;
92 friend class DominatorTree;
93 friend struct PostDominatorTree;
94 friend class DominatorTreeBase;
97 std::vector<Node*> Children;
99 typedef std::vector<Node*>::iterator iterator;
100 typedef std::vector<Node*>::const_iterator const_iterator;
102 iterator begin() { return Children.begin(); }
103 iterator end() { return Children.end(); }
104 const_iterator begin() const { return Children.begin(); }
105 const_iterator end() const { return Children.end(); }
107 inline BasicBlock *getBlock() const { return TheBB; }
108 inline Node *getIDom() const { return IDom; }
109 inline const std::vector<Node*> &getChildren() const { return Children; }
111 /// properlyDominates - Returns true iff this dominates N and this != N.
112 /// Note that this is not a constant time operation!
114 bool properlyDominates(const Node *N) const {
116 if (this == 0 || N == 0) return false;
117 while ((IDom = N->getIDom()) != 0 && IDom != this)
118 N = IDom; // Walk up the tree
122 /// dominates - Returns true iff this dominates N. Note that this is not a
123 /// constant time operation!
125 inline bool dominates(const Node *N) const {
126 if (N == this) return true; // A node trivially dominates itself.
127 return properlyDominates(N);
131 inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
132 inline Node *addChild(Node *C) { Children.push_back(C); return C; }
134 void setIDom(Node *NewIDom);
138 DominatorTreeBase(intptr_t ID, bool isPostDom)
139 : DominatorBase(ID, isPostDom) {}
140 ~DominatorTreeBase() { reset(); }
142 virtual void releaseMemory() { reset(); }
144 /// getNode - return the (Post)DominatorTree node for the specified basic
145 /// block. This is the same as using operator[] on this class.
147 inline Node *getNode(BasicBlock *BB) const {
148 NodeMapType::const_iterator i = Nodes.find(BB);
149 return (i != Nodes.end()) ? i->second : 0;
152 inline Node *operator[](BasicBlock *BB) const {
156 /// getRootNode - This returns the entry node for the CFG of the function. If
157 /// this tree represents the post-dominance relations for a function, however,
158 /// this root may be a node with the block == NULL. This is the case when
159 /// there are multiple exit nodes from a particular function. Consumers of
160 /// post-dominance information must be capable of dealing with this
163 Node *getRootNode() { return RootNode; }
164 const Node *getRootNode() const { return RootNode; }
166 //===--------------------------------------------------------------------===//
167 // API to update (Post)DominatorTree information based on modifications to
170 /// createNewNode - Add a new node to the dominator tree information. This
171 /// creates a new node as a child of IDomNode, linking it into the children
172 /// list of the immediate dominator.
174 Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
175 assert(getNode(BB) == 0 && "Block already in dominator tree!");
176 assert(IDomNode && "Not immediate dominator specified for block!");
177 return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
180 /// changeImmediateDominator - This method is used to update the dominator
181 /// tree information when a node's immediate dominator changes.
183 void changeImmediateDominator(Node *N, Node *NewIDom) {
184 assert(N && NewIDom && "Cannot change null node pointers!");
188 /// removeNode - Removes a node from the dominator tree. Block must not
189 /// dominate any other blocks. Invalidates any node pointing to removed
191 void removeNode(BasicBlock *BB) {
192 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
196 /// print - Convert to human readable form
198 virtual void print(std::ostream &OS, const Module* = 0) const;
199 void print(std::ostream *OS, const Module* M = 0) const {
200 if (OS) print(*OS, M);
205 //===-------------------------------------
206 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
207 /// compute a normal dominator tree.
209 class DominatorTree : public DominatorTreeBase {
211 static char ID; // Pass ID, replacement for typeid
212 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {}
214 BasicBlock *getRoot() const {
215 assert(Roots.size() == 1 && "Should always have entry node!");
219 virtual bool runOnFunction(Function &F);
221 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
222 AU.setPreservesAll();
225 void calculate(Function& F);
226 Node *getNodeForBlock(BasicBlock *BB);
227 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
228 void Compress(BasicBlock *V);
229 BasicBlock *Eval(BasicBlock *v);
230 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
231 inline BasicBlock *getIDom(BasicBlock *BB) const {
232 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
233 return I != IDoms.end() ? I->second : 0;
237 //===-------------------------------------
238 /// DominatorTree GraphTraits specialization so the DominatorTree can be
239 /// iterable by generic graph iterators.
241 template <> struct GraphTraits<DominatorTree::Node*> {
242 typedef DominatorTree::Node NodeType;
243 typedef NodeType::iterator ChildIteratorType;
245 static NodeType *getEntryNode(NodeType *N) {
248 static inline ChildIteratorType child_begin(NodeType* N) {
251 static inline ChildIteratorType child_end(NodeType* N) {
256 template <> struct GraphTraits<DominatorTree*>
257 : public GraphTraits<DominatorTree::Node*> {
258 static NodeType *getEntryNode(DominatorTree *DT) {
259 return DT->getRootNode();
264 //===-------------------------------------
265 /// ET-Forest Class - Class used to construct forwards and backwards
268 class ETForestBase : public DominatorBase {
270 ETForestBase(intptr_t ID, bool isPostDom)
271 : DominatorBase(ID, isPostDom), Nodes(),
272 DFSInfoValid(false), SlowQueries(0) {}
274 virtual void releaseMemory() { reset(); }
276 typedef std::map<BasicBlock*, ETNode*> ETMapType;
278 void updateDFSNumbers();
280 /// dominates - Return true if A dominates B.
282 inline bool dominates(BasicBlock *A, BasicBlock *B) {
286 ETNode *NodeA = getNode(A);
287 ETNode *NodeB = getNode(B);
290 return NodeB->DominatedBy(NodeA);
292 // If we end up with too many slow queries, just update the
293 // DFS numbers on the theory that we are going to keep querying.
295 if (SlowQueries > 32) {
297 return NodeB->DominatedBy(NodeA);
299 return NodeB->DominatedBySlow(NodeA);
303 // dominates - Return true if A dominates B. This performs the
304 // special checks necessary if A and B are in the same basic block.
305 bool dominates(Instruction *A, Instruction *B);
307 /// properlyDominates - Return true if A dominates B and A != B.
309 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
310 return dominates(A, B) && A != B;
313 /// isReachableFromEntry - Return true if A is dominated by the entry
314 /// block of the function containing it.
315 const bool isReachableFromEntry(BasicBlock* A);
317 /// Return the nearest common dominator of A and B.
318 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
319 ETNode *NodeA = getNode(A);
320 ETNode *NodeB = getNode(B);
322 ETNode *Common = NodeA->NCA(NodeB);
325 return Common->getData<BasicBlock>();
328 /// Return the immediate dominator of A.
329 BasicBlock *getIDom(BasicBlock *A) const {
330 ETNode *NodeA = getNode(A);
331 if (!NodeA) return 0;
332 const ETNode *idom = NodeA->getFather();
333 return idom ? idom->getData<BasicBlock>() : 0;
336 void getChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const {
337 ETNode *NodeA = getNode(A);
339 const ETNode* son = NodeA->getSon();
342 children.push_back(son->getData<BasicBlock>());
344 const ETNode* brother = son->getBrother();
345 while (brother != son) {
346 children.push_back(brother->getData<BasicBlock>());
347 brother = brother->getBrother();
351 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
352 AU.setPreservesAll();
353 AU.addRequired<DominatorTree>();
355 //===--------------------------------------------------------------------===//
356 // API to update Forest information based on modifications
359 /// addNewBlock - Add a new block to the CFG, with the specified immediate
362 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
364 /// setImmediateDominator - Update the immediate dominator information to
365 /// change the current immediate dominator for the specified block
366 /// to another block. This method requires that BB for NewIDom
367 /// already have an ETNode, otherwise just use addNewBlock.
369 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
370 /// print - Convert to human readable form
372 virtual void print(std::ostream &OS, const Module* = 0) const;
373 void print(std::ostream *OS, const Module* M = 0) const {
374 if (OS) print(*OS, M);
378 /// getNode - return the (Post)DominatorTree node for the specified basic
379 /// block. This is the same as using operator[] on this class.
381 inline ETNode *getNode(BasicBlock *BB) const {
382 ETMapType::const_iterator i = Nodes.find(BB);
383 return (i != Nodes.end()) ? i->second : 0;
386 inline ETNode *operator[](BasicBlock *BB) const {
393 unsigned int SlowQueries;
397 //==-------------------------------------
398 /// ETForest Class - Concrete subclass of ETForestBase that is used to
399 /// compute a forwards ET-Forest.
401 class ETForest : public ETForestBase {
403 static char ID; // Pass identification, replacement for typeid
405 ETForest() : ETForestBase((intptr_t)&ID, false) {}
407 BasicBlock *getRoot() const {
408 assert(Roots.size() == 1 && "Should always have entry node!");
412 virtual bool runOnFunction(Function &F) {
413 reset(); // Reset from the last time we were run...
414 DominatorTree &DT = getAnalysis<DominatorTree>();
415 Roots = DT.getRoots();
420 void calculate(const DominatorTree &DT);
421 ETNode *getNodeForBlock(BasicBlock *BB);
424 //===----------------------------------------------------------------------===//
425 /// DominanceFrontierBase - Common base class for computing forward and inverse
426 /// dominance frontiers for a function.
428 class DominanceFrontierBase : public DominatorBase {
430 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
431 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
433 DomSetMapType Frontiers;
435 DominanceFrontierBase(intptr_t ID, bool isPostDom)
436 : DominatorBase(ID, isPostDom) {}
438 virtual void releaseMemory() { Frontiers.clear(); }
440 // Accessor interface:
441 typedef DomSetMapType::iterator iterator;
442 typedef DomSetMapType::const_iterator const_iterator;
443 iterator begin() { return Frontiers.begin(); }
444 const_iterator begin() const { return Frontiers.begin(); }
445 iterator end() { return Frontiers.end(); }
446 const_iterator end() const { return Frontiers.end(); }
447 iterator find(BasicBlock *B) { return Frontiers.find(B); }
448 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
450 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
451 assert(find(BB) == end() && "Block already in DominanceFrontier!");
452 Frontiers.insert(std::make_pair(BB, frontier));
455 void addToFrontier(iterator I, BasicBlock *Node) {
456 assert(I != end() && "BB is not in DominanceFrontier!");
457 I->second.insert(Node);
460 void removeFromFrontier(iterator I, BasicBlock *Node) {
461 assert(I != end() && "BB is not in DominanceFrontier!");
462 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
463 I->second.erase(Node);
466 /// print - Convert to human readable form
468 virtual void print(std::ostream &OS, const Module* = 0) const;
469 void print(std::ostream *OS, const Module* M = 0) const {
470 if (OS) print(*OS, M);
476 //===-------------------------------------
477 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
478 /// used to compute a forward dominator frontiers.
480 class DominanceFrontier : public DominanceFrontierBase {
482 static char ID; // Pass ID, replacement for typeid
483 DominanceFrontier() :
484 DominanceFrontierBase((intptr_t)& ID, false) {}
486 BasicBlock *getRoot() const {
487 assert(Roots.size() == 1 && "Should always have entry node!");
491 virtual bool runOnFunction(Function &) {
493 DominatorTree &DT = getAnalysis<DominatorTree>();
494 Roots = DT.getRoots();
495 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
496 calculate(DT, DT[Roots[0]]);
500 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
501 AU.setPreservesAll();
502 AU.addRequired<DominatorTree>();
505 const DomSetType &calculate(const DominatorTree &DT,
506 const DominatorTree::Node *Node);
510 } // End llvm namespace