RegionInfoImpl.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- RegionInfoImpl.h - SESE region detection analysis --------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. // Detects single entry single exit regions in the control flow graph.
  14. //===----------------------------------------------------------------------===//
  15. #ifndef LLVM_ANALYSIS_REGIONINFOIMPL_H
  16. #define LLVM_ANALYSIS_REGIONINFOIMPL_H
  17. #include "llvm/ADT/GraphTraits.h"
  18. #include "llvm/ADT/PostOrderIterator.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/iterator_range.h"
  22. #include "llvm/Analysis/DominanceFrontier.h"
  23. #include "llvm/Analysis/LoopInfo.h"
  24. #include "llvm/Analysis/PostDominators.h"
  25. #include "llvm/Analysis/RegionInfo.h"
  26. #include "llvm/Analysis/RegionIterator.h"
  27. #include "llvm/Config/llvm-config.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <algorithm>
  32. #include <cassert>
  33. #include <iterator>
  34. #include <memory>
  35. #include <set>
  36. #include <string>
  37. #include <type_traits>
  38. #include <vector>
  39. #define DEBUG_TYPE "region"
  40. namespace llvm {
  41. //===----------------------------------------------------------------------===//
  42. /// RegionBase Implementation
  43. template <class Tr>
  44. RegionBase<Tr>::RegionBase(BlockT *Entry, BlockT *Exit,
  45. typename Tr::RegionInfoT *RInfo, DomTreeT *dt,
  46. RegionT *Parent)
  47. : RegionNodeBase<Tr>(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
  48. template <class Tr>
  49. RegionBase<Tr>::~RegionBase() {
  50. // Only clean the cache for this Region. Caches of child Regions will be
  51. // cleaned when the child Regions are deleted.
  52. BBNodeMap.clear();
  53. }
  54. template <class Tr>
  55. void RegionBase<Tr>::replaceEntry(BlockT *BB) {
  56. this->entry.setPointer(BB);
  57. }
  58. template <class Tr>
  59. void RegionBase<Tr>::replaceExit(BlockT *BB) {
  60. assert(exit && "No exit to replace!");
  61. exit = BB;
  62. }
  63. template <class Tr>
  64. void RegionBase<Tr>::replaceEntryRecursive(BlockT *NewEntry) {
  65. std::vector<RegionT *> RegionQueue;
  66. BlockT *OldEntry = getEntry();
  67. RegionQueue.push_back(static_cast<RegionT *>(this));
  68. while (!RegionQueue.empty()) {
  69. RegionT *R = RegionQueue.back();
  70. RegionQueue.pop_back();
  71. R->replaceEntry(NewEntry);
  72. for (std::unique_ptr<RegionT> &Child : *R) {
  73. if (Child->getEntry() == OldEntry)
  74. RegionQueue.push_back(Child.get());
  75. }
  76. }
  77. }
  78. template <class Tr>
  79. void RegionBase<Tr>::replaceExitRecursive(BlockT *NewExit) {
  80. std::vector<RegionT *> RegionQueue;
  81. BlockT *OldExit = getExit();
  82. RegionQueue.push_back(static_cast<RegionT *>(this));
  83. while (!RegionQueue.empty()) {
  84. RegionT *R = RegionQueue.back();
  85. RegionQueue.pop_back();
  86. R->replaceExit(NewExit);
  87. for (std::unique_ptr<RegionT> &Child : *R) {
  88. if (Child->getExit() == OldExit)
  89. RegionQueue.push_back(Child.get());
  90. }
  91. }
  92. }
  93. template <class Tr>
  94. bool RegionBase<Tr>::contains(const BlockT *B) const {
  95. BlockT *BB = const_cast<BlockT *>(B);
  96. if (!DT->getNode(BB))
  97. return false;
  98. BlockT *entry = getEntry(), *exit = getExit();
  99. // Toplevel region.
  100. if (!exit)
  101. return true;
  102. return (DT->dominates(entry, BB) &&
  103. !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
  104. }
  105. template <class Tr>
  106. bool RegionBase<Tr>::contains(const LoopT *L) const {
  107. // BBs that are not part of any loop are element of the Loop
  108. // described by the NULL pointer. This loop is not part of any region,
  109. // except if the region describes the whole function.
  110. if (!L)
  111. return getExit() == nullptr;
  112. if (!contains(L->getHeader()))
  113. return false;
  114. SmallVector<BlockT *, 8> ExitingBlocks;
  115. L->getExitingBlocks(ExitingBlocks);
  116. for (BlockT *BB : ExitingBlocks) {
  117. if (!contains(BB))
  118. return false;
  119. }
  120. return true;
  121. }
  122. template <class Tr>
  123. typename Tr::LoopT *RegionBase<Tr>::outermostLoopInRegion(LoopT *L) const {
  124. if (!contains(L))
  125. return nullptr;
  126. while (L && contains(L->getParentLoop())) {
  127. L = L->getParentLoop();
  128. }
  129. return L;
  130. }
  131. template <class Tr>
  132. typename Tr::LoopT *RegionBase<Tr>::outermostLoopInRegion(LoopInfoT *LI,
  133. BlockT *BB) const {
  134. assert(LI && BB && "LI and BB cannot be null!");
  135. LoopT *L = LI->getLoopFor(BB);
  136. return outermostLoopInRegion(L);
  137. }
  138. template <class Tr>
  139. typename RegionBase<Tr>::BlockT *RegionBase<Tr>::getEnteringBlock() const {
  140. BlockT *entry = getEntry();
  141. BlockT *enteringBlock = nullptr;
  142. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(entry),
  143. InvBlockTraits::child_end(entry))) {
  144. if (DT->getNode(Pred) && !contains(Pred)) {
  145. if (enteringBlock)
  146. return nullptr;
  147. enteringBlock = Pred;
  148. }
  149. }
  150. return enteringBlock;
  151. }
  152. template <class Tr>
  153. bool RegionBase<Tr>::getExitingBlocks(
  154. SmallVectorImpl<BlockT *> &Exitings) const {
  155. bool CoverAll = true;
  156. if (!exit)
  157. return CoverAll;
  158. for (PredIterTy PI = InvBlockTraits::child_begin(exit),
  159. PE = InvBlockTraits::child_end(exit);
  160. PI != PE; ++PI) {
  161. BlockT *Pred = *PI;
  162. if (contains(Pred)) {
  163. Exitings.push_back(Pred);
  164. continue;
  165. }
  166. CoverAll = false;
  167. }
  168. return CoverAll;
  169. }
  170. template <class Tr>
  171. typename RegionBase<Tr>::BlockT *RegionBase<Tr>::getExitingBlock() const {
  172. BlockT *exit = getExit();
  173. BlockT *exitingBlock = nullptr;
  174. if (!exit)
  175. return nullptr;
  176. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(exit),
  177. InvBlockTraits::child_end(exit))) {
  178. if (contains(Pred)) {
  179. if (exitingBlock)
  180. return nullptr;
  181. exitingBlock = Pred;
  182. }
  183. }
  184. return exitingBlock;
  185. }
  186. template <class Tr>
  187. bool RegionBase<Tr>::isSimple() const {
  188. return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
  189. }
  190. template <class Tr>
  191. std::string RegionBase<Tr>::getNameStr() const {
  192. std::string exitName;
  193. std::string entryName;
  194. if (getEntry()->getName().empty()) {
  195. raw_string_ostream OS(entryName);
  196. getEntry()->printAsOperand(OS, false);
  197. } else
  198. entryName = std::string(getEntry()->getName());
  199. if (getExit()) {
  200. if (getExit()->getName().empty()) {
  201. raw_string_ostream OS(exitName);
  202. getExit()->printAsOperand(OS, false);
  203. } else
  204. exitName = std::string(getExit()->getName());
  205. } else
  206. exitName = "<Function Return>";
  207. return entryName + " => " + exitName;
  208. }
  209. template <class Tr>
  210. void RegionBase<Tr>::verifyBBInRegion(BlockT *BB) const {
  211. if (!contains(BB))
  212. report_fatal_error("Broken region found: enumerated BB not in region!");
  213. BlockT *entry = getEntry(), *exit = getExit();
  214. for (BlockT *Succ :
  215. make_range(BlockTraits::child_begin(BB), BlockTraits::child_end(BB))) {
  216. if (!contains(Succ) && exit != Succ)
  217. report_fatal_error("Broken region found: edges leaving the region must go "
  218. "to the exit node!");
  219. }
  220. if (entry != BB) {
  221. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(BB),
  222. InvBlockTraits::child_end(BB))) {
  223. if (!contains(Pred))
  224. report_fatal_error("Broken region found: edges entering the region must "
  225. "go to the entry node!");
  226. }
  227. }
  228. }
  229. template <class Tr>
  230. void RegionBase<Tr>::verifyWalk(BlockT *BB, std::set<BlockT *> *visited) const {
  231. BlockT *exit = getExit();
  232. visited->insert(BB);
  233. verifyBBInRegion(BB);
  234. for (BlockT *Succ :
  235. make_range(BlockTraits::child_begin(BB), BlockTraits::child_end(BB))) {
  236. if (Succ != exit && visited->find(Succ) == visited->end())
  237. verifyWalk(Succ, visited);
  238. }
  239. }
  240. template <class Tr>
  241. void RegionBase<Tr>::verifyRegion() const {
  242. // Only do verification when user wants to, otherwise this expensive check
  243. // will be invoked by PMDataManager::verifyPreservedAnalysis when
  244. // a regionpass (marked PreservedAll) finish.
  245. if (!RegionInfoBase<Tr>::VerifyRegionInfo)
  246. return;
  247. std::set<BlockT *> visited;
  248. verifyWalk(getEntry(), &visited);
  249. }
  250. template <class Tr>
  251. void RegionBase<Tr>::verifyRegionNest() const {
  252. for (const std::unique_ptr<RegionT> &R : *this)
  253. R->verifyRegionNest();
  254. verifyRegion();
  255. }
  256. template <class Tr>
  257. typename RegionBase<Tr>::element_iterator RegionBase<Tr>::element_begin() {
  258. return GraphTraits<RegionT *>::nodes_begin(static_cast<RegionT *>(this));
  259. }
  260. template <class Tr>
  261. typename RegionBase<Tr>::element_iterator RegionBase<Tr>::element_end() {
  262. return GraphTraits<RegionT *>::nodes_end(static_cast<RegionT *>(this));
  263. }
  264. template <class Tr>
  265. typename RegionBase<Tr>::const_element_iterator
  266. RegionBase<Tr>::element_begin() const {
  267. return GraphTraits<const RegionT *>::nodes_begin(
  268. static_cast<const RegionT *>(this));
  269. }
  270. template <class Tr>
  271. typename RegionBase<Tr>::const_element_iterator
  272. RegionBase<Tr>::element_end() const {
  273. return GraphTraits<const RegionT *>::nodes_end(
  274. static_cast<const RegionT *>(this));
  275. }
  276. template <class Tr>
  277. typename Tr::RegionT *RegionBase<Tr>::getSubRegionNode(BlockT *BB) const {
  278. using RegionT = typename Tr::RegionT;
  279. RegionT *R = RI->getRegionFor(BB);
  280. if (!R || R == this)
  281. return nullptr;
  282. // If we pass the BB out of this region, that means our code is broken.
  283. assert(contains(R) && "BB not in current region!");
  284. while (contains(R->getParent()) && R->getParent() != this)
  285. R = R->getParent();
  286. if (R->getEntry() != BB)
  287. return nullptr;
  288. return R;
  289. }
  290. template <class Tr>
  291. typename Tr::RegionNodeT *RegionBase<Tr>::getBBNode(BlockT *BB) const {
  292. assert(contains(BB) && "Can get BB node out of this region!");
  293. typename BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
  294. if (at == BBNodeMap.end()) {
  295. auto Deconst = const_cast<RegionBase<Tr> *>(this);
  296. typename BBNodeMapT::value_type V = {
  297. BB,
  298. std::make_unique<RegionNodeT>(static_cast<RegionT *>(Deconst), BB)};
  299. at = BBNodeMap.insert(std::move(V)).first;
  300. }
  301. return at->second.get();
  302. }
  303. template <class Tr>
  304. typename Tr::RegionNodeT *RegionBase<Tr>::getNode(BlockT *BB) const {
  305. assert(contains(BB) && "Can get BB node out of this region!");
  306. if (RegionT *Child = getSubRegionNode(BB))
  307. return Child->getNode();
  308. return getBBNode(BB);
  309. }
  310. template <class Tr>
  311. void RegionBase<Tr>::transferChildrenTo(RegionT *To) {
  312. for (std::unique_ptr<RegionT> &R : *this) {
  313. R->parent = To;
  314. To->children.push_back(std::move(R));
  315. }
  316. children.clear();
  317. }
  318. template <class Tr>
  319. void RegionBase<Tr>::addSubRegion(RegionT *SubRegion, bool moveChildren) {
  320. assert(!SubRegion->parent && "SubRegion already has a parent!");
  321. assert(llvm::find_if(*this,
  322. [&](const std::unique_ptr<RegionT> &R) {
  323. return R.get() == SubRegion;
  324. }) == children.end() &&
  325. "Subregion already exists!");
  326. SubRegion->parent = static_cast<RegionT *>(this);
  327. children.push_back(std::unique_ptr<RegionT>(SubRegion));
  328. if (!moveChildren)
  329. return;
  330. assert(SubRegion->children.empty() &&
  331. "SubRegions that contain children are not supported");
  332. for (RegionNodeT *Element : elements()) {
  333. if (!Element->isSubRegion()) {
  334. BlockT *BB = Element->template getNodeAs<BlockT>();
  335. if (SubRegion->contains(BB))
  336. RI->setRegionFor(BB, SubRegion);
  337. }
  338. }
  339. std::vector<std::unique_ptr<RegionT>> Keep;
  340. for (std::unique_ptr<RegionT> &R : *this) {
  341. if (SubRegion->contains(R.get()) && R.get() != SubRegion) {
  342. R->parent = SubRegion;
  343. SubRegion->children.push_back(std::move(R));
  344. } else
  345. Keep.push_back(std::move(R));
  346. }
  347. children.clear();
  348. children.insert(
  349. children.begin(),
  350. std::move_iterator<typename RegionSet::iterator>(Keep.begin()),
  351. std::move_iterator<typename RegionSet::iterator>(Keep.end()));
  352. }
  353. template <class Tr>
  354. typename Tr::RegionT *RegionBase<Tr>::removeSubRegion(RegionT *Child) {
  355. assert(Child->parent == this && "Child is not a child of this region!");
  356. Child->parent = nullptr;
  357. typename RegionSet::iterator I =
  358. llvm::find_if(children, [&](const std::unique_ptr<RegionT> &R) {
  359. return R.get() == Child;
  360. });
  361. assert(I != children.end() && "Region does not exit. Unable to remove.");
  362. children.erase(children.begin() + (I - begin()));
  363. return Child;
  364. }
  365. template <class Tr>
  366. unsigned RegionBase<Tr>::getDepth() const {
  367. unsigned Depth = 0;
  368. for (RegionT *R = getParent(); R != nullptr; R = R->getParent())
  369. ++Depth;
  370. return Depth;
  371. }
  372. template <class Tr>
  373. typename Tr::RegionT *RegionBase<Tr>::getExpandedRegion() const {
  374. unsigned NumSuccessors = Tr::getNumSuccessors(exit);
  375. if (NumSuccessors == 0)
  376. return nullptr;
  377. RegionT *R = RI->getRegionFor(exit);
  378. if (R->getEntry() != exit) {
  379. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(getExit()),
  380. InvBlockTraits::child_end(getExit())))
  381. if (!contains(Pred))
  382. return nullptr;
  383. if (Tr::getNumSuccessors(exit) == 1)
  384. return new RegionT(getEntry(), *BlockTraits::child_begin(exit), RI, DT);
  385. return nullptr;
  386. }
  387. while (R->getParent() && R->getParent()->getEntry() == exit)
  388. R = R->getParent();
  389. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(getExit()),
  390. InvBlockTraits::child_end(getExit()))) {
  391. if (!(contains(Pred) || R->contains(Pred)))
  392. return nullptr;
  393. }
  394. return new RegionT(getEntry(), R->getExit(), RI, DT);
  395. }
  396. template <class Tr>
  397. void RegionBase<Tr>::print(raw_ostream &OS, bool print_tree, unsigned level,
  398. PrintStyle Style) const {
  399. if (print_tree)
  400. OS.indent(level * 2) << '[' << level << "] " << getNameStr();
  401. else
  402. OS.indent(level * 2) << getNameStr();
  403. OS << '\n';
  404. if (Style != PrintNone) {
  405. OS.indent(level * 2) << "{\n";
  406. OS.indent(level * 2 + 2);
  407. if (Style == PrintBB) {
  408. for (const auto *BB : blocks())
  409. OS << BB->getName() << ", "; // TODO: remove the last ","
  410. } else if (Style == PrintRN) {
  411. for (const RegionNodeT *Element : elements()) {
  412. OS << *Element << ", "; // TODO: remove the last ",
  413. }
  414. }
  415. OS << '\n';
  416. }
  417. if (print_tree) {
  418. for (const std::unique_ptr<RegionT> &R : *this)
  419. R->print(OS, print_tree, level + 1, Style);
  420. }
  421. if (Style != PrintNone)
  422. OS.indent(level * 2) << "} \n";
  423. }
  424. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  425. template <class Tr>
  426. void RegionBase<Tr>::dump() const {
  427. print(dbgs(), true, getDepth(), RegionInfoBase<Tr>::printStyle);
  428. }
  429. #endif
  430. template <class Tr>
  431. void RegionBase<Tr>::clearNodeCache() {
  432. BBNodeMap.clear();
  433. for (std::unique_ptr<RegionT> &R : *this)
  434. R->clearNodeCache();
  435. }
  436. //===----------------------------------------------------------------------===//
  437. // RegionInfoBase implementation
  438. //
  439. template <class Tr>
  440. RegionInfoBase<Tr>::RegionInfoBase() = default;
  441. template <class Tr>
  442. RegionInfoBase<Tr>::~RegionInfoBase() {
  443. releaseMemory();
  444. }
  445. template <class Tr>
  446. void RegionInfoBase<Tr>::verifyBBMap(const RegionT *R) const {
  447. assert(R && "Re must be non-null");
  448. for (const typename Tr::RegionNodeT *Element : R->elements()) {
  449. if (Element->isSubRegion()) {
  450. const RegionT *SR = Element->template getNodeAs<RegionT>();
  451. verifyBBMap(SR);
  452. } else {
  453. BlockT *BB = Element->template getNodeAs<BlockT>();
  454. if (getRegionFor(BB) != R)
  455. report_fatal_error("BB map does not match region nesting");
  456. }
  457. }
  458. }
  459. template <class Tr>
  460. bool RegionInfoBase<Tr>::isCommonDomFrontier(BlockT *BB, BlockT *entry,
  461. BlockT *exit) const {
  462. for (BlockT *P : make_range(InvBlockTraits::child_begin(BB),
  463. InvBlockTraits::child_end(BB))) {
  464. if (DT->dominates(entry, P) && !DT->dominates(exit, P))
  465. return false;
  466. }
  467. return true;
  468. }
  469. template <class Tr>
  470. bool RegionInfoBase<Tr>::isRegion(BlockT *entry, BlockT *exit) const {
  471. assert(entry && exit && "entry and exit must not be null!");
  472. using DST = typename DomFrontierT::DomSetType;
  473. DST *entrySuccs = &DF->find(entry)->second;
  474. // Exit is the header of a loop that contains the entry. In this case,
  475. // the dominance frontier must only contain the exit.
  476. if (!DT->dominates(entry, exit)) {
  477. for (BlockT *successor : *entrySuccs) {
  478. if (successor != exit && successor != entry)
  479. return false;
  480. }
  481. return true;
  482. }
  483. DST *exitSuccs = &DF->find(exit)->second;
  484. // Do not allow edges leaving the region.
  485. for (BlockT *Succ : *entrySuccs) {
  486. if (Succ == exit || Succ == entry)
  487. continue;
  488. if (exitSuccs->find(Succ) == exitSuccs->end())
  489. return false;
  490. if (!isCommonDomFrontier(Succ, entry, exit))
  491. return false;
  492. }
  493. // Do not allow edges pointing into the region.
  494. for (BlockT *Succ : *exitSuccs) {
  495. if (DT->properlyDominates(entry, Succ) && Succ != exit)
  496. return false;
  497. }
  498. return true;
  499. }
  500. template <class Tr>
  501. void RegionInfoBase<Tr>::insertShortCut(BlockT *entry, BlockT *exit,
  502. BBtoBBMap *ShortCut) const {
  503. assert(entry && exit && "entry and exit must not be null!");
  504. typename BBtoBBMap::iterator e = ShortCut->find(exit);
  505. if (e == ShortCut->end())
  506. // No further region at exit available.
  507. (*ShortCut)[entry] = exit;
  508. else {
  509. // We found a region e that starts at exit. Therefore (entry, e->second)
  510. // is also a region, that is larger than (entry, exit). Insert the
  511. // larger one.
  512. BlockT *BB = e->second;
  513. (*ShortCut)[entry] = BB;
  514. }
  515. }
  516. template <class Tr>
  517. typename Tr::DomTreeNodeT *
  518. RegionInfoBase<Tr>::getNextPostDom(DomTreeNodeT *N, BBtoBBMap *ShortCut) const {
  519. typename BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
  520. if (e == ShortCut->end())
  521. return N->getIDom();
  522. return PDT->getNode(e->second)->getIDom();
  523. }
  524. template <class Tr>
  525. bool RegionInfoBase<Tr>::isTrivialRegion(BlockT *entry, BlockT *exit) const {
  526. assert(entry && exit && "entry and exit must not be null!");
  527. unsigned num_successors =
  528. BlockTraits::child_end(entry) - BlockTraits::child_begin(entry);
  529. if (num_successors <= 1 && exit == *(BlockTraits::child_begin(entry)))
  530. return true;
  531. return false;
  532. }
  533. template <class Tr>
  534. typename Tr::RegionT *RegionInfoBase<Tr>::createRegion(BlockT *entry,
  535. BlockT *exit) {
  536. assert(entry && exit && "entry and exit must not be null!");
  537. if (isTrivialRegion(entry, exit))
  538. return nullptr;
  539. RegionT *region =
  540. new RegionT(entry, exit, static_cast<RegionInfoT *>(this), DT);
  541. BBtoRegion.insert({entry, region});
  542. #ifdef EXPENSIVE_CHECKS
  543. region->verifyRegion();
  544. #else
  545. LLVM_DEBUG(region->verifyRegion());
  546. #endif
  547. updateStatistics(region);
  548. return region;
  549. }
  550. template <class Tr>
  551. void RegionInfoBase<Tr>::findRegionsWithEntry(BlockT *entry,
  552. BBtoBBMap *ShortCut) {
  553. assert(entry);
  554. DomTreeNodeT *N = PDT->getNode(entry);
  555. if (!N)
  556. return;
  557. RegionT *lastRegion = nullptr;
  558. BlockT *lastExit = entry;
  559. // As only a BasicBlock that postdominates entry can finish a region, walk the
  560. // post dominance tree upwards.
  561. while ((N = getNextPostDom(N, ShortCut))) {
  562. BlockT *exit = N->getBlock();
  563. if (!exit)
  564. break;
  565. if (isRegion(entry, exit)) {
  566. RegionT *newRegion = createRegion(entry, exit);
  567. if (lastRegion)
  568. newRegion->addSubRegion(lastRegion);
  569. lastRegion = newRegion;
  570. lastExit = exit;
  571. }
  572. // This can never be a region, so stop the search.
  573. if (!DT->dominates(entry, exit))
  574. break;
  575. }
  576. // Tried to create regions from entry to lastExit. Next time take a
  577. // shortcut from entry to lastExit.
  578. if (lastExit != entry)
  579. insertShortCut(entry, lastExit, ShortCut);
  580. }
  581. template <class Tr>
  582. void RegionInfoBase<Tr>::scanForRegions(FuncT &F, BBtoBBMap *ShortCut) {
  583. using FuncPtrT = std::add_pointer_t<FuncT>;
  584. BlockT *entry = GraphTraits<FuncPtrT>::getEntryNode(&F);
  585. DomTreeNodeT *N = DT->getNode(entry);
  586. // Iterate over the dominance tree in post order to start with the small
  587. // regions from the bottom of the dominance tree. If the small regions are
  588. // detected first, detection of bigger regions is faster, as we can jump
  589. // over the small regions.
  590. for (auto DomNode : post_order(N))
  591. findRegionsWithEntry(DomNode->getBlock(), ShortCut);
  592. }
  593. template <class Tr>
  594. typename Tr::RegionT *RegionInfoBase<Tr>::getTopMostParent(RegionT *region) {
  595. while (region->getParent())
  596. region = region->getParent();
  597. return region;
  598. }
  599. template <class Tr>
  600. void RegionInfoBase<Tr>::buildRegionsTree(DomTreeNodeT *N, RegionT *region) {
  601. BlockT *BB = N->getBlock();
  602. // Passed region exit
  603. while (BB == region->getExit())
  604. region = region->getParent();
  605. typename BBtoRegionMap::iterator it = BBtoRegion.find(BB);
  606. // This basic block is a start block of a region. It is already in the
  607. // BBtoRegion relation. Only the child basic blocks have to be updated.
  608. if (it != BBtoRegion.end()) {
  609. RegionT *newRegion = it->second;
  610. region->addSubRegion(getTopMostParent(newRegion));
  611. region = newRegion;
  612. } else {
  613. BBtoRegion[BB] = region;
  614. }
  615. for (DomTreeNodeBase<BlockT> *C : *N) {
  616. buildRegionsTree(C, region);
  617. }
  618. }
  619. #ifdef EXPENSIVE_CHECKS
  620. template <class Tr>
  621. bool RegionInfoBase<Tr>::VerifyRegionInfo = true;
  622. #else
  623. template <class Tr>
  624. bool RegionInfoBase<Tr>::VerifyRegionInfo = false;
  625. #endif
  626. template <class Tr>
  627. typename Tr::RegionT::PrintStyle RegionInfoBase<Tr>::printStyle =
  628. RegionBase<Tr>::PrintNone;
  629. template <class Tr>
  630. void RegionInfoBase<Tr>::print(raw_ostream &OS) const {
  631. OS << "Region tree:\n";
  632. TopLevelRegion->print(OS, true, 0, printStyle);
  633. OS << "End region tree\n";
  634. }
  635. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  636. template <class Tr>
  637. void RegionInfoBase<Tr>::dump() const { print(dbgs()); }
  638. #endif
  639. template <class Tr>
  640. void RegionInfoBase<Tr>::releaseMemory() {
  641. BBtoRegion.clear();
  642. if (TopLevelRegion)
  643. delete TopLevelRegion;
  644. TopLevelRegion = nullptr;
  645. }
  646. template <class Tr>
  647. void RegionInfoBase<Tr>::verifyAnalysis() const {
  648. // Do only verify regions if explicitely activated using EXPENSIVE_CHECKS or
  649. // -verify-region-info
  650. if (!RegionInfoBase<Tr>::VerifyRegionInfo)
  651. return;
  652. TopLevelRegion->verifyRegionNest();
  653. verifyBBMap(TopLevelRegion);
  654. }
  655. // Region pass manager support.
  656. template <class Tr>
  657. typename Tr::RegionT *RegionInfoBase<Tr>::getRegionFor(BlockT *BB) const {
  658. return BBtoRegion.lookup(BB);
  659. }
  660. template <class Tr>
  661. void RegionInfoBase<Tr>::setRegionFor(BlockT *BB, RegionT *R) {
  662. BBtoRegion[BB] = R;
  663. }
  664. template <class Tr>
  665. typename Tr::RegionT *RegionInfoBase<Tr>::operator[](BlockT *BB) const {
  666. return getRegionFor(BB);
  667. }
  668. template <class Tr>
  669. typename RegionInfoBase<Tr>::BlockT *
  670. RegionInfoBase<Tr>::getMaxRegionExit(BlockT *BB) const {
  671. BlockT *Exit = nullptr;
  672. while (true) {
  673. // Get largest region that starts at BB.
  674. RegionT *R = getRegionFor(BB);
  675. while (R && R->getParent() && R->getParent()->getEntry() == BB)
  676. R = R->getParent();
  677. // Get the single exit of BB.
  678. if (R && R->getEntry() == BB)
  679. Exit = R->getExit();
  680. else {
  681. auto next = BlockTraits::child_begin(BB);
  682. ++next;
  683. if (next == BlockTraits::child_end(BB))
  684. Exit = *BlockTraits::child_begin(BB);
  685. else // No single exit exists.
  686. return Exit;
  687. }
  688. // Get largest region that starts at Exit.
  689. RegionT *ExitR = getRegionFor(Exit);
  690. while (ExitR && ExitR->getParent() &&
  691. ExitR->getParent()->getEntry() == Exit)
  692. ExitR = ExitR->getParent();
  693. for (BlockT *Pred : make_range(InvBlockTraits::child_begin(Exit),
  694. InvBlockTraits::child_end(Exit))) {
  695. if (!R->contains(Pred) && !ExitR->contains(Pred))
  696. break;
  697. }
  698. // This stops infinite cycles.
  699. if (DT->dominates(Exit, BB))
  700. break;
  701. BB = Exit;
  702. }
  703. return Exit;
  704. }
  705. template <class Tr>
  706. typename Tr::RegionT *RegionInfoBase<Tr>::getCommonRegion(RegionT *A,
  707. RegionT *B) const {
  708. assert(A && B && "One of the Regions is NULL");
  709. if (A->contains(B))
  710. return A;
  711. while (!B->contains(A))
  712. B = B->getParent();
  713. return B;
  714. }
  715. template <class Tr>
  716. typename Tr::RegionT *
  717. RegionInfoBase<Tr>::getCommonRegion(SmallVectorImpl<RegionT *> &Regions) const {
  718. RegionT *ret = Regions.pop_back_val();
  719. for (RegionT *R : Regions)
  720. ret = getCommonRegion(ret, R);
  721. return ret;
  722. }
  723. template <class Tr>
  724. typename Tr::RegionT *
  725. RegionInfoBase<Tr>::getCommonRegion(SmallVectorImpl<BlockT *> &BBs) const {
  726. RegionT *ret = getRegionFor(BBs.back());
  727. BBs.pop_back();
  728. for (BlockT *BB : BBs)
  729. ret = getCommonRegion(ret, getRegionFor(BB));
  730. return ret;
  731. }
  732. template <class Tr>
  733. void RegionInfoBase<Tr>::calculate(FuncT &F) {
  734. using FuncPtrT = std::add_pointer_t<FuncT>;
  735. // ShortCut a function where for every BB the exit of the largest region
  736. // starting with BB is stored. These regions can be threated as single BBS.
  737. // This improves performance on linear CFGs.
  738. BBtoBBMap ShortCut;
  739. scanForRegions(F, &ShortCut);
  740. BlockT *BB = GraphTraits<FuncPtrT>::getEntryNode(&F);
  741. buildRegionsTree(DT->getNode(BB), TopLevelRegion);
  742. }
  743. } // end namespace llvm
  744. #undef DEBUG_TYPE
  745. #endif // LLVM_ANALYSIS_REGIONINFOIMPL_H
  746. #ifdef __GNUC__
  747. #pragma GCC diagnostic pop
  748. #endif