RegionInfo.h 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. //===- RegionInfo.h - SESE region analysis ----------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Calculate a program structure tree built out of single entry single exit
  10. // regions.
  11. // The basic ideas are taken from "The Program Structure Tree - Richard Johnson,
  12. // David Pearson, Keshav Pingali - 1994", however enriched with ideas from "The
  13. // Refined Process Structure Tree - Jussi Vanhatalo, Hagen Voelyer, Jana
  14. // Koehler - 2009".
  15. // The algorithm to calculate these data structures however is completely
  16. // different, as it takes advantage of existing information already available
  17. // in (Post)dominace tree and dominance frontier passes. This leads to a simpler
  18. // and in practice hopefully better performing algorithm. The runtime of the
  19. // algorithms described in the papers above are both linear in graph size,
  20. // O(V+E), whereas this algorithm is not, as the dominance frontier information
  21. // itself is not, but in practice runtime seems to be in the order of magnitude
  22. // of dominance tree calculation.
  23. //
  24. // WARNING: LLVM is generally very concerned about compile time such that
  25. // the use of additional analysis passes in the default
  26. // optimization sequence is avoided as much as possible.
  27. // Specifically, if you do not need the RegionInfo, but dominance
  28. // information could be sufficient please base your work only on
  29. // the dominator tree. Most passes maintain it, such that using
  30. // it has often near zero cost. In contrast RegionInfo is by
  31. // default not available, is not maintained by existing
  32. // transformations and there is no intention to do so.
  33. //
  34. //===----------------------------------------------------------------------===//
  35. #ifndef LLVM_ANALYSIS_REGIONINFO_H
  36. #define LLVM_ANALYSIS_REGIONINFO_H
  37. #include "llvm/ADT/DenseMap.h"
  38. #include "llvm/ADT/DepthFirstIterator.h"
  39. #include "llvm/ADT/GraphTraits.h"
  40. #include "llvm/ADT/PointerIntPair.h"
  41. #include "llvm/ADT/iterator_range.h"
  42. #include "llvm/Config/llvm-config.h"
  43. #include "llvm/IR/BasicBlock.h"
  44. #include "llvm/IR/Dominators.h"
  45. #include "llvm/IR/PassManager.h"
  46. #include "llvm/Pass.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <map>
  51. #include <memory>
  52. #include <set>
  53. #include <string>
  54. #include <type_traits>
  55. #include <vector>
  56. namespace llvm {
  57. class DominanceFrontier;
  58. class Loop;
  59. class LoopInfo;
  60. class PostDominatorTree;
  61. class Region;
  62. template <class RegionTr> class RegionBase;
  63. class RegionInfo;
  64. template <class RegionTr> class RegionInfoBase;
  65. class RegionNode;
  66. // Class to be specialized for different users of RegionInfo
  67. // (i.e. BasicBlocks or MachineBasicBlocks). This is only to avoid needing to
  68. // pass around an unreasonable number of template parameters.
  69. template <class FuncT_>
  70. struct RegionTraits {
  71. // FuncT
  72. // BlockT
  73. // RegionT
  74. // RegionNodeT
  75. // RegionInfoT
  76. using BrokenT = typename FuncT_::UnknownRegionTypeError;
  77. };
  78. template <>
  79. struct RegionTraits<Function> {
  80. using FuncT = Function;
  81. using BlockT = BasicBlock;
  82. using RegionT = Region;
  83. using RegionNodeT = RegionNode;
  84. using RegionInfoT = RegionInfo;
  85. using DomTreeT = DominatorTree;
  86. using DomTreeNodeT = DomTreeNode;
  87. using DomFrontierT = DominanceFrontier;
  88. using PostDomTreeT = PostDominatorTree;
  89. using InstT = Instruction;
  90. using LoopT = Loop;
  91. using LoopInfoT = LoopInfo;
  92. static unsigned getNumSuccessors(BasicBlock *BB) {
  93. return BB->getTerminator()->getNumSuccessors();
  94. }
  95. };
  96. /// Marker class to iterate over the elements of a Region in flat mode.
  97. ///
  98. /// The class is used to either iterate in Flat mode or by not using it to not
  99. /// iterate in Flat mode. During a Flat mode iteration all Regions are entered
  100. /// and the iteration returns every BasicBlock. If the Flat mode is not
  101. /// selected for SubRegions just one RegionNode containing the subregion is
  102. /// returned.
  103. template <class GraphType>
  104. class FlatIt {};
  105. /// A RegionNode represents a subregion or a BasicBlock that is part of a
  106. /// Region.
  107. template <class Tr>
  108. class RegionNodeBase {
  109. friend class RegionBase<Tr>;
  110. public:
  111. using BlockT = typename Tr::BlockT;
  112. using RegionT = typename Tr::RegionT;
  113. private:
  114. /// This is the entry basic block that starts this region node. If this is a
  115. /// BasicBlock RegionNode, then entry is just the basic block, that this
  116. /// RegionNode represents. Otherwise it is the entry of this (Sub)RegionNode.
  117. ///
  118. /// In the BBtoRegionNode map of the parent of this node, BB will always map
  119. /// to this node no matter which kind of node this one is.
  120. ///
  121. /// The node can hold either a Region or a BasicBlock.
  122. /// Use one bit to save, if this RegionNode is a subregion or BasicBlock
  123. /// RegionNode.
  124. PointerIntPair<BlockT *, 1, bool> entry;
  125. /// The parent Region of this RegionNode.
  126. /// @see getParent()
  127. RegionT *parent;
  128. protected:
  129. /// Create a RegionNode.
  130. ///
  131. /// @param Parent The parent of this RegionNode.
  132. /// @param Entry The entry BasicBlock of the RegionNode. If this
  133. /// RegionNode represents a BasicBlock, this is the
  134. /// BasicBlock itself. If it represents a subregion, this
  135. /// is the entry BasicBlock of the subregion.
  136. /// @param isSubRegion If this RegionNode represents a SubRegion.
  137. inline RegionNodeBase(RegionT *Parent, BlockT *Entry,
  138. bool isSubRegion = false)
  139. : entry(Entry, isSubRegion), parent(Parent) {}
  140. public:
  141. RegionNodeBase(const RegionNodeBase &) = delete;
  142. RegionNodeBase &operator=(const RegionNodeBase &) = delete;
  143. /// Get the parent Region of this RegionNode.
  144. ///
  145. /// The parent Region is the Region this RegionNode belongs to. If for
  146. /// example a BasicBlock is element of two Regions, there exist two
  147. /// RegionNodes for this BasicBlock. Each with the getParent() function
  148. /// pointing to the Region this RegionNode belongs to.
  149. ///
  150. /// @return Get the parent Region of this RegionNode.
  151. inline RegionT *getParent() const { return parent; }
  152. /// Get the entry BasicBlock of this RegionNode.
  153. ///
  154. /// If this RegionNode represents a BasicBlock this is just the BasicBlock
  155. /// itself, otherwise we return the entry BasicBlock of the Subregion
  156. ///
  157. /// @return The entry BasicBlock of this RegionNode.
  158. inline BlockT *getEntry() const { return entry.getPointer(); }
  159. /// Get the content of this RegionNode.
  160. ///
  161. /// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
  162. /// check the type of the content with the isSubRegion() function call.
  163. ///
  164. /// @return The content of this RegionNode.
  165. template <class T> inline T *getNodeAs() const;
  166. /// Is this RegionNode a subregion?
  167. ///
  168. /// @return True if it contains a subregion. False if it contains a
  169. /// BasicBlock.
  170. inline bool isSubRegion() const { return entry.getInt(); }
  171. };
  172. //===----------------------------------------------------------------------===//
  173. /// A single entry single exit Region.
  174. ///
  175. /// A Region is a connected subgraph of a control flow graph that has exactly
  176. /// two connections to the remaining graph. It can be used to analyze or
  177. /// optimize parts of the control flow graph.
  178. ///
  179. /// A <em> simple Region </em> is connected to the remaining graph by just two
  180. /// edges. One edge entering the Region and another one leaving the Region.
  181. ///
  182. /// An <em> extended Region </em> (or just Region) is a subgraph that can be
  183. /// transform into a simple Region. The transformation is done by adding
  184. /// BasicBlocks that merge several entry or exit edges so that after the merge
  185. /// just one entry and one exit edge exists.
  186. ///
  187. /// The \e Entry of a Region is the first BasicBlock that is passed after
  188. /// entering the Region. It is an element of the Region. The entry BasicBlock
  189. /// dominates all BasicBlocks in the Region.
  190. ///
  191. /// The \e Exit of a Region is the first BasicBlock that is passed after
  192. /// leaving the Region. It is not an element of the Region. The exit BasicBlock,
  193. /// postdominates all BasicBlocks in the Region.
  194. ///
  195. /// A <em> canonical Region </em> cannot be constructed by combining smaller
  196. /// Regions.
  197. ///
  198. /// Region A is the \e parent of Region B, if B is completely contained in A.
  199. ///
  200. /// Two canonical Regions either do not intersect at all or one is
  201. /// the parent of the other.
  202. ///
  203. /// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
  204. /// Regions in the control flow graph and E is the \e parent relation of these
  205. /// Regions.
  206. ///
  207. /// Example:
  208. ///
  209. /// \verbatim
  210. /// A simple control flow graph, that contains two regions.
  211. ///
  212. /// 1
  213. /// / |
  214. /// 2 |
  215. /// / \ 3
  216. /// 4 5 |
  217. /// | | |
  218. /// 6 7 8
  219. /// \ | /
  220. /// \ |/ Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
  221. /// 9 Region B: 2 -> 9 {2,4,5,6,7}
  222. /// \endverbatim
  223. ///
  224. /// You can obtain more examples by either calling
  225. ///
  226. /// <tt> "opt -regions -analyze anyprogram.ll" </tt>
  227. /// or
  228. /// <tt> "opt -view-regions-only anyprogram.ll" </tt>
  229. ///
  230. /// on any LLVM file you are interested in.
  231. ///
  232. /// The first call returns a textual representation of the program structure
  233. /// tree, the second one creates a graphical representation using graphviz.
  234. template <class Tr>
  235. class RegionBase : public RegionNodeBase<Tr> {
  236. friend class RegionInfoBase<Tr>;
  237. using FuncT = typename Tr::FuncT;
  238. using BlockT = typename Tr::BlockT;
  239. using RegionInfoT = typename Tr::RegionInfoT;
  240. using RegionT = typename Tr::RegionT;
  241. using RegionNodeT = typename Tr::RegionNodeT;
  242. using DomTreeT = typename Tr::DomTreeT;
  243. using LoopT = typename Tr::LoopT;
  244. using LoopInfoT = typename Tr::LoopInfoT;
  245. using InstT = typename Tr::InstT;
  246. using BlockTraits = GraphTraits<BlockT *>;
  247. using InvBlockTraits = GraphTraits<Inverse<BlockT *>>;
  248. using SuccIterTy = typename BlockTraits::ChildIteratorType;
  249. using PredIterTy = typename InvBlockTraits::ChildIteratorType;
  250. // Information necessary to manage this Region.
  251. RegionInfoT *RI;
  252. DomTreeT *DT;
  253. // The exit BasicBlock of this region.
  254. // (The entry BasicBlock is part of RegionNode)
  255. BlockT *exit;
  256. using RegionSet = std::vector<std::unique_ptr<RegionT>>;
  257. // The subregions of this region.
  258. RegionSet children;
  259. using BBNodeMapT = std::map<BlockT *, std::unique_ptr<RegionNodeT>>;
  260. // Save the BasicBlock RegionNodes that are element of this Region.
  261. mutable BBNodeMapT BBNodeMap;
  262. /// Check if a BB is in this Region. This check also works
  263. /// if the region is incorrectly built. (EXPENSIVE!)
  264. void verifyBBInRegion(BlockT *BB) const;
  265. /// Walk over all the BBs of the region starting from BB and
  266. /// verify that all reachable basic blocks are elements of the region.
  267. /// (EXPENSIVE!)
  268. void verifyWalk(BlockT *BB, std::set<BlockT *> *visitedBB) const;
  269. /// Verify if the region and its children are valid regions (EXPENSIVE!)
  270. void verifyRegionNest() const;
  271. public:
  272. /// Create a new region.
  273. ///
  274. /// @param Entry The entry basic block of the region.
  275. /// @param Exit The exit basic block of the region.
  276. /// @param RI The region info object that is managing this region.
  277. /// @param DT The dominator tree of the current function.
  278. /// @param Parent The surrounding region or NULL if this is a top level
  279. /// region.
  280. RegionBase(BlockT *Entry, BlockT *Exit, RegionInfoT *RI, DomTreeT *DT,
  281. RegionT *Parent = nullptr);
  282. RegionBase(const RegionBase &) = delete;
  283. RegionBase &operator=(const RegionBase &) = delete;
  284. /// Delete the Region and all its subregions.
  285. ~RegionBase();
  286. /// Get the entry BasicBlock of the Region.
  287. /// @return The entry BasicBlock of the region.
  288. BlockT *getEntry() const {
  289. return RegionNodeBase<Tr>::getEntry();
  290. }
  291. /// Replace the entry basic block of the region with the new basic
  292. /// block.
  293. ///
  294. /// @param BB The new entry basic block of the region.
  295. void replaceEntry(BlockT *BB);
  296. /// Replace the exit basic block of the region with the new basic
  297. /// block.
  298. ///
  299. /// @param BB The new exit basic block of the region.
  300. void replaceExit(BlockT *BB);
  301. /// Recursively replace the entry basic block of the region.
  302. ///
  303. /// This function replaces the entry basic block with a new basic block. It
  304. /// also updates all child regions that have the same entry basic block as
  305. /// this region.
  306. ///
  307. /// @param NewEntry The new entry basic block.
  308. void replaceEntryRecursive(BlockT *NewEntry);
  309. /// Recursively replace the exit basic block of the region.
  310. ///
  311. /// This function replaces the exit basic block with a new basic block. It
  312. /// also updates all child regions that have the same exit basic block as
  313. /// this region.
  314. ///
  315. /// @param NewExit The new exit basic block.
  316. void replaceExitRecursive(BlockT *NewExit);
  317. /// Get the exit BasicBlock of the Region.
  318. /// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
  319. /// Region.
  320. BlockT *getExit() const { return exit; }
  321. /// Get the parent of the Region.
  322. /// @return The parent of the Region or NULL if this is a top level
  323. /// Region.
  324. RegionT *getParent() const {
  325. return RegionNodeBase<Tr>::getParent();
  326. }
  327. /// Get the RegionNode representing the current Region.
  328. /// @return The RegionNode representing the current Region.
  329. RegionNodeT *getNode() const {
  330. return const_cast<RegionNodeT *>(
  331. reinterpret_cast<const RegionNodeT *>(this));
  332. }
  333. /// Get the nesting level of this Region.
  334. ///
  335. /// An toplevel Region has depth 0.
  336. ///
  337. /// @return The depth of the region.
  338. unsigned getDepth() const;
  339. /// Check if a Region is the TopLevel region.
  340. ///
  341. /// The toplevel region represents the whole function.
  342. bool isTopLevelRegion() const { return exit == nullptr; }
  343. /// Return a new (non-canonical) region, that is obtained by joining
  344. /// this region with its predecessors.
  345. ///
  346. /// @return A region also starting at getEntry(), but reaching to the next
  347. /// basic block that forms with getEntry() a (non-canonical) region.
  348. /// NULL if such a basic block does not exist.
  349. RegionT *getExpandedRegion() const;
  350. /// Return the first block of this region's single entry edge,
  351. /// if existing.
  352. ///
  353. /// @return The BasicBlock starting this region's single entry edge,
  354. /// else NULL.
  355. BlockT *getEnteringBlock() const;
  356. /// Return the first block of this region's single exit edge,
  357. /// if existing.
  358. ///
  359. /// @return The BasicBlock starting this region's single exit edge,
  360. /// else NULL.
  361. BlockT *getExitingBlock() const;
  362. /// Collect all blocks of this region's single exit edge, if existing.
  363. ///
  364. /// @return True if this region contains all the predecessors of the exit.
  365. bool getExitingBlocks(SmallVectorImpl<BlockT *> &Exitings) const;
  366. /// Is this a simple region?
  367. ///
  368. /// A region is simple if it has exactly one exit and one entry edge.
  369. ///
  370. /// @return True if the Region is simple.
  371. bool isSimple() const;
  372. /// Returns the name of the Region.
  373. /// @return The Name of the Region.
  374. std::string getNameStr() const;
  375. /// Return the RegionInfo object, that belongs to this Region.
  376. RegionInfoT *getRegionInfo() const { return RI; }
  377. /// PrintStyle - Print region in difference ways.
  378. enum PrintStyle { PrintNone, PrintBB, PrintRN };
  379. /// Print the region.
  380. ///
  381. /// @param OS The output stream the Region is printed to.
  382. /// @param printTree Print also the tree of subregions.
  383. /// @param level The indentation level used for printing.
  384. void print(raw_ostream &OS, bool printTree = true, unsigned level = 0,
  385. PrintStyle Style = PrintNone) const;
  386. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  387. /// Print the region to stderr.
  388. void dump() const;
  389. #endif
  390. /// Check if the region contains a BasicBlock.
  391. ///
  392. /// @param BB The BasicBlock that might be contained in this Region.
  393. /// @return True if the block is contained in the region otherwise false.
  394. bool contains(const BlockT *BB) const;
  395. /// Check if the region contains another region.
  396. ///
  397. /// @param SubRegion The region that might be contained in this Region.
  398. /// @return True if SubRegion is contained in the region otherwise false.
  399. bool contains(const RegionT *SubRegion) const {
  400. // Toplevel Region.
  401. if (!getExit())
  402. return true;
  403. return contains(SubRegion->getEntry()) &&
  404. (contains(SubRegion->getExit()) ||
  405. SubRegion->getExit() == getExit());
  406. }
  407. /// Check if the region contains an Instruction.
  408. ///
  409. /// @param Inst The Instruction that might be contained in this region.
  410. /// @return True if the Instruction is contained in the region otherwise
  411. /// false.
  412. bool contains(const InstT *Inst) const { return contains(Inst->getParent()); }
  413. /// Check if the region contains a loop.
  414. ///
  415. /// @param L The loop that might be contained in this region.
  416. /// @return True if the loop is contained in the region otherwise false.
  417. /// In case a NULL pointer is passed to this function the result
  418. /// is false, except for the region that describes the whole function.
  419. /// In that case true is returned.
  420. bool contains(const LoopT *L) const;
  421. /// Get the outermost loop in the region that contains a loop.
  422. ///
  423. /// Find for a Loop L the outermost loop OuterL that is a parent loop of L
  424. /// and is itself contained in the region.
  425. ///
  426. /// @param L The loop the lookup is started.
  427. /// @return The outermost loop in the region, NULL if such a loop does not
  428. /// exist or if the region describes the whole function.
  429. LoopT *outermostLoopInRegion(LoopT *L) const;
  430. /// Get the outermost loop in the region that contains a basic block.
  431. ///
  432. /// Find for a basic block BB the outermost loop L that contains BB and is
  433. /// itself contained in the region.
  434. ///
  435. /// @param LI A pointer to a LoopInfo analysis.
  436. /// @param BB The basic block surrounded by the loop.
  437. /// @return The outermost loop in the region, NULL if such a loop does not
  438. /// exist or if the region describes the whole function.
  439. LoopT *outermostLoopInRegion(LoopInfoT *LI, BlockT *BB) const;
  440. /// Get the subregion that starts at a BasicBlock
  441. ///
  442. /// @param BB The BasicBlock the subregion should start.
  443. /// @return The Subregion if available, otherwise NULL.
  444. RegionT *getSubRegionNode(BlockT *BB) const;
  445. /// Get the RegionNode for a BasicBlock
  446. ///
  447. /// @param BB The BasicBlock at which the RegionNode should start.
  448. /// @return If available, the RegionNode that represents the subregion
  449. /// starting at BB. If no subregion starts at BB, the RegionNode
  450. /// representing BB.
  451. RegionNodeT *getNode(BlockT *BB) const;
  452. /// Get the BasicBlock RegionNode for a BasicBlock
  453. ///
  454. /// @param BB The BasicBlock for which the RegionNode is requested.
  455. /// @return The RegionNode representing the BB.
  456. RegionNodeT *getBBNode(BlockT *BB) const;
  457. /// Add a new subregion to this Region.
  458. ///
  459. /// @param SubRegion The new subregion that will be added.
  460. /// @param moveChildren Move the children of this region, that are also
  461. /// contained in SubRegion into SubRegion.
  462. void addSubRegion(RegionT *SubRegion, bool moveChildren = false);
  463. /// Remove a subregion from this Region.
  464. ///
  465. /// The subregion is not deleted, as it will probably be inserted into another
  466. /// region.
  467. /// @param SubRegion The SubRegion that will be removed.
  468. RegionT *removeSubRegion(RegionT *SubRegion);
  469. /// Move all direct child nodes of this Region to another Region.
  470. ///
  471. /// @param To The Region the child nodes will be transferred to.
  472. void transferChildrenTo(RegionT *To);
  473. /// Verify if the region is a correct region.
  474. ///
  475. /// Check if this is a correctly build Region. This is an expensive check, as
  476. /// the complete CFG of the Region will be walked.
  477. void verifyRegion() const;
  478. /// Clear the cache for BB RegionNodes.
  479. ///
  480. /// After calling this function the BasicBlock RegionNodes will be stored at
  481. /// different memory locations. RegionNodes obtained before this function is
  482. /// called are therefore not comparable to RegionNodes abtained afterwords.
  483. void clearNodeCache();
  484. /// @name Subregion Iterators
  485. ///
  486. /// These iterators iterator over all subregions of this Region.
  487. //@{
  488. using iterator = typename RegionSet::iterator;
  489. using const_iterator = typename RegionSet::const_iterator;
  490. iterator begin() { return children.begin(); }
  491. iterator end() { return children.end(); }
  492. const_iterator begin() const { return children.begin(); }
  493. const_iterator end() const { return children.end(); }
  494. //@}
  495. /// @name BasicBlock Iterators
  496. ///
  497. /// These iterators iterate over all BasicBlocks that are contained in this
  498. /// Region. The iterator also iterates over BasicBlocks that are elements of
  499. /// a subregion of this Region. It is therefore called a flat iterator.
  500. //@{
  501. template <bool IsConst>
  502. class block_iterator_wrapper
  503. : public df_iterator<
  504. std::conditional_t<IsConst, const BlockT, BlockT> *> {
  505. using super =
  506. df_iterator<std::conditional_t<IsConst, const BlockT, BlockT> *>;
  507. public:
  508. using Self = block_iterator_wrapper<IsConst>;
  509. using value_type = typename super::value_type;
  510. // Construct the begin iterator.
  511. block_iterator_wrapper(value_type Entry, value_type Exit)
  512. : super(df_begin(Entry)) {
  513. // Mark the exit of the region as visited, so that the children of the
  514. // exit and the exit itself, i.e. the block outside the region will never
  515. // be visited.
  516. super::Visited.insert(Exit);
  517. }
  518. // Construct the end iterator.
  519. block_iterator_wrapper() : super(df_end<value_type>((BlockT *)nullptr)) {}
  520. /*implicit*/ block_iterator_wrapper(super I) : super(I) {}
  521. // FIXME: Even a const_iterator returns a non-const BasicBlock pointer.
  522. // This was introduced for backwards compatibility, but should
  523. // be removed as soon as all users are fixed.
  524. BlockT *operator*() const {
  525. return const_cast<BlockT *>(super::operator*());
  526. }
  527. };
  528. using block_iterator = block_iterator_wrapper<false>;
  529. using const_block_iterator = block_iterator_wrapper<true>;
  530. block_iterator block_begin() { return block_iterator(getEntry(), getExit()); }
  531. block_iterator block_end() { return block_iterator(); }
  532. const_block_iterator block_begin() const {
  533. return const_block_iterator(getEntry(), getExit());
  534. }
  535. const_block_iterator block_end() const { return const_block_iterator(); }
  536. using block_range = iterator_range<block_iterator>;
  537. using const_block_range = iterator_range<const_block_iterator>;
  538. /// Returns a range view of the basic blocks in the region.
  539. inline block_range blocks() {
  540. return block_range(block_begin(), block_end());
  541. }
  542. /// Returns a range view of the basic blocks in the region.
  543. ///
  544. /// This is the 'const' version of the range view.
  545. inline const_block_range blocks() const {
  546. return const_block_range(block_begin(), block_end());
  547. }
  548. //@}
  549. /// @name Element Iterators
  550. ///
  551. /// These iterators iterate over all BasicBlock and subregion RegionNodes that
  552. /// are direct children of this Region. It does not iterate over any
  553. /// RegionNodes that are also element of a subregion of this Region.
  554. //@{
  555. using element_iterator =
  556. df_iterator<RegionNodeT *, df_iterator_default_set<RegionNodeT *>, false,
  557. GraphTraits<RegionNodeT *>>;
  558. using const_element_iterator =
  559. df_iterator<const RegionNodeT *,
  560. df_iterator_default_set<const RegionNodeT *>, false,
  561. GraphTraits<const RegionNodeT *>>;
  562. element_iterator element_begin();
  563. element_iterator element_end();
  564. iterator_range<element_iterator> elements() {
  565. return make_range(element_begin(), element_end());
  566. }
  567. const_element_iterator element_begin() const;
  568. const_element_iterator element_end() const;
  569. iterator_range<const_element_iterator> elements() const {
  570. return make_range(element_begin(), element_end());
  571. }
  572. //@}
  573. };
  574. /// Print a RegionNode.
  575. template <class Tr>
  576. inline raw_ostream &operator<<(raw_ostream &OS, const RegionNodeBase<Tr> &Node);
  577. //===----------------------------------------------------------------------===//
  578. /// Analysis that detects all canonical Regions.
  579. ///
  580. /// The RegionInfo pass detects all canonical regions in a function. The Regions
  581. /// are connected using the parent relation. This builds a Program Structure
  582. /// Tree.
  583. template <class Tr>
  584. class RegionInfoBase {
  585. friend class RegionInfo;
  586. friend class MachineRegionInfo;
  587. using BlockT = typename Tr::BlockT;
  588. using FuncT = typename Tr::FuncT;
  589. using RegionT = typename Tr::RegionT;
  590. using RegionInfoT = typename Tr::RegionInfoT;
  591. using DomTreeT = typename Tr::DomTreeT;
  592. using DomTreeNodeT = typename Tr::DomTreeNodeT;
  593. using PostDomTreeT = typename Tr::PostDomTreeT;
  594. using DomFrontierT = typename Tr::DomFrontierT;
  595. using BlockTraits = GraphTraits<BlockT *>;
  596. using InvBlockTraits = GraphTraits<Inverse<BlockT *>>;
  597. using SuccIterTy = typename BlockTraits::ChildIteratorType;
  598. using PredIterTy = typename InvBlockTraits::ChildIteratorType;
  599. using BBtoBBMap = DenseMap<BlockT *, BlockT *>;
  600. using BBtoRegionMap = DenseMap<BlockT *, RegionT *>;
  601. RegionInfoBase();
  602. RegionInfoBase(RegionInfoBase &&Arg)
  603. : DT(std::move(Arg.DT)), PDT(std::move(Arg.PDT)), DF(std::move(Arg.DF)),
  604. TopLevelRegion(std::move(Arg.TopLevelRegion)),
  605. BBtoRegion(std::move(Arg.BBtoRegion)) {
  606. Arg.wipe();
  607. }
  608. RegionInfoBase &operator=(RegionInfoBase &&RHS) {
  609. DT = std::move(RHS.DT);
  610. PDT = std::move(RHS.PDT);
  611. DF = std::move(RHS.DF);
  612. TopLevelRegion = std::move(RHS.TopLevelRegion);
  613. BBtoRegion = std::move(RHS.BBtoRegion);
  614. RHS.wipe();
  615. return *this;
  616. }
  617. virtual ~RegionInfoBase();
  618. DomTreeT *DT;
  619. PostDomTreeT *PDT;
  620. DomFrontierT *DF;
  621. /// The top level region.
  622. RegionT *TopLevelRegion = nullptr;
  623. /// Map every BB to the smallest region, that contains BB.
  624. BBtoRegionMap BBtoRegion;
  625. protected:
  626. /// Update refences to a RegionInfoT held by the RegionT managed here
  627. ///
  628. /// This is a post-move helper. Regions hold references to the owning
  629. /// RegionInfo object. After a move these need to be fixed.
  630. template<typename TheRegionT>
  631. void updateRegionTree(RegionInfoT &RI, TheRegionT *R) {
  632. if (!R)
  633. return;
  634. R->RI = &RI;
  635. for (auto &SubR : *R)
  636. updateRegionTree(RI, SubR.get());
  637. }
  638. private:
  639. /// Wipe this region tree's state without releasing any resources.
  640. ///
  641. /// This is essentially a post-move helper only. It leaves the object in an
  642. /// assignable and destroyable state, but otherwise invalid.
  643. void wipe() {
  644. DT = nullptr;
  645. PDT = nullptr;
  646. DF = nullptr;
  647. TopLevelRegion = nullptr;
  648. BBtoRegion.clear();
  649. }
  650. // Check whether the entries of BBtoRegion for the BBs of region
  651. // SR are correct. Triggers an assertion if not. Calls itself recursively for
  652. // subregions.
  653. void verifyBBMap(const RegionT *SR) const;
  654. // Returns true if BB is in the dominance frontier of
  655. // entry, because it was inherited from exit. In the other case there is an
  656. // edge going from entry to BB without passing exit.
  657. bool isCommonDomFrontier(BlockT *BB, BlockT *entry, BlockT *exit) const;
  658. // Check if entry and exit surround a valid region, based on
  659. // dominance tree and dominance frontier.
  660. bool isRegion(BlockT *entry, BlockT *exit) const;
  661. // Saves a shortcut pointing from entry to exit.
  662. // This function may extend this shortcut if possible.
  663. void insertShortCut(BlockT *entry, BlockT *exit, BBtoBBMap *ShortCut) const;
  664. // Returns the next BB that postdominates N, while skipping
  665. // all post dominators that cannot finish a canonical region.
  666. DomTreeNodeT *getNextPostDom(DomTreeNodeT *N, BBtoBBMap *ShortCut) const;
  667. // A region is trivial, if it contains only one BB.
  668. bool isTrivialRegion(BlockT *entry, BlockT *exit) const;
  669. // Creates a single entry single exit region.
  670. RegionT *createRegion(BlockT *entry, BlockT *exit);
  671. // Detect all regions starting with bb 'entry'.
  672. void findRegionsWithEntry(BlockT *entry, BBtoBBMap *ShortCut);
  673. // Detects regions in F.
  674. void scanForRegions(FuncT &F, BBtoBBMap *ShortCut);
  675. // Get the top most parent with the same entry block.
  676. RegionT *getTopMostParent(RegionT *region);
  677. // Build the region hierarchy after all region detected.
  678. void buildRegionsTree(DomTreeNodeT *N, RegionT *region);
  679. // Update statistic about created regions.
  680. virtual void updateStatistics(RegionT *R) = 0;
  681. // Detect all regions in function and build the region tree.
  682. void calculate(FuncT &F);
  683. public:
  684. RegionInfoBase(const RegionInfoBase &) = delete;
  685. RegionInfoBase &operator=(const RegionInfoBase &) = delete;
  686. static bool VerifyRegionInfo;
  687. static typename RegionT::PrintStyle printStyle;
  688. void print(raw_ostream &OS) const;
  689. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  690. void dump() const;
  691. #endif
  692. void releaseMemory();
  693. /// Get the smallest region that contains a BasicBlock.
  694. ///
  695. /// @param BB The basic block.
  696. /// @return The smallest region, that contains BB or NULL, if there is no
  697. /// region containing BB.
  698. RegionT *getRegionFor(BlockT *BB) const;
  699. /// Set the smallest region that surrounds a basic block.
  700. ///
  701. /// @param BB The basic block surrounded by a region.
  702. /// @param R The smallest region that surrounds BB.
  703. void setRegionFor(BlockT *BB, RegionT *R);
  704. /// A shortcut for getRegionFor().
  705. ///
  706. /// @param BB The basic block.
  707. /// @return The smallest region, that contains BB or NULL, if there is no
  708. /// region containing BB.
  709. RegionT *operator[](BlockT *BB) const;
  710. /// Return the exit of the maximal refined region, that starts at a
  711. /// BasicBlock.
  712. ///
  713. /// @param BB The BasicBlock the refined region starts.
  714. BlockT *getMaxRegionExit(BlockT *BB) const;
  715. /// Find the smallest region that contains two regions.
  716. ///
  717. /// @param A The first region.
  718. /// @param B The second region.
  719. /// @return The smallest region containing A and B.
  720. RegionT *getCommonRegion(RegionT *A, RegionT *B) const;
  721. /// Find the smallest region that contains two basic blocks.
  722. ///
  723. /// @param A The first basic block.
  724. /// @param B The second basic block.
  725. /// @return The smallest region that contains A and B.
  726. RegionT *getCommonRegion(BlockT *A, BlockT *B) const {
  727. return getCommonRegion(getRegionFor(A), getRegionFor(B));
  728. }
  729. /// Find the smallest region that contains a set of regions.
  730. ///
  731. /// @param Regions A vector of regions.
  732. /// @return The smallest region that contains all regions in Regions.
  733. RegionT *getCommonRegion(SmallVectorImpl<RegionT *> &Regions) const;
  734. /// Find the smallest region that contains a set of basic blocks.
  735. ///
  736. /// @param BBs A vector of basic blocks.
  737. /// @return The smallest region that contains all basic blocks in BBS.
  738. RegionT *getCommonRegion(SmallVectorImpl<BlockT *> &BBs) const;
  739. RegionT *getTopLevelRegion() const { return TopLevelRegion; }
  740. /// Clear the Node Cache for all Regions.
  741. ///
  742. /// @see Region::clearNodeCache()
  743. void clearNodeCache() {
  744. if (TopLevelRegion)
  745. TopLevelRegion->clearNodeCache();
  746. }
  747. void verifyAnalysis() const;
  748. };
  749. class RegionNode : public RegionNodeBase<RegionTraits<Function>> {
  750. public:
  751. inline RegionNode(Region *Parent, BasicBlock *Entry, bool isSubRegion = false)
  752. : RegionNodeBase<RegionTraits<Function>>(Parent, Entry, isSubRegion) {}
  753. bool operator==(const Region &RN) const {
  754. return this == reinterpret_cast<const RegionNode *>(&RN);
  755. }
  756. };
  757. class Region : public RegionBase<RegionTraits<Function>> {
  758. public:
  759. Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo *RI, DominatorTree *DT,
  760. Region *Parent = nullptr);
  761. ~Region();
  762. bool operator==(const RegionNode &RN) const {
  763. return &RN == reinterpret_cast<const RegionNode *>(this);
  764. }
  765. };
  766. class RegionInfo : public RegionInfoBase<RegionTraits<Function>> {
  767. public:
  768. using Base = RegionInfoBase<RegionTraits<Function>>;
  769. explicit RegionInfo();
  770. RegionInfo(RegionInfo &&Arg) : Base(std::move(static_cast<Base &>(Arg))) {
  771. updateRegionTree(*this, TopLevelRegion);
  772. }
  773. RegionInfo &operator=(RegionInfo &&RHS) {
  774. Base::operator=(std::move(static_cast<Base &>(RHS)));
  775. updateRegionTree(*this, TopLevelRegion);
  776. return *this;
  777. }
  778. ~RegionInfo() override;
  779. /// Handle invalidation explicitly.
  780. bool invalidate(Function &F, const PreservedAnalyses &PA,
  781. FunctionAnalysisManager::Invalidator &);
  782. // updateStatistics - Update statistic about created regions.
  783. void updateStatistics(Region *R) final;
  784. void recalculate(Function &F, DominatorTree *DT, PostDominatorTree *PDT,
  785. DominanceFrontier *DF);
  786. #ifndef NDEBUG
  787. /// Opens a viewer to show the GraphViz visualization of the regions.
  788. ///
  789. /// Useful during debugging as an alternative to dump().
  790. void view();
  791. /// Opens a viewer to show the GraphViz visualization of this region
  792. /// without instructions in the BasicBlocks.
  793. ///
  794. /// Useful during debugging as an alternative to dump().
  795. void viewOnly();
  796. #endif
  797. };
  798. class RegionInfoPass : public FunctionPass {
  799. RegionInfo RI;
  800. public:
  801. static char ID;
  802. explicit RegionInfoPass();
  803. ~RegionInfoPass() override;
  804. RegionInfo &getRegionInfo() { return RI; }
  805. const RegionInfo &getRegionInfo() const { return RI; }
  806. /// @name FunctionPass interface
  807. //@{
  808. bool runOnFunction(Function &F) override;
  809. void releaseMemory() override;
  810. void verifyAnalysis() const override;
  811. void getAnalysisUsage(AnalysisUsage &AU) const override;
  812. void print(raw_ostream &OS, const Module *) const override;
  813. void dump() const;
  814. //@}
  815. };
  816. /// Analysis pass that exposes the \c RegionInfo for a function.
  817. class RegionInfoAnalysis : public AnalysisInfoMixin<RegionInfoAnalysis> {
  818. friend AnalysisInfoMixin<RegionInfoAnalysis>;
  819. static AnalysisKey Key;
  820. public:
  821. using Result = RegionInfo;
  822. RegionInfo run(Function &F, FunctionAnalysisManager &AM);
  823. };
  824. /// Printer pass for the \c RegionInfo.
  825. class RegionInfoPrinterPass : public PassInfoMixin<RegionInfoPrinterPass> {
  826. raw_ostream &OS;
  827. public:
  828. explicit RegionInfoPrinterPass(raw_ostream &OS);
  829. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  830. };
  831. /// Verifier pass for the \c RegionInfo.
  832. struct RegionInfoVerifierPass : PassInfoMixin<RegionInfoVerifierPass> {
  833. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  834. };
  835. template <>
  836. template <>
  837. inline BasicBlock *
  838. RegionNodeBase<RegionTraits<Function>>::getNodeAs<BasicBlock>() const {
  839. assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
  840. return getEntry();
  841. }
  842. template <>
  843. template <>
  844. inline Region *
  845. RegionNodeBase<RegionTraits<Function>>::getNodeAs<Region>() const {
  846. assert(isSubRegion() && "This is not a subregion RegionNode!");
  847. auto Unconst = const_cast<RegionNodeBase<RegionTraits<Function>> *>(this);
  848. return reinterpret_cast<Region *>(Unconst);
  849. }
  850. template <class Tr>
  851. inline raw_ostream &operator<<(raw_ostream &OS,
  852. const RegionNodeBase<Tr> &Node) {
  853. using BlockT = typename Tr::BlockT;
  854. using RegionT = typename Tr::RegionT;
  855. if (Node.isSubRegion())
  856. return OS << Node.template getNodeAs<RegionT>()->getNameStr();
  857. else
  858. return OS << Node.template getNodeAs<BlockT>()->getName();
  859. }
  860. extern template class RegionBase<RegionTraits<Function>>;
  861. extern template class RegionNodeBase<RegionTraits<Function>>;
  862. extern template class RegionInfoBase<RegionTraits<Function>>;
  863. } // end namespace llvm
  864. #endif // LLVM_ANALYSIS_REGIONINFO_H