1 //===- RegionInfo.h - SESE region analysis ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Calculate a program structure tree built out of single entry single exit
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
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.
25 // WARNING: LLVM is generally very concerned about compile time such that
26 // the use of additional analysis passes in the default
27 // optimization sequence is avoided as much as possible.
28 // Specifically, if you do not need the RegionInfo, but dominance
29 // information could be sufficient please base your work only on
30 // the dominator tree. Most passes maintain it, such that using
31 // it has often near zero cost. In contrast RegionInfo is by
32 // default not available, is not maintained by existing
33 // transformations and there is no intention to do so.
35 //===----------------------------------------------------------------------===//
37 #ifndef LLVM_ANALYSIS_REGIONINFO_H
38 #define LLVM_ANALYSIS_REGIONINFO_H
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/DepthFirstIterator.h"
42 #include "llvm/ADT/GraphTraits.h"
43 #include "llvm/ADT/PointerIntPair.h"
44 #include "llvm/ADT/iterator_range.h"
45 #include "llvm/Config/llvm-config.h"
46 #include "llvm/IR/BasicBlock.h"
47 #include "llvm/IR/Dominators.h"
48 #include "llvm/IR/PassManager.h"
49 #include "llvm/Pass.h"
50 #include "llvm/Support/raw_ostream.h"
57 #include <type_traits>
62 class DominanceFrontier;
66 class PostDominatorTree;
68 template <class RegionTr> class RegionBase;
70 template <class RegionTr> class RegionInfoBase;
73 // Class to be specialized for different users of RegionInfo
74 // (i.e. BasicBlocks or MachineBasicBlocks). This is only to avoid needing to
75 // pass around an unreasonable number of template parameters.
76 template <class FuncT_>
83 using BrokenT = typename FuncT_::UnknownRegionTypeError;
87 struct RegionTraits<Function> {
88 using FuncT = Function;
89 using BlockT = BasicBlock;
90 using RegionT = Region;
91 using RegionNodeT = RegionNode;
92 using RegionInfoT = RegionInfo;
93 using DomTreeT = DominatorTree;
94 using DomTreeNodeT = DomTreeNode;
95 using DomFrontierT = DominanceFrontier;
96 using PostDomTreeT = PostDominatorTree;
97 using InstT = Instruction;
99 using LoopInfoT = LoopInfo;
101 static unsigned getNumSuccessors(BasicBlock *BB) {
102 return BB->getTerminator()->getNumSuccessors();
106 /// Marker class to iterate over the elements of a Region in flat mode.
108 /// The class is used to either iterate in Flat mode or by not using it to not
109 /// iterate in Flat mode. During a Flat mode iteration all Regions are entered
110 /// and the iteration returns every BasicBlock. If the Flat mode is not
111 /// selected for SubRegions just one RegionNode containing the subregion is
113 template <class GraphType>
116 /// A RegionNode represents a subregion or a BasicBlock that is part of a
119 class RegionNodeBase {
120 friend class RegionBase<Tr>;
123 using BlockT = typename Tr::BlockT;
124 using RegionT = typename Tr::RegionT;
127 /// This is the entry basic block that starts this region node. If this is a
128 /// BasicBlock RegionNode, then entry is just the basic block, that this
129 /// RegionNode represents. Otherwise it is the entry of this (Sub)RegionNode.
131 /// In the BBtoRegionNode map of the parent of this node, BB will always map
132 /// to this node no matter which kind of node this one is.
134 /// The node can hold either a Region or a BasicBlock.
135 /// Use one bit to save, if this RegionNode is a subregion or BasicBlock
137 PointerIntPair<BlockT *, 1, bool> entry;
139 /// The parent Region of this RegionNode.
144 /// Create a RegionNode.
146 /// @param Parent The parent of this RegionNode.
147 /// @param Entry The entry BasicBlock of the RegionNode. If this
148 /// RegionNode represents a BasicBlock, this is the
149 /// BasicBlock itself. If it represents a subregion, this
150 /// is the entry BasicBlock of the subregion.
151 /// @param isSubRegion If this RegionNode represents a SubRegion.
152 inline RegionNodeBase(RegionT *Parent, BlockT *Entry,
153 bool isSubRegion = false)
154 : entry(Entry, isSubRegion), parent(Parent) {}
157 RegionNodeBase(const RegionNodeBase &) = delete;
158 RegionNodeBase &operator=(const RegionNodeBase &) = delete;
160 /// Get the parent Region of this RegionNode.
162 /// The parent Region is the Region this RegionNode belongs to. If for
163 /// example a BasicBlock is element of two Regions, there exist two
164 /// RegionNodes for this BasicBlock. Each with the getParent() function
165 /// pointing to the Region this RegionNode belongs to.
167 /// @return Get the parent Region of this RegionNode.
168 inline RegionT *getParent() const { return parent; }
170 /// Get the entry BasicBlock of this RegionNode.
172 /// If this RegionNode represents a BasicBlock this is just the BasicBlock
173 /// itself, otherwise we return the entry BasicBlock of the Subregion
175 /// @return The entry BasicBlock of this RegionNode.
176 inline BlockT *getEntry() const { return entry.getPointer(); }
178 /// Get the content of this RegionNode.
180 /// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
181 /// check the type of the content with the isSubRegion() function call.
183 /// @return The content of this RegionNode.
184 template <class T> inline T *getNodeAs() const;
186 /// Is this RegionNode a subregion?
188 /// @return True if it contains a subregion. False if it contains a
190 inline bool isSubRegion() const { return entry.getInt(); }
193 //===----------------------------------------------------------------------===//
194 /// A single entry single exit Region.
196 /// A Region is a connected subgraph of a control flow graph that has exactly
197 /// two connections to the remaining graph. It can be used to analyze or
198 /// optimize parts of the control flow graph.
200 /// A <em> simple Region </em> is connected to the remaining graph by just two
201 /// edges. One edge entering the Region and another one leaving the Region.
203 /// An <em> extended Region </em> (or just Region) is a subgraph that can be
204 /// transform into a simple Region. The transformation is done by adding
205 /// BasicBlocks that merge several entry or exit edges so that after the merge
206 /// just one entry and one exit edge exists.
208 /// The \e Entry of a Region is the first BasicBlock that is passed after
209 /// entering the Region. It is an element of the Region. The entry BasicBlock
210 /// dominates all BasicBlocks in the Region.
212 /// The \e Exit of a Region is the first BasicBlock that is passed after
213 /// leaving the Region. It is not an element of the Region. The exit BasicBlock,
214 /// postdominates all BasicBlocks in the Region.
216 /// A <em> canonical Region </em> cannot be constructed by combining smaller
219 /// Region A is the \e parent of Region B, if B is completely contained in A.
221 /// Two canonical Regions either do not intersect at all or one is
222 /// the parent of the other.
224 /// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
225 /// Regions in the control flow graph and E is the \e parent relation of these
231 /// A simple control flow graph, that contains two regions.
241 /// \ |/ Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
242 /// 9 Region B: 2 -> 9 {2,4,5,6,7}
245 /// You can obtain more examples by either calling
247 /// <tt> "opt -regions -analyze anyprogram.ll" </tt>
249 /// <tt> "opt -view-regions-only anyprogram.ll" </tt>
251 /// on any LLVM file you are interested in.
253 /// The first call returns a textual representation of the program structure
254 /// tree, the second one creates a graphical representation using graphviz.
256 class RegionBase : public RegionNodeBase<Tr> {
257 friend class RegionInfoBase<Tr>;
259 using FuncT = typename Tr::FuncT;
260 using BlockT = typename Tr::BlockT;
261 using RegionInfoT = typename Tr::RegionInfoT;
262 using RegionT = typename Tr::RegionT;
263 using RegionNodeT = typename Tr::RegionNodeT;
264 using DomTreeT = typename Tr::DomTreeT;
265 using LoopT = typename Tr::LoopT;
266 using LoopInfoT = typename Tr::LoopInfoT;
267 using InstT = typename Tr::InstT;
269 using BlockTraits = GraphTraits<BlockT *>;
270 using InvBlockTraits = GraphTraits<Inverse<BlockT *>>;
271 using SuccIterTy = typename BlockTraits::ChildIteratorType;
272 using PredIterTy = typename InvBlockTraits::ChildIteratorType;
274 // Information necessary to manage this Region.
278 // The exit BasicBlock of this region.
279 // (The entry BasicBlock is part of RegionNode)
282 using RegionSet = std::vector<std::unique_ptr<RegionT>>;
284 // The subregions of this region.
287 using BBNodeMapT = std::map<BlockT *, std::unique_ptr<RegionNodeT>>;
289 // Save the BasicBlock RegionNodes that are element of this Region.
290 mutable BBNodeMapT BBNodeMap;
292 /// Check if a BB is in this Region. This check also works
293 /// if the region is incorrectly built. (EXPENSIVE!)
294 void verifyBBInRegion(BlockT *BB) const;
296 /// Walk over all the BBs of the region starting from BB and
297 /// verify that all reachable basic blocks are elements of the region.
299 void verifyWalk(BlockT *BB, std::set<BlockT *> *visitedBB) const;
301 /// Verify if the region and its children are valid regions (EXPENSIVE!)
302 void verifyRegionNest() const;
305 /// Create a new region.
307 /// @param Entry The entry basic block of the region.
308 /// @param Exit The exit basic block of the region.
309 /// @param RI The region info object that is managing this region.
310 /// @param DT The dominator tree of the current function.
311 /// @param Parent The surrounding region or NULL if this is a top level
313 RegionBase(BlockT *Entry, BlockT *Exit, RegionInfoT *RI, DomTreeT *DT,
314 RegionT *Parent = nullptr);
316 RegionBase(const RegionBase &) = delete;
317 RegionBase &operator=(const RegionBase &) = delete;
319 /// Delete the Region and all its subregions.
322 /// Get the entry BasicBlock of the Region.
323 /// @return The entry BasicBlock of the region.
324 BlockT *getEntry() const {
325 return RegionNodeBase<Tr>::getEntry();
328 /// Replace the entry basic block of the region with the new basic
331 /// @param BB The new entry basic block of the region.
332 void replaceEntry(BlockT *BB);
334 /// Replace the exit basic block of the region with the new basic
337 /// @param BB The new exit basic block of the region.
338 void replaceExit(BlockT *BB);
340 /// Recursively replace the entry basic block of the region.
342 /// This function replaces the entry basic block with a new basic block. It
343 /// also updates all child regions that have the same entry basic block as
346 /// @param NewEntry The new entry basic block.
347 void replaceEntryRecursive(BlockT *NewEntry);
349 /// Recursively replace the exit basic block of the region.
351 /// This function replaces the exit basic block with a new basic block. It
352 /// also updates all child regions that have the same exit basic block as
355 /// @param NewExit The new exit basic block.
356 void replaceExitRecursive(BlockT *NewExit);
358 /// Get the exit BasicBlock of the Region.
359 /// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
361 BlockT *getExit() const { return exit; }
363 /// Get the parent of the Region.
364 /// @return The parent of the Region or NULL if this is a top level
366 RegionT *getParent() const {
367 return RegionNodeBase<Tr>::getParent();
370 /// Get the RegionNode representing the current Region.
371 /// @return The RegionNode representing the current Region.
372 RegionNodeT *getNode() const {
373 return const_cast<RegionNodeT *>(
374 reinterpret_cast<const RegionNodeT *>(this));
377 /// Get the nesting level of this Region.
379 /// An toplevel Region has depth 0.
381 /// @return The depth of the region.
382 unsigned getDepth() const;
384 /// Check if a Region is the TopLevel region.
386 /// The toplevel region represents the whole function.
387 bool isTopLevelRegion() const { return exit == nullptr; }
389 /// Return a new (non-canonical) region, that is obtained by joining
390 /// this region with its predecessors.
392 /// @return A region also starting at getEntry(), but reaching to the next
393 /// basic block that forms with getEntry() a (non-canonical) region.
394 /// NULL if such a basic block does not exist.
395 RegionT *getExpandedRegion() const;
397 /// Return the first block of this region's single entry edge,
400 /// @return The BasicBlock starting this region's single entry edge,
402 BlockT *getEnteringBlock() const;
404 /// Return the first block of this region's single exit edge,
407 /// @return The BasicBlock starting this region's single exit edge,
409 BlockT *getExitingBlock() const;
411 /// Collect all blocks of this region's single exit edge, if existing.
413 /// @return True if this region contains all the predecessors of the exit.
414 bool getExitingBlocks(SmallVectorImpl<BlockT *> &Exitings) const;
416 /// Is this a simple region?
418 /// A region is simple if it has exactly one exit and one entry edge.
420 /// @return True if the Region is simple.
421 bool isSimple() const;
423 /// Returns the name of the Region.
424 /// @return The Name of the Region.
425 std::string getNameStr() const;
427 /// Return the RegionInfo object, that belongs to this Region.
428 RegionInfoT *getRegionInfo() const { return RI; }
430 /// PrintStyle - Print region in difference ways.
431 enum PrintStyle { PrintNone, PrintBB, PrintRN };
433 /// Print the region.
435 /// @param OS The output stream the Region is printed to.
436 /// @param printTree Print also the tree of subregions.
437 /// @param level The indentation level used for printing.
438 void print(raw_ostream &OS, bool printTree = true, unsigned level = 0,
439 PrintStyle Style = PrintNone) const;
441 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
442 /// Print the region to stderr.
446 /// Check if the region contains a BasicBlock.
448 /// @param BB The BasicBlock that might be contained in this Region.
449 /// @return True if the block is contained in the region otherwise false.
450 bool contains(const BlockT *BB) const;
452 /// Check if the region contains another region.
454 /// @param SubRegion The region that might be contained in this Region.
455 /// @return True if SubRegion is contained in the region otherwise false.
456 bool contains(const RegionT *SubRegion) const {
461 return contains(SubRegion->getEntry()) &&
462 (contains(SubRegion->getExit()) ||
463 SubRegion->getExit() == getExit());
466 /// Check if the region contains an Instruction.
468 /// @param Inst The Instruction that might be contained in this region.
469 /// @return True if the Instruction is contained in the region otherwise
471 bool contains(const InstT *Inst) const { return contains(Inst->getParent()); }
473 /// Check if the region contains a loop.
475 /// @param L The loop that might be contained in this region.
476 /// @return True if the loop is contained in the region otherwise false.
477 /// In case a NULL pointer is passed to this function the result
478 /// is false, except for the region that describes the whole function.
479 /// In that case true is returned.
480 bool contains(const LoopT *L) const;
482 /// Get the outermost loop in the region that contains a loop.
484 /// Find for a Loop L the outermost loop OuterL that is a parent loop of L
485 /// and is itself contained in the region.
487 /// @param L The loop the lookup is started.
488 /// @return The outermost loop in the region, NULL if such a loop does not
489 /// exist or if the region describes the whole function.
490 LoopT *outermostLoopInRegion(LoopT *L) const;
492 /// Get the outermost loop in the region that contains a basic block.
494 /// Find for a basic block BB the outermost loop L that contains BB and is
495 /// itself contained in the region.
497 /// @param LI A pointer to a LoopInfo analysis.
498 /// @param BB The basic block surrounded by the loop.
499 /// @return The outermost loop in the region, NULL if such a loop does not
500 /// exist or if the region describes the whole function.
501 LoopT *outermostLoopInRegion(LoopInfoT *LI, BlockT *BB) const;
503 /// Get the subregion that starts at a BasicBlock
505 /// @param BB The BasicBlock the subregion should start.
506 /// @return The Subregion if available, otherwise NULL.
507 RegionT *getSubRegionNode(BlockT *BB) const;
509 /// Get the RegionNode for a BasicBlock
511 /// @param BB The BasicBlock at which the RegionNode should start.
512 /// @return If available, the RegionNode that represents the subregion
513 /// starting at BB. If no subregion starts at BB, the RegionNode
515 RegionNodeT *getNode(BlockT *BB) const;
517 /// Get the BasicBlock RegionNode for a BasicBlock
519 /// @param BB The BasicBlock for which the RegionNode is requested.
520 /// @return The RegionNode representing the BB.
521 RegionNodeT *getBBNode(BlockT *BB) const;
523 /// Add a new subregion to this Region.
525 /// @param SubRegion The new subregion that will be added.
526 /// @param moveChildren Move the children of this region, that are also
527 /// contained in SubRegion into SubRegion.
528 void addSubRegion(RegionT *SubRegion, bool moveChildren = false);
530 /// Remove a subregion from this Region.
532 /// The subregion is not deleted, as it will probably be inserted into another
534 /// @param SubRegion The SubRegion that will be removed.
535 RegionT *removeSubRegion(RegionT *SubRegion);
537 /// Move all direct child nodes of this Region to another Region.
539 /// @param To The Region the child nodes will be transferred to.
540 void transferChildrenTo(RegionT *To);
542 /// Verify if the region is a correct region.
544 /// Check if this is a correctly build Region. This is an expensive check, as
545 /// the complete CFG of the Region will be walked.
546 void verifyRegion() const;
548 /// Clear the cache for BB RegionNodes.
550 /// After calling this function the BasicBlock RegionNodes will be stored at
551 /// different memory locations. RegionNodes obtained before this function is
552 /// called are therefore not comparable to RegionNodes abtained afterwords.
553 void clearNodeCache();
555 /// @name Subregion Iterators
557 /// These iterators iterator over all subregions of this Region.
559 using iterator = typename RegionSet::iterator;
560 using const_iterator = typename RegionSet::const_iterator;
562 iterator begin() { return children.begin(); }
563 iterator end() { return children.end(); }
565 const_iterator begin() const { return children.begin(); }
566 const_iterator end() const { return children.end(); }
569 /// @name BasicBlock Iterators
571 /// These iterators iterate over all BasicBlocks that are contained in this
572 /// Region. The iterator also iterates over BasicBlocks that are elements of
573 /// a subregion of this Region. It is therefore called a flat iterator.
575 template <bool IsConst>
576 class block_iterator_wrapper
577 : public df_iterator<
578 typename std::conditional<IsConst, const BlockT, BlockT>::type *> {
581 typename std::conditional<IsConst, const BlockT, BlockT>::type *>;
584 using Self = block_iterator_wrapper<IsConst>;
585 using value_type = typename super::value_type;
587 // Construct the begin iterator.
588 block_iterator_wrapper(value_type Entry, value_type Exit)
589 : super(df_begin(Entry)) {
590 // Mark the exit of the region as visited, so that the children of the
591 // exit and the exit itself, i.e. the block outside the region will never
593 super::Visited.insert(Exit);
596 // Construct the end iterator.
597 block_iterator_wrapper() : super(df_end<value_type>((BlockT *)nullptr)) {}
599 /*implicit*/ block_iterator_wrapper(super I) : super(I) {}
601 // FIXME: Even a const_iterator returns a non-const BasicBlock pointer.
602 // This was introduced for backwards compatibility, but should
603 // be removed as soon as all users are fixed.
604 BlockT *operator*() const {
605 return const_cast<BlockT *>(super::operator*());
609 using block_iterator = block_iterator_wrapper<false>;
610 using const_block_iterator = block_iterator_wrapper<true>;
612 block_iterator block_begin() { return block_iterator(getEntry(), getExit()); }
614 block_iterator block_end() { return block_iterator(); }
616 const_block_iterator block_begin() const {
617 return const_block_iterator(getEntry(), getExit());
619 const_block_iterator block_end() const { return const_block_iterator(); }
621 using block_range = iterator_range<block_iterator>;
622 using const_block_range = iterator_range<const_block_iterator>;
624 /// Returns a range view of the basic blocks in the region.
625 inline block_range blocks() {
626 return block_range(block_begin(), block_end());
629 /// Returns a range view of the basic blocks in the region.
631 /// This is the 'const' version of the range view.
632 inline const_block_range blocks() const {
633 return const_block_range(block_begin(), block_end());
637 /// @name Element Iterators
639 /// These iterators iterate over all BasicBlock and subregion RegionNodes that
640 /// are direct children of this Region. It does not iterate over any
641 /// RegionNodes that are also element of a subregion of this Region.
643 using element_iterator =
644 df_iterator<RegionNodeT *, df_iterator_default_set<RegionNodeT *>, false,
645 GraphTraits<RegionNodeT *>>;
647 using const_element_iterator =
648 df_iterator<const RegionNodeT *,
649 df_iterator_default_set<const RegionNodeT *>, false,
650 GraphTraits<const RegionNodeT *>>;
652 element_iterator element_begin();
653 element_iterator element_end();
654 iterator_range<element_iterator> elements() {
655 return make_range(element_begin(), element_end());
658 const_element_iterator element_begin() const;
659 const_element_iterator element_end() const;
660 iterator_range<const_element_iterator> elements() const {
661 return make_range(element_begin(), element_end());
666 /// Print a RegionNode.
668 inline raw_ostream &operator<<(raw_ostream &OS, const RegionNodeBase<Tr> &Node);
670 //===----------------------------------------------------------------------===//
671 /// Analysis that detects all canonical Regions.
673 /// The RegionInfo pass detects all canonical regions in a function. The Regions
674 /// are connected using the parent relation. This builds a Program Structure
677 class RegionInfoBase {
678 friend class RegionInfo;
679 friend class MachineRegionInfo;
681 using BlockT = typename Tr::BlockT;
682 using FuncT = typename Tr::FuncT;
683 using RegionT = typename Tr::RegionT;
684 using RegionInfoT = typename Tr::RegionInfoT;
685 using DomTreeT = typename Tr::DomTreeT;
686 using DomTreeNodeT = typename Tr::DomTreeNodeT;
687 using PostDomTreeT = typename Tr::PostDomTreeT;
688 using DomFrontierT = typename Tr::DomFrontierT;
689 using BlockTraits = GraphTraits<BlockT *>;
690 using InvBlockTraits = GraphTraits<Inverse<BlockT *>>;
691 using SuccIterTy = typename BlockTraits::ChildIteratorType;
692 using PredIterTy = typename InvBlockTraits::ChildIteratorType;
694 using BBtoBBMap = DenseMap<BlockT *, BlockT *>;
695 using BBtoRegionMap = DenseMap<BlockT *, RegionT *>;
699 RegionInfoBase(RegionInfoBase &&Arg)
700 : DT(std::move(Arg.DT)), PDT(std::move(Arg.PDT)), DF(std::move(Arg.DF)),
701 TopLevelRegion(std::move(Arg.TopLevelRegion)),
702 BBtoRegion(std::move(Arg.BBtoRegion)) {
706 RegionInfoBase &operator=(RegionInfoBase &&RHS) {
707 DT = std::move(RHS.DT);
708 PDT = std::move(RHS.PDT);
709 DF = std::move(RHS.DF);
710 TopLevelRegion = std::move(RHS.TopLevelRegion);
711 BBtoRegion = std::move(RHS.BBtoRegion);
716 virtual ~RegionInfoBase();
722 /// The top level region.
723 RegionT *TopLevelRegion = nullptr;
725 /// Map every BB to the smallest region, that contains BB.
726 BBtoRegionMap BBtoRegion;
729 /// Update refences to a RegionInfoT held by the RegionT managed here
731 /// This is a post-move helper. Regions hold references to the owning
732 /// RegionInfo object. After a move these need to be fixed.
733 template<typename TheRegionT>
734 void updateRegionTree(RegionInfoT &RI, TheRegionT *R) {
738 for (auto &SubR : *R)
739 updateRegionTree(RI, SubR.get());
743 /// Wipe this region tree's state without releasing any resources.
745 /// This is essentially a post-move helper only. It leaves the object in an
746 /// assignable and destroyable state, but otherwise invalid.
751 TopLevelRegion = nullptr;
755 // Check whether the entries of BBtoRegion for the BBs of region
756 // SR are correct. Triggers an assertion if not. Calls itself recursively for
758 void verifyBBMap(const RegionT *SR) const;
760 // Returns true if BB is in the dominance frontier of
761 // entry, because it was inherited from exit. In the other case there is an
762 // edge going from entry to BB without passing exit.
763 bool isCommonDomFrontier(BlockT *BB, BlockT *entry, BlockT *exit) const;
765 // Check if entry and exit surround a valid region, based on
766 // dominance tree and dominance frontier.
767 bool isRegion(BlockT *entry, BlockT *exit) const;
769 // Saves a shortcut pointing from entry to exit.
770 // This function may extend this shortcut if possible.
771 void insertShortCut(BlockT *entry, BlockT *exit, BBtoBBMap *ShortCut) const;
773 // Returns the next BB that postdominates N, while skipping
774 // all post dominators that cannot finish a canonical region.
775 DomTreeNodeT *getNextPostDom(DomTreeNodeT *N, BBtoBBMap *ShortCut) const;
777 // A region is trivial, if it contains only one BB.
778 bool isTrivialRegion(BlockT *entry, BlockT *exit) const;
780 // Creates a single entry single exit region.
781 RegionT *createRegion(BlockT *entry, BlockT *exit);
783 // Detect all regions starting with bb 'entry'.
784 void findRegionsWithEntry(BlockT *entry, BBtoBBMap *ShortCut);
786 // Detects regions in F.
787 void scanForRegions(FuncT &F, BBtoBBMap *ShortCut);
789 // Get the top most parent with the same entry block.
790 RegionT *getTopMostParent(RegionT *region);
792 // Build the region hierarchy after all region detected.
793 void buildRegionsTree(DomTreeNodeT *N, RegionT *region);
795 // Update statistic about created regions.
796 virtual void updateStatistics(RegionT *R) = 0;
798 // Detect all regions in function and build the region tree.
799 void calculate(FuncT &F);
802 RegionInfoBase(const RegionInfoBase &) = delete;
803 RegionInfoBase &operator=(const RegionInfoBase &) = delete;
805 static bool VerifyRegionInfo;
806 static typename RegionT::PrintStyle printStyle;
808 void print(raw_ostream &OS) const;
809 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
813 void releaseMemory();
815 /// Get the smallest region that contains a BasicBlock.
817 /// @param BB The basic block.
818 /// @return The smallest region, that contains BB or NULL, if there is no
819 /// region containing BB.
820 RegionT *getRegionFor(BlockT *BB) const;
822 /// Set the smallest region that surrounds a basic block.
824 /// @param BB The basic block surrounded by a region.
825 /// @param R The smallest region that surrounds BB.
826 void setRegionFor(BlockT *BB, RegionT *R);
828 /// A shortcut for getRegionFor().
830 /// @param BB The basic block.
831 /// @return The smallest region, that contains BB or NULL, if there is no
832 /// region containing BB.
833 RegionT *operator[](BlockT *BB) const;
835 /// Return the exit of the maximal refined region, that starts at a
838 /// @param BB The BasicBlock the refined region starts.
839 BlockT *getMaxRegionExit(BlockT *BB) const;
841 /// Find the smallest region that contains two regions.
843 /// @param A The first region.
844 /// @param B The second region.
845 /// @return The smallest region containing A and B.
846 RegionT *getCommonRegion(RegionT *A, RegionT *B) const;
848 /// Find the smallest region that contains two basic blocks.
850 /// @param A The first basic block.
851 /// @param B The second basic block.
852 /// @return The smallest region that contains A and B.
853 RegionT *getCommonRegion(BlockT *A, BlockT *B) const {
854 return getCommonRegion(getRegionFor(A), getRegionFor(B));
857 /// Find the smallest region that contains a set of regions.
859 /// @param Regions A vector of regions.
860 /// @return The smallest region that contains all regions in Regions.
861 RegionT *getCommonRegion(SmallVectorImpl<RegionT *> &Regions) const;
863 /// Find the smallest region that contains a set of basic blocks.
865 /// @param BBs A vector of basic blocks.
866 /// @return The smallest region that contains all basic blocks in BBS.
867 RegionT *getCommonRegion(SmallVectorImpl<BlockT *> &BBs) const;
869 RegionT *getTopLevelRegion() const { return TopLevelRegion; }
871 /// Clear the Node Cache for all Regions.
873 /// @see Region::clearNodeCache()
874 void clearNodeCache() {
876 TopLevelRegion->clearNodeCache();
879 void verifyAnalysis() const;
884 class RegionNode : public RegionNodeBase<RegionTraits<Function>> {
886 inline RegionNode(Region *Parent, BasicBlock *Entry, bool isSubRegion = false)
887 : RegionNodeBase<RegionTraits<Function>>(Parent, Entry, isSubRegion) {}
889 bool operator==(const Region &RN) const {
890 return this == reinterpret_cast<const RegionNode *>(&RN);
894 class Region : public RegionBase<RegionTraits<Function>> {
896 Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo *RI, DominatorTree *DT,
897 Region *Parent = nullptr);
900 bool operator==(const RegionNode &RN) const {
901 return &RN == reinterpret_cast<const RegionNode *>(this);
905 class RegionInfo : public RegionInfoBase<RegionTraits<Function>> {
907 using Base = RegionInfoBase<RegionTraits<Function>>;
909 explicit RegionInfo();
911 RegionInfo(RegionInfo &&Arg) : Base(std::move(static_cast<Base &>(Arg))) {
912 updateRegionTree(*this, TopLevelRegion);
915 RegionInfo &operator=(RegionInfo &&RHS) {
916 Base::operator=(std::move(static_cast<Base &>(RHS)));
917 updateRegionTree(*this, TopLevelRegion);
921 ~RegionInfo() override;
923 /// Handle invalidation explicitly.
924 bool invalidate(Function &F, const PreservedAnalyses &PA,
925 FunctionAnalysisManager::Invalidator &);
927 // updateStatistics - Update statistic about created regions.
928 void updateStatistics(Region *R) final;
930 void recalculate(Function &F, DominatorTree *DT, PostDominatorTree *PDT,
931 DominanceFrontier *DF);
934 /// Opens a viewer to show the GraphViz visualization of the regions.
936 /// Useful during debugging as an alternative to dump().
939 /// Opens a viewer to show the GraphViz visualization of this region
940 /// without instructions in the BasicBlocks.
942 /// Useful during debugging as an alternative to dump().
947 class RegionInfoPass : public FunctionPass {
953 explicit RegionInfoPass();
954 ~RegionInfoPass() override;
956 RegionInfo &getRegionInfo() { return RI; }
958 const RegionInfo &getRegionInfo() const { return RI; }
960 /// @name FunctionPass interface
962 bool runOnFunction(Function &F) override;
963 void releaseMemory() override;
964 void verifyAnalysis() const override;
965 void getAnalysisUsage(AnalysisUsage &AU) const override;
966 void print(raw_ostream &OS, const Module *) const override;
971 /// Analysis pass that exposes the \c RegionInfo for a function.
972 class RegionInfoAnalysis : public AnalysisInfoMixin<RegionInfoAnalysis> {
973 friend AnalysisInfoMixin<RegionInfoAnalysis>;
975 static AnalysisKey Key;
978 using Result = RegionInfo;
980 RegionInfo run(Function &F, FunctionAnalysisManager &AM);
983 /// Printer pass for the \c RegionInfo.
984 class RegionInfoPrinterPass : public PassInfoMixin<RegionInfoPrinterPass> {
988 explicit RegionInfoPrinterPass(raw_ostream &OS);
990 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
993 /// Verifier pass for the \c RegionInfo.
994 struct RegionInfoVerifierPass : PassInfoMixin<RegionInfoVerifierPass> {
995 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
1001 RegionNodeBase<RegionTraits<Function>>::getNodeAs<BasicBlock>() const {
1002 assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
1009 RegionNodeBase<RegionTraits<Function>>::getNodeAs<Region>() const {
1010 assert(isSubRegion() && "This is not a subregion RegionNode!");
1011 auto Unconst = const_cast<RegionNodeBase<RegionTraits<Function>> *>(this);
1012 return reinterpret_cast<Region *>(Unconst);
1016 inline raw_ostream &operator<<(raw_ostream &OS,
1017 const RegionNodeBase<Tr> &Node) {
1018 using BlockT = typename Tr::BlockT;
1019 using RegionT = typename Tr::RegionT;
1021 if (Node.isSubRegion())
1022 return OS << Node.template getNodeAs<RegionT>()->getNameStr();
1024 return OS << Node.template getNodeAs<BlockT>()->getName();
1027 extern template class RegionBase<RegionTraits<Function>>;
1028 extern template class RegionNodeBase<RegionTraits<Function>>;
1029 extern template class RegionInfoBase<RegionTraits<Function>>;
1031 } // end namespace llvm
1033 #endif // LLVM_ANALYSIS_REGIONINFO_H