Implement the block_iterator of Region based on df_iterator.
[oota-llvm.git] / include / llvm / Analysis / RegionInfo.h
1 //===- RegionInfo.h - SESE region analysis ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Calculate a program structure tree built out of single entry single exit
11 // regions.
12 // The basic ideas are taken from "The Program Structure Tree - Richard Johnson,
13 // David Pearson, Keshav Pingali - 1994", however enriched with ideas from "The
14 // Refined Process Structure Tree - Jussi Vanhatalo, Hagen Voelyer, Jana
15 // Koehler - 2009".
16 // The algorithm to calculate these data structures however is completely
17 // different, as it takes advantage of existing information already available
18 // in (Post)dominace tree and dominance frontier passes. This leads to a simpler
19 // and in practice hopefully better performing algorithm. The runtime of the
20 // algorithms described in the papers above are both linear in graph size,
21 // O(V+E), whereas this algorithm is not, as the dominance frontier information
22 // itself is not, but in practice runtime seems to be in the order of magnitude
23 // of dominance tree calculation.
24 //
25 //===----------------------------------------------------------------------===//
26
27 #ifndef LLVM_ANALYSIS_REGION_INFO_H
28 #define LLVM_ANALYSIS_REGION_INFO_H
29
30 #include "llvm/ADT/PointerIntPair.h"
31 #include "llvm/Analysis/DominanceFrontier.h"
32 #include "llvm/Analysis/PostDominators.h"
33 #include "llvm/Support/Allocator.h"
34 #include <map>
35
36 namespace llvm {
37
38 class Region;
39 class RegionInfo;
40 class raw_ostream;
41 class Loop;
42 class LoopInfo;
43
44 /// @brief Marker class to iterate over the elements of a Region in flat mode.
45 ///
46 /// The class is used to either iterate in Flat mode or by not using it to not
47 /// iterate in Flat mode.  During a Flat mode iteration all Regions are entered
48 /// and the iteration returns every BasicBlock.  If the Flat mode is not
49 /// selected for SubRegions just one RegionNode containing the subregion is
50 /// returned.
51 template <class GraphType>
52 class FlatIt {};
53
54 /// @brief A RegionNode represents a subregion or a BasicBlock that is part of a
55 /// Region.
56 class RegionNode {
57   // DO NOT IMPLEMENT
58   RegionNode(const RegionNode &);
59   // DO NOT IMPLEMENT
60   const RegionNode &operator=(const RegionNode &);
61
62 protected:
63   /// This is the entry basic block that starts this region node.  If this is a
64   /// BasicBlock RegionNode, then entry is just the basic block, that this
65   /// RegionNode represents.  Otherwise it is the entry of this (Sub)RegionNode.
66   ///
67   /// In the BBtoRegionNode map of the parent of this node, BB will always map
68   /// to this node no matter which kind of node this one is.
69   ///
70   /// The node can hold either a Region or a BasicBlock.
71   /// Use one bit to save, if this RegionNode is a subregion or BasicBlock
72   /// RegionNode.
73   PointerIntPair<BasicBlock*, 1, bool> entry;
74
75   /// @brief The parent Region of this RegionNode.
76   /// @see getParent()
77   Region* parent;
78
79 public:
80   /// @brief Create a RegionNode.
81   ///
82   /// @param Parent      The parent of this RegionNode.
83   /// @param Entry       The entry BasicBlock of the RegionNode.  If this
84   ///                    RegionNode represents a BasicBlock, this is the
85   ///                    BasicBlock itself.  If it represents a subregion, this
86   ///                    is the entry BasicBlock of the subregion.
87   /// @param isSubRegion If this RegionNode represents a SubRegion.
88   inline RegionNode(Region* Parent, BasicBlock* Entry, bool isSubRegion = 0)
89     : entry(Entry, isSubRegion), parent(Parent) {}
90
91   /// @brief Get the parent Region of this RegionNode.
92   ///
93   /// The parent Region is the Region this RegionNode belongs to. If for
94   /// example a BasicBlock is element of two Regions, there exist two
95   /// RegionNodes for this BasicBlock. Each with the getParent() function
96   /// pointing to the Region this RegionNode belongs to.
97   ///
98   /// @return Get the parent Region of this RegionNode.
99   inline Region* getParent() const { return parent; }
100
101   /// @brief Get the entry BasicBlock of this RegionNode.
102   ///
103   /// If this RegionNode represents a BasicBlock this is just the BasicBlock
104   /// itself, otherwise we return the entry BasicBlock of the Subregion
105   ///
106   /// @return The entry BasicBlock of this RegionNode.
107   inline BasicBlock* getEntry() const { return entry.getPointer(); }
108
109   /// @brief Get the content of this RegionNode.
110   ///
111   /// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
112   /// check the type of the content with the isSubRegion() function call.
113   ///
114   /// @return The content of this RegionNode.
115   template<class T>
116   inline T* getNodeAs() const;
117
118   /// @brief Is this RegionNode a subregion?
119   ///
120   /// @return True if it contains a subregion. False if it contains a
121   ///         BasicBlock.
122   inline bool isSubRegion() const {
123     return entry.getInt();
124   }
125 };
126
127 /// Print a RegionNode.
128 inline raw_ostream &operator<<(raw_ostream &OS, const RegionNode &Node);
129
130 template<>
131 inline BasicBlock* RegionNode::getNodeAs<BasicBlock>() const {
132   assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
133   return getEntry();
134 }
135
136 template<>
137 inline Region* RegionNode::getNodeAs<Region>() const {
138   assert(isSubRegion() && "This is not a subregion RegionNode!");
139   return reinterpret_cast<Region*>(const_cast<RegionNode*>(this));
140 }
141
142 //===----------------------------------------------------------------------===//
143 /// @brief A single entry single exit Region.
144 ///
145 /// A Region is a connected subgraph of a control flow graph that has exactly
146 /// two connections to the remaining graph. It can be used to analyze or
147 /// optimize parts of the control flow graph.
148 ///
149 /// A <em> simple Region </em> is connected to the remaining graph by just two
150 /// edges. One edge entering the Region and another one leaving the Region.
151 ///
152 /// An <em> extended Region </em> (or just Region) is a subgraph that can be
153 /// transform into a simple Region. The transformation is done by adding
154 /// BasicBlocks that merge several entry or exit edges so that after the merge
155 /// just one entry and one exit edge exists.
156 ///
157 /// The \e Entry of a Region is the first BasicBlock that is passed after
158 /// entering the Region. It is an element of the Region. The entry BasicBlock
159 /// dominates all BasicBlocks in the Region.
160 ///
161 /// The \e Exit of a Region is the first BasicBlock that is passed after
162 /// leaving the Region. It is not an element of the Region. The exit BasicBlock,
163 /// postdominates all BasicBlocks in the Region.
164 ///
165 /// A <em> canonical Region </em> cannot be constructed by combining smaller
166 /// Regions.
167 ///
168 /// Region A is the \e parent of Region B, if B is completely contained in A.
169 ///
170 /// Two canonical Regions either do not intersect at all or one is
171 /// the parent of the other.
172 ///
173 /// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
174 /// Regions in the control flow graph and E is the \e parent relation of these
175 /// Regions.
176 ///
177 /// Example:
178 ///
179 /// \verbatim
180 /// A simple control flow graph, that contains two regions.
181 ///
182 ///        1
183 ///       / |
184 ///      2   |
185 ///     / \   3
186 ///    4   5  |
187 ///    |   |  |
188 ///    6   7  8
189 ///     \  | /
190 ///      \ |/       Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
191 ///        9        Region B: 2 -> 9 {2,4,5,6,7}
192 /// \endverbatim
193 ///
194 /// You can obtain more examples by either calling
195 ///
196 /// <tt> "opt -regions -analyze anyprogram.ll" </tt>
197 /// or
198 /// <tt> "opt -view-regions-only anyprogram.ll" </tt>
199 ///
200 /// on any LLVM file you are interested in.
201 ///
202 /// The first call returns a textual representation of the program structure
203 /// tree, the second one creates a graphical representation using graphviz.
204 class Region : public RegionNode {
205   friend class RegionInfo;
206   // DO NOT IMPLEMENT
207   Region(const Region &);
208   // DO NOT IMPLEMENT
209   const Region &operator=(const Region &);
210
211   // Information necessary to manage this Region.
212   RegionInfo* RI;
213   DominatorTree *DT;
214
215   // The exit BasicBlock of this region.
216   // (The entry BasicBlock is part of RegionNode)
217   BasicBlock *exit;
218
219   typedef std::vector<Region*> RegionSet;
220
221   // The subregions of this region.
222   RegionSet children;
223
224   typedef std::map<BasicBlock*, RegionNode*> BBNodeMapT;
225
226   // Save the BasicBlock RegionNodes that are element of this Region.
227   mutable BBNodeMapT BBNodeMap;
228
229   /// verifyBBInRegion - Check if a BB is in this Region. This check also works
230   /// if the region is incorrectly built. (EXPENSIVE!)
231   void verifyBBInRegion(BasicBlock* BB) const;
232
233   /// verifyWalk - Walk over all the BBs of the region starting from BB and
234   /// verify that all reachable basic blocks are elements of the region.
235   /// (EXPENSIVE!)
236   void verifyWalk(BasicBlock* BB, std::set<BasicBlock*>* visitedBB) const;
237
238   /// verifyRegionNest - Verify if the region and its children are valid
239   /// regions (EXPENSIVE!)
240   void verifyRegionNest() const;
241
242 public:
243   /// @brief Create a new region.
244   ///
245   /// @param Entry  The entry basic block of the region.
246   /// @param Exit   The exit basic block of the region.
247   /// @param RI     The region info object that is managing this region.
248   /// @param DT     The dominator tree of the current function.
249   /// @param Parent The surrounding region or NULL if this is a top level
250   ///               region.
251   Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RI,
252          DominatorTree *DT, Region *Parent = 0);
253
254   /// Delete the Region and all its subregions.
255   ~Region();
256
257   /// @brief Get the entry BasicBlock of the Region.
258   /// @return The entry BasicBlock of the region.
259   BasicBlock *getEntry() const { return RegionNode::getEntry(); }
260
261   /// @brief Replace the entry basic block of the region with the new basic
262   ///        block.
263   ///
264   /// @param BB  The new entry basic block of the region.
265   void replaceEntry(BasicBlock *BB);
266
267   /// @brief Replace the exit basic block of the region with the new basic
268   ///        block.
269   ///
270   /// @param BB  The new exit basic block of the region.
271   void replaceExit(BasicBlock *BB);
272
273   /// @brief Get the exit BasicBlock of the Region.
274   /// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
275   ///         Region.
276   BasicBlock *getExit() const { return exit; }
277
278   /// @brief Get the parent of the Region.
279   /// @return The parent of the Region or NULL if this is a top level
280   ///         Region.
281   Region *getParent() const { return RegionNode::getParent(); }
282
283   /// @brief Get the RegionNode representing the current Region.
284   /// @return The RegionNode representing the current Region.
285   RegionNode* getNode() const {
286     return const_cast<RegionNode*>(reinterpret_cast<const RegionNode*>(this));
287   }
288
289   /// @brief Get the nesting level of this Region.
290   ///
291   /// An toplevel Region has depth 0.
292   ///
293   /// @return The depth of the region.
294   unsigned getDepth() const;
295
296   /// @brief Check if a Region is the TopLevel region.
297   ///
298   /// The toplevel region represents the whole function.
299   bool isTopLevelRegion() const { return exit == NULL; }
300
301   /// @brief Return a new (non canonical) region, that is obtained by joining
302   ///        this region with its predecessors.
303   ///
304   /// @return A region also starting at getEntry(), but reaching to the next
305   ///         basic block that forms with getEntry() a (non canonical) region.
306   ///         NULL if such a basic block does not exist.
307   Region *getExpandedRegion() const;
308
309   /// @brief Return the first block of this region's single entry edge,
310   ///        if existing.
311   ///
312   /// @return The BasicBlock starting this region's single entry edge,
313   ///         else NULL.
314   BasicBlock *getEnteringBlock() const;
315
316   /// @brief Return the first block of this region's single exit edge,
317   ///        if existing.
318   ///
319   /// @return The BasicBlock starting this region's single exit edge,
320   ///         else NULL.
321   BasicBlock *getExitingBlock() const;
322
323   /// @brief Is this a simple region?
324   ///
325   /// A region is simple if it has exactly one exit and one entry edge.
326   ///
327   /// @return True if the Region is simple.
328   bool isSimple() const;
329
330   /// @brief Returns the name of the Region.
331   /// @return The Name of the Region.
332   std::string getNameStr() const;
333
334   /// @brief Return the RegionInfo object, that belongs to this Region.
335   RegionInfo *getRegionInfo() const {
336     return RI;
337   }
338
339   /// PrintStyle - Print region in difference ways.
340   enum PrintStyle { PrintNone, PrintBB, PrintRN  };
341
342   /// @brief Print the region.
343   ///
344   /// @param OS The output stream the Region is printed to.
345   /// @param printTree Print also the tree of subregions.
346   /// @param level The indentation level used for printing.
347   void print(raw_ostream& OS, bool printTree = true, unsigned level = 0,
348              enum PrintStyle Style = PrintNone) const;
349
350   /// @brief Print the region to stderr.
351   void dump() const;
352
353   /// @brief Check if the region contains a BasicBlock.
354   ///
355   /// @param BB The BasicBlock that might be contained in this Region.
356   /// @return True if the block is contained in the region otherwise false.
357   bool contains(const BasicBlock *BB) const;
358
359   /// @brief Check if the region contains another region.
360   ///
361   /// @param SubRegion The region that might be contained in this Region.
362   /// @return True if SubRegion is contained in the region otherwise false.
363   bool contains(const Region *SubRegion) const {
364     // Toplevel Region.
365     if (!getExit())
366       return true;
367
368     return contains(SubRegion->getEntry())
369       && (contains(SubRegion->getExit()) || SubRegion->getExit() == getExit());
370   }
371
372   /// @brief Check if the region contains an Instruction.
373   ///
374   /// @param Inst The Instruction that might be contained in this region.
375   /// @return True if the Instruction is contained in the region otherwise false.
376   bool contains(const Instruction *Inst) const {
377     return contains(Inst->getParent());
378   }
379
380   /// @brief Check if the region contains a loop.
381   ///
382   /// @param L The loop that might be contained in this region.
383   /// @return True if the loop is contained in the region otherwise false.
384   ///         In case a NULL pointer is passed to this function the result
385   ///         is false, except for the region that describes the whole function.
386   ///         In that case true is returned.
387   bool contains(const Loop *L) const;
388
389   /// @brief Get the outermost loop in the region that contains a loop.
390   ///
391   /// Find for a Loop L the outermost loop OuterL that is a parent loop of L
392   /// and is itself contained in the region.
393   ///
394   /// @param L The loop the lookup is started.
395   /// @return The outermost loop in the region, NULL if such a loop does not
396   ///         exist or if the region describes the whole function.
397   Loop *outermostLoopInRegion(Loop *L) const;
398
399   /// @brief Get the outermost loop in the region that contains a basic block.
400   ///
401   /// Find for a basic block BB the outermost loop L that contains BB and is
402   /// itself contained in the region.
403   ///
404   /// @param LI A pointer to a LoopInfo analysis.
405   /// @param BB The basic block surrounded by the loop.
406   /// @return The outermost loop in the region, NULL if such a loop does not
407   ///         exist or if the region describes the whole function.
408   Loop *outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const;
409
410   /// @brief Get the subregion that starts at a BasicBlock
411   ///
412   /// @param BB The BasicBlock the subregion should start.
413   /// @return The Subregion if available, otherwise NULL.
414   Region* getSubRegionNode(BasicBlock *BB) const;
415
416   /// @brief Get the RegionNode for a BasicBlock
417   ///
418   /// @param BB The BasicBlock at which the RegionNode should start.
419   /// @return If available, the RegionNode that represents the subregion
420   ///         starting at BB. If no subregion starts at BB, the RegionNode
421   ///         representing BB.
422   RegionNode* getNode(BasicBlock *BB) const;
423
424   /// @brief Get the BasicBlock RegionNode for a BasicBlock
425   ///
426   /// @param BB The BasicBlock for which the RegionNode is requested.
427   /// @return The RegionNode representing the BB.
428   RegionNode* getBBNode(BasicBlock *BB) const;
429
430   /// @brief Add a new subregion to this Region.
431   ///
432   /// @param SubRegion The new subregion that will be added.
433   /// @param moveChildren Move the children of this region, that are also
434   ///                     contained in SubRegion into SubRegion.
435   void addSubRegion(Region *SubRegion, bool moveChildren = false);
436
437   /// @brief Remove a subregion from this Region.
438   ///
439   /// The subregion is not deleted, as it will probably be inserted into another
440   /// region.
441   /// @param SubRegion The SubRegion that will be removed.
442   Region *removeSubRegion(Region *SubRegion);
443
444   /// @brief Move all direct child nodes of this Region to another Region.
445   ///
446   /// @param To The Region the child nodes will be transferred to.
447   void transferChildrenTo(Region *To);
448
449   /// @brief Verify if the region is a correct region.
450   ///
451   /// Check if this is a correctly build Region. This is an expensive check, as
452   /// the complete CFG of the Region will be walked.
453   void verifyRegion() const;
454
455   /// @brief Clear the cache for BB RegionNodes.
456   ///
457   /// After calling this function the BasicBlock RegionNodes will be stored at
458   /// different memory locations. RegionNodes obtained before this function is
459   /// called are therefore not comparable to RegionNodes abtained afterwords.
460   void clearNodeCache();
461
462   /// @name Subregion Iterators
463   ///
464   /// These iterators iterator over all subregions of this Region.
465   //@{
466   typedef RegionSet::iterator iterator;
467   typedef RegionSet::const_iterator const_iterator;
468
469   iterator begin() { return children.begin(); }
470   iterator end() { return children.end(); }
471
472   const_iterator begin() const { return children.begin(); }
473   const_iterator end() const { return children.end(); }
474   //@}
475
476   /// @name BasicBlock Node Iterators
477   ///
478   /// These iterators iterate over all BasicBlock RegionNodes that are
479   /// contained in this Region. The iterator also iterates over BasicBlock
480   /// RegionNodes that are elements of a subregion of this Region. It is
481   /// therefore called a flat iterator.
482   //@{
483   typedef df_iterator<RegionNode*, SmallPtrSet<RegionNode*, 8>, false,
484                       GraphTraits<FlatIt<RegionNode*> > > block_node_iterator;
485
486   typedef df_iterator<const RegionNode*, SmallPtrSet<const RegionNode*, 8>,
487                       false, GraphTraits<FlatIt<const RegionNode*> > >
488             const_block_node_iterator;
489
490   block_node_iterator block_node_begin();
491   block_node_iterator block_node_end();
492
493   const_block_node_iterator block_node_begin() const;
494   const_block_node_iterator block_node_end() const;
495   //@}
496
497   /// @name BasicBlock Iterators
498   ///
499   /// These iterators iterate over all BasicBlocks that are contained in this
500   /// Region. The iterator also iterates over BasicBlocks that are elements of
501   /// a subregion of this Region. It is therefore called a flat iterator.
502   //@{
503   template <bool IsConst>
504   class block_iterator_wrapper
505     : public df_iterator<typename conditional<IsConst,
506                                               const BasicBlock,
507                                               BasicBlock>::type*> {
508     typedef df_iterator<typename conditional<IsConst,
509                                              const BasicBlock,
510                                              BasicBlock>::type*>
511       super;
512   public:
513     typedef block_iterator_wrapper<IsConst> Self;
514     typedef typename super::pointer pointer;
515
516     // Construct the begin iterator.
517     block_iterator_wrapper(pointer Entry, pointer Exit) : super(df_begin(Entry))
518     {
519       // Mark the exit of the region as visited, so that the children of the
520       // exit and the exit itself, i.e. the block outside the region will never
521       // be visited.
522       super::Visited.insert(Exit);
523     }
524
525     // Construct the end iterator.
526     block_iterator_wrapper() : super(df_end<pointer>(0)) {}
527
528     /*implicit*/ block_iterator_wrapper(super I) : super(I) {}
529
530     // FIXME: Even a const_iterator returns a non-const BasicBlock pointer.
531     //        This was introduced for backwards compatibility, but should
532     //        be removed as soon as all users are fixed.
533     BasicBlock *operator*() const {
534       return const_cast<BasicBlock*>(super::operator*());
535     }
536   };
537
538   typedef block_iterator_wrapper<false> block_iterator;
539   typedef block_iterator_wrapper<true>  const_block_iterator;
540
541   block_iterator block_begin() {
542    return block_iterator(getEntry(), getExit());
543   }
544
545   block_iterator block_end() {
546    return block_iterator();
547   }
548
549   const_block_iterator block_begin() const {
550     return const_block_iterator(getEntry(), getExit());
551   }
552   const_block_iterator block_end() const {
553     return const_block_iterator();
554   }
555   //@}
556
557   /// @name Element Iterators
558   ///
559   /// These iterators iterate over all BasicBlock and subregion RegionNodes that
560   /// are direct children of this Region. It does not iterate over any
561   /// RegionNodes that are also element of a subregion of this Region.
562   //@{
563   typedef df_iterator<RegionNode*, SmallPtrSet<RegionNode*, 8>, false,
564                       GraphTraits<RegionNode*> > element_iterator;
565
566   typedef df_iterator<const RegionNode*, SmallPtrSet<const RegionNode*, 8>,
567                       false, GraphTraits<const RegionNode*> >
568             const_element_iterator;
569
570   element_iterator element_begin();
571   element_iterator element_end();
572
573   const_element_iterator element_begin() const;
574   const_element_iterator element_end() const;
575   //@}
576 };
577
578 //===----------------------------------------------------------------------===//
579 /// @brief Analysis that detects all canonical Regions.
580 ///
581 /// The RegionInfo pass detects all canonical regions in a function. The Regions
582 /// are connected using the parent relation. This builds a Program Structure
583 /// Tree.
584 class RegionInfo : public FunctionPass {
585   typedef DenseMap<BasicBlock*,BasicBlock*> BBtoBBMap;
586   typedef DenseMap<BasicBlock*, Region*> BBtoRegionMap;
587   typedef SmallPtrSet<Region*, 4> RegionSet;
588
589   // DO NOT IMPLEMENT
590   RegionInfo(const RegionInfo &);
591   // DO NOT IMPLEMENT
592   const RegionInfo &operator=(const RegionInfo &);
593
594   DominatorTree *DT;
595   PostDominatorTree *PDT;
596   DominanceFrontier *DF;
597
598   /// The top level region.
599   Region *TopLevelRegion;
600
601   /// Map every BB to the smallest region, that contains BB.
602   BBtoRegionMap BBtoRegion;
603
604   // isCommonDomFrontier - Returns true if BB is in the dominance frontier of
605   // entry, because it was inherited from exit. In the other case there is an
606   // edge going from entry to BB without passing exit.
607   bool isCommonDomFrontier(BasicBlock* BB, BasicBlock* entry,
608                            BasicBlock* exit) const;
609
610   // isRegion - Check if entry and exit surround a valid region, based on
611   // dominance tree and dominance frontier.
612   bool isRegion(BasicBlock* entry, BasicBlock* exit) const;
613
614   // insertShortCut - Saves a shortcut pointing from entry to exit.
615   // This function may extend this shortcut if possible.
616   void insertShortCut(BasicBlock* entry, BasicBlock* exit,
617                       BBtoBBMap* ShortCut) const;
618
619   // getNextPostDom - Returns the next BB that postdominates N, while skipping
620   // all post dominators that cannot finish a canonical region.
621   DomTreeNode *getNextPostDom(DomTreeNode* N, BBtoBBMap *ShortCut) const;
622
623   // isTrivialRegion - A region is trivial, if it contains only one BB.
624   bool isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const;
625
626   // createRegion - Creates a single entry single exit region.
627   Region *createRegion(BasicBlock *entry, BasicBlock *exit);
628
629   // findRegionsWithEntry - Detect all regions starting with bb 'entry'.
630   void findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut);
631
632   // scanForRegions - Detects regions in F.
633   void scanForRegions(Function &F, BBtoBBMap *ShortCut);
634
635   // getTopMostParent - Get the top most parent with the same entry block.
636   Region *getTopMostParent(Region *region);
637
638   // buildRegionsTree - build the region hierarchy after all region detected.
639   void buildRegionsTree(DomTreeNode *N, Region *region);
640
641   // Calculate - detecte all regions in function and build the region tree.
642   void Calculate(Function& F);
643
644   void releaseMemory();
645
646   // updateStatistics - Update statistic about created regions.
647   void updateStatistics(Region *R);
648
649   // isSimple - Check if a region is a simple region with exactly one entry
650   // edge and exactly one exit edge.
651   bool isSimple(Region* R) const;
652
653 public:
654   static char ID;
655   explicit RegionInfo();
656
657   ~RegionInfo();
658
659   /// @name FunctionPass interface
660   //@{
661   virtual bool runOnFunction(Function &F);
662   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
663   virtual void print(raw_ostream &OS, const Module *) const;
664   virtual void verifyAnalysis() const;
665   //@}
666
667   /// @brief Get the smallest region that contains a BasicBlock.
668   ///
669   /// @param BB The basic block.
670   /// @return The smallest region, that contains BB or NULL, if there is no
671   /// region containing BB.
672   Region *getRegionFor(BasicBlock *BB) const;
673
674   /// @brief  Set the smallest region that surrounds a basic block.
675   ///
676   /// @param BB The basic block surrounded by a region.
677   /// @param R The smallest region that surrounds BB.
678   void setRegionFor(BasicBlock *BB, Region *R);
679
680   /// @brief A shortcut for getRegionFor().
681   ///
682   /// @param BB The basic block.
683   /// @return The smallest region, that contains BB or NULL, if there is no
684   /// region containing BB.
685   Region *operator[](BasicBlock *BB) const;
686
687   /// @brief Return the exit of the maximal refined region, that starts at a
688   /// BasicBlock.
689   ///
690   /// @param BB The BasicBlock the refined region starts.
691   BasicBlock *getMaxRegionExit(BasicBlock *BB) const;
692
693   /// @brief Find the smallest region that contains two regions.
694   ///
695   /// @param A The first region.
696   /// @param B The second region.
697   /// @return The smallest region containing A and B.
698   Region *getCommonRegion(Region* A, Region *B) const;
699
700   /// @brief Find the smallest region that contains two basic blocks.
701   ///
702   /// @param A The first basic block.
703   /// @param B The second basic block.
704   /// @return The smallest region that contains A and B.
705   Region* getCommonRegion(BasicBlock* A, BasicBlock *B) const {
706     return getCommonRegion(getRegionFor(A), getRegionFor(B));
707   }
708
709   /// @brief Find the smallest region that contains a set of regions.
710   ///
711   /// @param Regions A vector of regions.
712   /// @return The smallest region that contains all regions in Regions.
713   Region* getCommonRegion(SmallVectorImpl<Region*> &Regions) const;
714
715   /// @brief Find the smallest region that contains a set of basic blocks.
716   ///
717   /// @param BBs A vector of basic blocks.
718   /// @return The smallest region that contains all basic blocks in BBS.
719   Region* getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const;
720
721   Region *getTopLevelRegion() const {
722     return TopLevelRegion;
723   }
724
725   /// @brief Update RegionInfo after a basic block was split.
726   ///
727   /// @param NewBB The basic block that was created before OldBB.
728   /// @param OldBB The old basic block.
729   void splitBlock(BasicBlock* NewBB, BasicBlock *OldBB);
730
731   /// @brief Clear the Node Cache for all Regions.
732   ///
733   /// @see Region::clearNodeCache()
734   void clearNodeCache() {
735     if (TopLevelRegion)
736       TopLevelRegion->clearNodeCache();
737   }
738 };
739
740 inline raw_ostream &operator<<(raw_ostream &OS, const RegionNode &Node) {
741   if (Node.isSubRegion())
742     return OS << Node.getNodeAs<Region>()->getNameStr();
743   else
744     return OS << Node.getNodeAs<BasicBlock>()->getName();
745 }
746 } // End llvm namespace
747 #endif
748