LoopInfoImpl.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Analysis/LoopInfoImpl.h - Natural Loop Calculator ---*- 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. //
  14. // This is the generic implementation of LoopInfo used for both Loops and
  15. // MachineLoops.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_ANALYSIS_LOOPINFOIMPL_H
  19. #define LLVM_ANALYSIS_LOOPINFOIMPL_H
  20. #include "llvm/ADT/DepthFirstIterator.h"
  21. #include "llvm/ADT/PostOrderIterator.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SetOperations.h"
  24. #include "llvm/Analysis/LoopInfo.h"
  25. #include "llvm/IR/Dominators.h"
  26. namespace llvm {
  27. //===----------------------------------------------------------------------===//
  28. // APIs for simple analysis of the loop. See header notes.
  29. /// getExitingBlocks - Return all blocks inside the loop that have successors
  30. /// outside of the loop. These are the blocks _inside of the current loop_
  31. /// which branch out. The returned list is always unique.
  32. ///
  33. template <class BlockT, class LoopT>
  34. void LoopBase<BlockT, LoopT>::getExitingBlocks(
  35. SmallVectorImpl<BlockT *> &ExitingBlocks) const {
  36. assert(!isInvalid() && "Loop not in a valid state!");
  37. for (const auto BB : blocks())
  38. for (auto *Succ : children<BlockT *>(BB))
  39. if (!contains(Succ)) {
  40. // Not in current loop? It must be an exit block.
  41. ExitingBlocks.push_back(BB);
  42. break;
  43. }
  44. }
  45. /// getExitingBlock - If getExitingBlocks would return exactly one block,
  46. /// return that block. Otherwise return null.
  47. template <class BlockT, class LoopT>
  48. BlockT *LoopBase<BlockT, LoopT>::getExitingBlock() const {
  49. assert(!isInvalid() && "Loop not in a valid state!");
  50. SmallVector<BlockT *, 8> ExitingBlocks;
  51. getExitingBlocks(ExitingBlocks);
  52. if (ExitingBlocks.size() == 1)
  53. return ExitingBlocks[0];
  54. return nullptr;
  55. }
  56. /// getExitBlocks - Return all of the successor blocks of this loop. These
  57. /// are the blocks _outside of the current loop_ which are branched to.
  58. ///
  59. template <class BlockT, class LoopT>
  60. void LoopBase<BlockT, LoopT>::getExitBlocks(
  61. SmallVectorImpl<BlockT *> &ExitBlocks) const {
  62. assert(!isInvalid() && "Loop not in a valid state!");
  63. for (const auto BB : blocks())
  64. for (auto *Succ : children<BlockT *>(BB))
  65. if (!contains(Succ))
  66. // Not in current loop? It must be an exit block.
  67. ExitBlocks.push_back(Succ);
  68. }
  69. template <class BlockT, class LoopT>
  70. bool LoopBase<BlockT, LoopT>::hasNoExitBlocks() const {
  71. SmallVector<BlockT *, 8> ExitBlocks;
  72. getExitBlocks(ExitBlocks);
  73. return ExitBlocks.empty();
  74. }
  75. /// getExitBlock - If getExitBlocks would return exactly one block,
  76. /// return that block. Otherwise return null.
  77. template <class BlockT, class LoopT>
  78. BlockT *LoopBase<BlockT, LoopT>::getExitBlock() const {
  79. assert(!isInvalid() && "Loop not in a valid state!");
  80. SmallVector<BlockT *, 8> ExitBlocks;
  81. getExitBlocks(ExitBlocks);
  82. if (ExitBlocks.size() == 1)
  83. return ExitBlocks[0];
  84. return nullptr;
  85. }
  86. template <class BlockT, class LoopT>
  87. bool LoopBase<BlockT, LoopT>::hasDedicatedExits() const {
  88. // Each predecessor of each exit block of a normal loop is contained
  89. // within the loop.
  90. SmallVector<BlockT *, 4> UniqueExitBlocks;
  91. getUniqueExitBlocks(UniqueExitBlocks);
  92. for (BlockT *EB : UniqueExitBlocks)
  93. for (BlockT *Predecessor : children<Inverse<BlockT *>>(EB))
  94. if (!contains(Predecessor))
  95. return false;
  96. // All the requirements are met.
  97. return true;
  98. }
  99. // Helper function to get unique loop exits. Pred is a predicate pointing to
  100. // BasicBlocks in a loop which should be considered to find loop exits.
  101. template <class BlockT, class LoopT, typename PredicateT>
  102. void getUniqueExitBlocksHelper(const LoopT *L,
  103. SmallVectorImpl<BlockT *> &ExitBlocks,
  104. PredicateT Pred) {
  105. assert(!L->isInvalid() && "Loop not in a valid state!");
  106. SmallPtrSet<BlockT *, 32> Visited;
  107. auto Filtered = make_filter_range(L->blocks(), Pred);
  108. for (BlockT *BB : Filtered)
  109. for (BlockT *Successor : children<BlockT *>(BB))
  110. if (!L->contains(Successor))
  111. if (Visited.insert(Successor).second)
  112. ExitBlocks.push_back(Successor);
  113. }
  114. template <class BlockT, class LoopT>
  115. void LoopBase<BlockT, LoopT>::getUniqueExitBlocks(
  116. SmallVectorImpl<BlockT *> &ExitBlocks) const {
  117. getUniqueExitBlocksHelper(this, ExitBlocks,
  118. [](const BlockT *BB) { return true; });
  119. }
  120. template <class BlockT, class LoopT>
  121. void LoopBase<BlockT, LoopT>::getUniqueNonLatchExitBlocks(
  122. SmallVectorImpl<BlockT *> &ExitBlocks) const {
  123. const BlockT *Latch = getLoopLatch();
  124. assert(Latch && "Latch block must exists");
  125. getUniqueExitBlocksHelper(this, ExitBlocks,
  126. [Latch](const BlockT *BB) { return BB != Latch; });
  127. }
  128. template <class BlockT, class LoopT>
  129. BlockT *LoopBase<BlockT, LoopT>::getUniqueExitBlock() const {
  130. SmallVector<BlockT *, 8> UniqueExitBlocks;
  131. getUniqueExitBlocks(UniqueExitBlocks);
  132. if (UniqueExitBlocks.size() == 1)
  133. return UniqueExitBlocks[0];
  134. return nullptr;
  135. }
  136. /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
  137. template <class BlockT, class LoopT>
  138. void LoopBase<BlockT, LoopT>::getExitEdges(
  139. SmallVectorImpl<Edge> &ExitEdges) const {
  140. assert(!isInvalid() && "Loop not in a valid state!");
  141. for (const auto BB : blocks())
  142. for (auto *Succ : children<BlockT *>(BB))
  143. if (!contains(Succ))
  144. // Not in current loop? It must be an exit block.
  145. ExitEdges.emplace_back(BB, Succ);
  146. }
  147. /// getLoopPreheader - If there is a preheader for this loop, return it. A
  148. /// loop has a preheader if there is only one edge to the header of the loop
  149. /// from outside of the loop and it is legal to hoist instructions into the
  150. /// predecessor. If this is the case, the block branching to the header of the
  151. /// loop is the preheader node.
  152. ///
  153. /// This method returns null if there is no preheader for the loop.
  154. ///
  155. template <class BlockT, class LoopT>
  156. BlockT *LoopBase<BlockT, LoopT>::getLoopPreheader() const {
  157. assert(!isInvalid() && "Loop not in a valid state!");
  158. // Keep track of nodes outside the loop branching to the header...
  159. BlockT *Out = getLoopPredecessor();
  160. if (!Out)
  161. return nullptr;
  162. // Make sure we are allowed to hoist instructions into the predecessor.
  163. if (!Out->isLegalToHoistInto())
  164. return nullptr;
  165. // Make sure there is only one exit out of the preheader.
  166. typedef GraphTraits<BlockT *> BlockTraits;
  167. typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
  168. ++SI;
  169. if (SI != BlockTraits::child_end(Out))
  170. return nullptr; // Multiple exits from the block, must not be a preheader.
  171. // The predecessor has exactly one successor, so it is a preheader.
  172. return Out;
  173. }
  174. /// getLoopPredecessor - If the given loop's header has exactly one unique
  175. /// predecessor outside the loop, return it. Otherwise return null.
  176. /// This is less strict that the loop "preheader" concept, which requires
  177. /// the predecessor to have exactly one successor.
  178. ///
  179. template <class BlockT, class LoopT>
  180. BlockT *LoopBase<BlockT, LoopT>::getLoopPredecessor() const {
  181. assert(!isInvalid() && "Loop not in a valid state!");
  182. // Keep track of nodes outside the loop branching to the header...
  183. BlockT *Out = nullptr;
  184. // Loop over the predecessors of the header node...
  185. BlockT *Header = getHeader();
  186. for (const auto Pred : children<Inverse<BlockT *>>(Header)) {
  187. if (!contains(Pred)) { // If the block is not in the loop...
  188. if (Out && Out != Pred)
  189. return nullptr; // Multiple predecessors outside the loop
  190. Out = Pred;
  191. }
  192. }
  193. return Out;
  194. }
  195. /// getLoopLatch - If there is a single latch block for this loop, return it.
  196. /// A latch block is a block that contains a branch back to the header.
  197. template <class BlockT, class LoopT>
  198. BlockT *LoopBase<BlockT, LoopT>::getLoopLatch() const {
  199. assert(!isInvalid() && "Loop not in a valid state!");
  200. BlockT *Header = getHeader();
  201. BlockT *Latch = nullptr;
  202. for (const auto Pred : children<Inverse<BlockT *>>(Header)) {
  203. if (contains(Pred)) {
  204. if (Latch)
  205. return nullptr;
  206. Latch = Pred;
  207. }
  208. }
  209. return Latch;
  210. }
  211. //===----------------------------------------------------------------------===//
  212. // APIs for updating loop information after changing the CFG
  213. //
  214. /// addBasicBlockToLoop - This method is used by other analyses to update loop
  215. /// information. NewBB is set to be a new member of the current loop.
  216. /// Because of this, it is added as a member of all parent loops, and is added
  217. /// to the specified LoopInfo object as being in the current basic block. It
  218. /// is not valid to replace the loop header with this method.
  219. ///
  220. template <class BlockT, class LoopT>
  221. void LoopBase<BlockT, LoopT>::addBasicBlockToLoop(
  222. BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
  223. assert(!isInvalid() && "Loop not in a valid state!");
  224. #ifndef NDEBUG
  225. if (!Blocks.empty()) {
  226. auto SameHeader = LIB[getHeader()];
  227. assert(contains(SameHeader) && getHeader() == SameHeader->getHeader() &&
  228. "Incorrect LI specified for this loop!");
  229. }
  230. #endif
  231. assert(NewBB && "Cannot add a null basic block to the loop!");
  232. assert(!LIB[NewBB] && "BasicBlock already in the loop!");
  233. LoopT *L = static_cast<LoopT *>(this);
  234. // Add the loop mapping to the LoopInfo object...
  235. LIB.BBMap[NewBB] = L;
  236. // Add the basic block to this loop and all parent loops...
  237. while (L) {
  238. L->addBlockEntry(NewBB);
  239. L = L->getParentLoop();
  240. }
  241. }
  242. /// replaceChildLoopWith - This is used when splitting loops up. It replaces
  243. /// the OldChild entry in our children list with NewChild, and updates the
  244. /// parent pointer of OldChild to be null and the NewChild to be this loop.
  245. /// This updates the loop depth of the new child.
  246. template <class BlockT, class LoopT>
  247. void LoopBase<BlockT, LoopT>::replaceChildLoopWith(LoopT *OldChild,
  248. LoopT *NewChild) {
  249. assert(!isInvalid() && "Loop not in a valid state!");
  250. assert(OldChild->ParentLoop == this && "This loop is already broken!");
  251. assert(!NewChild->ParentLoop && "NewChild already has a parent!");
  252. typename std::vector<LoopT *>::iterator I = find(SubLoops, OldChild);
  253. assert(I != SubLoops.end() && "OldChild not in loop!");
  254. *I = NewChild;
  255. OldChild->ParentLoop = nullptr;
  256. NewChild->ParentLoop = static_cast<LoopT *>(this);
  257. }
  258. /// verifyLoop - Verify loop structure
  259. template <class BlockT, class LoopT>
  260. void LoopBase<BlockT, LoopT>::verifyLoop() const {
  261. assert(!isInvalid() && "Loop not in a valid state!");
  262. #ifndef NDEBUG
  263. assert(!Blocks.empty() && "Loop header is missing");
  264. // Setup for using a depth-first iterator to visit every block in the loop.
  265. SmallVector<BlockT *, 8> ExitBBs;
  266. getExitBlocks(ExitBBs);
  267. df_iterator_default_set<BlockT *> VisitSet;
  268. VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
  269. df_ext_iterator<BlockT *, df_iterator_default_set<BlockT *>>
  270. BI = df_ext_begin(getHeader(), VisitSet),
  271. BE = df_ext_end(getHeader(), VisitSet);
  272. // Keep track of the BBs visited.
  273. SmallPtrSet<BlockT *, 8> VisitedBBs;
  274. // Check the individual blocks.
  275. for (; BI != BE; ++BI) {
  276. BlockT *BB = *BI;
  277. assert(std::any_of(GraphTraits<BlockT *>::child_begin(BB),
  278. GraphTraits<BlockT *>::child_end(BB),
  279. [&](BlockT *B) { return contains(B); }) &&
  280. "Loop block has no in-loop successors!");
  281. assert(std::any_of(GraphTraits<Inverse<BlockT *>>::child_begin(BB),
  282. GraphTraits<Inverse<BlockT *>>::child_end(BB),
  283. [&](BlockT *B) { return contains(B); }) &&
  284. "Loop block has no in-loop predecessors!");
  285. SmallVector<BlockT *, 2> OutsideLoopPreds;
  286. std::for_each(GraphTraits<Inverse<BlockT *>>::child_begin(BB),
  287. GraphTraits<Inverse<BlockT *>>::child_end(BB),
  288. [&](BlockT *B) {
  289. if (!contains(B))
  290. OutsideLoopPreds.push_back(B);
  291. });
  292. if (BB == getHeader()) {
  293. assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
  294. } else if (!OutsideLoopPreds.empty()) {
  295. // A non-header loop shouldn't be reachable from outside the loop,
  296. // though it is permitted if the predecessor is not itself actually
  297. // reachable.
  298. BlockT *EntryBB = &BB->getParent()->front();
  299. for (BlockT *CB : depth_first(EntryBB))
  300. for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
  301. assert(CB != OutsideLoopPreds[i] &&
  302. "Loop has multiple entry points!");
  303. }
  304. assert(BB != &getHeader()->getParent()->front() &&
  305. "Loop contains function entry block!");
  306. VisitedBBs.insert(BB);
  307. }
  308. if (VisitedBBs.size() != getNumBlocks()) {
  309. dbgs() << "The following blocks are unreachable in the loop: ";
  310. for (auto BB : Blocks) {
  311. if (!VisitedBBs.count(BB)) {
  312. dbgs() << *BB << "\n";
  313. }
  314. }
  315. assert(false && "Unreachable block in loop");
  316. }
  317. // Check the subloops.
  318. for (iterator I = begin(), E = end(); I != E; ++I)
  319. // Each block in each subloop should be contained within this loop.
  320. for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
  321. BI != BE; ++BI) {
  322. assert(contains(*BI) &&
  323. "Loop does not contain all the blocks of a subloop!");
  324. }
  325. // Check the parent loop pointer.
  326. if (ParentLoop) {
  327. assert(is_contained(*ParentLoop, this) &&
  328. "Loop is not a subloop of its parent!");
  329. }
  330. #endif
  331. }
  332. /// verifyLoop - Verify loop structure of this loop and all nested loops.
  333. template <class BlockT, class LoopT>
  334. void LoopBase<BlockT, LoopT>::verifyLoopNest(
  335. DenseSet<const LoopT *> *Loops) const {
  336. assert(!isInvalid() && "Loop not in a valid state!");
  337. Loops->insert(static_cast<const LoopT *>(this));
  338. // Verify this loop.
  339. verifyLoop();
  340. // Verify the subloops.
  341. for (iterator I = begin(), E = end(); I != E; ++I)
  342. (*I)->verifyLoopNest(Loops);
  343. }
  344. template <class BlockT, class LoopT>
  345. void LoopBase<BlockT, LoopT>::print(raw_ostream &OS, bool Verbose,
  346. bool PrintNested, unsigned Depth) const {
  347. OS.indent(Depth * 2);
  348. if (static_cast<const LoopT *>(this)->isAnnotatedParallel())
  349. OS << "Parallel ";
  350. OS << "Loop at depth " << getLoopDepth() << " containing: ";
  351. BlockT *H = getHeader();
  352. for (unsigned i = 0; i < getBlocks().size(); ++i) {
  353. BlockT *BB = getBlocks()[i];
  354. if (!Verbose) {
  355. if (i)
  356. OS << ",";
  357. BB->printAsOperand(OS, false);
  358. } else
  359. OS << "\n";
  360. if (BB == H)
  361. OS << "<header>";
  362. if (isLoopLatch(BB))
  363. OS << "<latch>";
  364. if (isLoopExiting(BB))
  365. OS << "<exiting>";
  366. if (Verbose)
  367. BB->print(OS);
  368. }
  369. if (PrintNested) {
  370. OS << "\n";
  371. for (iterator I = begin(), E = end(); I != E; ++I)
  372. (*I)->print(OS, /*Verbose*/ false, PrintNested, Depth + 2);
  373. }
  374. }
  375. //===----------------------------------------------------------------------===//
  376. /// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
  377. /// result does / not depend on use list (block predecessor) order.
  378. ///
  379. /// Discover a subloop with the specified backedges such that: All blocks within
  380. /// this loop are mapped to this loop or a subloop. And all subloops within this
  381. /// loop have their parent loop set to this loop or a subloop.
  382. template <class BlockT, class LoopT>
  383. static void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT *> Backedges,
  384. LoopInfoBase<BlockT, LoopT> *LI,
  385. const DomTreeBase<BlockT> &DomTree) {
  386. typedef GraphTraits<Inverse<BlockT *>> InvBlockTraits;
  387. unsigned NumBlocks = 0;
  388. unsigned NumSubloops = 0;
  389. // Perform a backward CFG traversal using a worklist.
  390. std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
  391. while (!ReverseCFGWorklist.empty()) {
  392. BlockT *PredBB = ReverseCFGWorklist.back();
  393. ReverseCFGWorklist.pop_back();
  394. LoopT *Subloop = LI->getLoopFor(PredBB);
  395. if (!Subloop) {
  396. if (!DomTree.isReachableFromEntry(PredBB))
  397. continue;
  398. // This is an undiscovered block. Map it to the current loop.
  399. LI->changeLoopFor(PredBB, L);
  400. ++NumBlocks;
  401. if (PredBB == L->getHeader())
  402. continue;
  403. // Push all block predecessors on the worklist.
  404. ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
  405. InvBlockTraits::child_begin(PredBB),
  406. InvBlockTraits::child_end(PredBB));
  407. } else {
  408. // This is a discovered block. Find its outermost discovered loop.
  409. while (LoopT *Parent = Subloop->getParentLoop())
  410. Subloop = Parent;
  411. // If it is already discovered to be a subloop of this loop, continue.
  412. if (Subloop == L)
  413. continue;
  414. // Discover a subloop of this loop.
  415. Subloop->setParentLoop(L);
  416. ++NumSubloops;
  417. NumBlocks += Subloop->getBlocksVector().capacity();
  418. PredBB = Subloop->getHeader();
  419. // Continue traversal along predecessors that are not loop-back edges from
  420. // within this subloop tree itself. Note that a predecessor may directly
  421. // reach another subloop that is not yet discovered to be a subloop of
  422. // this loop, which we must traverse.
  423. for (const auto Pred : children<Inverse<BlockT *>>(PredBB)) {
  424. if (LI->getLoopFor(Pred) != Subloop)
  425. ReverseCFGWorklist.push_back(Pred);
  426. }
  427. }
  428. }
  429. L->getSubLoopsVector().reserve(NumSubloops);
  430. L->reserveBlocks(NumBlocks);
  431. }
  432. /// Populate all loop data in a stable order during a single forward DFS.
  433. template <class BlockT, class LoopT> class PopulateLoopsDFS {
  434. typedef GraphTraits<BlockT *> BlockTraits;
  435. typedef typename BlockTraits::ChildIteratorType SuccIterTy;
  436. LoopInfoBase<BlockT, LoopT> *LI;
  437. public:
  438. PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li) : LI(li) {}
  439. void traverse(BlockT *EntryBlock);
  440. protected:
  441. void insertIntoLoop(BlockT *Block);
  442. };
  443. /// Top-level driver for the forward DFS within the loop.
  444. template <class BlockT, class LoopT>
  445. void PopulateLoopsDFS<BlockT, LoopT>::traverse(BlockT *EntryBlock) {
  446. for (BlockT *BB : post_order(EntryBlock))
  447. insertIntoLoop(BB);
  448. }
  449. /// Add a single Block to its ancestor loops in PostOrder. If the block is a
  450. /// subloop header, add the subloop to its parent in PostOrder, then reverse the
  451. /// Block and Subloop vectors of the now complete subloop to achieve RPO.
  452. template <class BlockT, class LoopT>
  453. void PopulateLoopsDFS<BlockT, LoopT>::insertIntoLoop(BlockT *Block) {
  454. LoopT *Subloop = LI->getLoopFor(Block);
  455. if (Subloop && Block == Subloop->getHeader()) {
  456. // We reach this point once per subloop after processing all the blocks in
  457. // the subloop.
  458. if (!Subloop->isOutermost())
  459. Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
  460. else
  461. LI->addTopLevelLoop(Subloop);
  462. // For convenience, Blocks and Subloops are inserted in postorder. Reverse
  463. // the lists, except for the loop header, which is always at the beginning.
  464. Subloop->reverseBlock(1);
  465. std::reverse(Subloop->getSubLoopsVector().begin(),
  466. Subloop->getSubLoopsVector().end());
  467. Subloop = Subloop->getParentLoop();
  468. }
  469. for (; Subloop; Subloop = Subloop->getParentLoop())
  470. Subloop->addBlockEntry(Block);
  471. }
  472. /// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
  473. /// interleaved with backward CFG traversals within each subloop
  474. /// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
  475. /// this part of the algorithm is linear in the number of CFG edges. Subloop and
  476. /// Block vectors are then populated during a single forward CFG traversal
  477. /// (PopulateLoopDFS).
  478. ///
  479. /// During the two CFG traversals each block is seen three times:
  480. /// 1) Discovered and mapped by a reverse CFG traversal.
  481. /// 2) Visited during a forward DFS CFG traversal.
  482. /// 3) Reverse-inserted in the loop in postorder following forward DFS.
  483. ///
  484. /// The Block vectors are inclusive, so step 3 requires loop-depth number of
  485. /// insertions per block.
  486. template <class BlockT, class LoopT>
  487. void LoopInfoBase<BlockT, LoopT>::analyze(const DomTreeBase<BlockT> &DomTree) {
  488. // Postorder traversal of the dominator tree.
  489. const DomTreeNodeBase<BlockT> *DomRoot = DomTree.getRootNode();
  490. for (auto DomNode : post_order(DomRoot)) {
  491. BlockT *Header = DomNode->getBlock();
  492. SmallVector<BlockT *, 4> Backedges;
  493. // Check each predecessor of the potential loop header.
  494. for (const auto Backedge : children<Inverse<BlockT *>>(Header)) {
  495. // If Header dominates predBB, this is a new loop. Collect the backedges.
  496. if (DomTree.dominates(Header, Backedge) &&
  497. DomTree.isReachableFromEntry(Backedge)) {
  498. Backedges.push_back(Backedge);
  499. }
  500. }
  501. // Perform a backward CFG traversal to discover and map blocks in this loop.
  502. if (!Backedges.empty()) {
  503. LoopT *L = AllocateLoop(Header);
  504. discoverAndMapSubloop(L, ArrayRef<BlockT *>(Backedges), this, DomTree);
  505. }
  506. }
  507. // Perform a single forward CFG traversal to populate block and subloop
  508. // vectors for all loops.
  509. PopulateLoopsDFS<BlockT, LoopT> DFS(this);
  510. DFS.traverse(DomRoot->getBlock());
  511. }
  512. template <class BlockT, class LoopT>
  513. SmallVector<LoopT *, 4>
  514. LoopInfoBase<BlockT, LoopT>::getLoopsInPreorder() const {
  515. SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
  516. // The outer-most loop actually goes into the result in the same relative
  517. // order as we walk it. But LoopInfo stores the top level loops in reverse
  518. // program order so for here we reverse it to get forward program order.
  519. // FIXME: If we change the order of LoopInfo we will want to remove the
  520. // reverse here.
  521. for (LoopT *RootL : reverse(*this)) {
  522. auto PreOrderLoopsInRootL = RootL->getLoopsInPreorder();
  523. PreOrderLoops.append(PreOrderLoopsInRootL.begin(),
  524. PreOrderLoopsInRootL.end());
  525. }
  526. return PreOrderLoops;
  527. }
  528. template <class BlockT, class LoopT>
  529. SmallVector<LoopT *, 4>
  530. LoopInfoBase<BlockT, LoopT>::getLoopsInReverseSiblingPreorder() const {
  531. SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
  532. // The outer-most loop actually goes into the result in the same relative
  533. // order as we walk it. LoopInfo stores the top level loops in reverse
  534. // program order so we walk in order here.
  535. // FIXME: If we change the order of LoopInfo we will want to add a reverse
  536. // here.
  537. for (LoopT *RootL : *this) {
  538. assert(PreOrderWorklist.empty() &&
  539. "Must start with an empty preorder walk worklist.");
  540. PreOrderWorklist.push_back(RootL);
  541. do {
  542. LoopT *L = PreOrderWorklist.pop_back_val();
  543. // Sub-loops are stored in forward program order, but will process the
  544. // worklist backwards so we can just append them in order.
  545. PreOrderWorklist.append(L->begin(), L->end());
  546. PreOrderLoops.push_back(L);
  547. } while (!PreOrderWorklist.empty());
  548. }
  549. return PreOrderLoops;
  550. }
  551. // Debugging
  552. template <class BlockT, class LoopT>
  553. void LoopInfoBase<BlockT, LoopT>::print(raw_ostream &OS) const {
  554. for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
  555. TopLevelLoops[i]->print(OS);
  556. #if 0
  557. for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
  558. E = BBMap.end(); I != E; ++I)
  559. OS << "BB '" << I->first->getName() << "' level = "
  560. << I->second->getLoopDepth() << "\n";
  561. #endif
  562. }
  563. template <typename T>
  564. bool compareVectors(std::vector<T> &BB1, std::vector<T> &BB2) {
  565. llvm::sort(BB1);
  566. llvm::sort(BB2);
  567. return BB1 == BB2;
  568. }
  569. template <class BlockT, class LoopT>
  570. void addInnerLoopsToHeadersMap(DenseMap<BlockT *, const LoopT *> &LoopHeaders,
  571. const LoopInfoBase<BlockT, LoopT> &LI,
  572. const LoopT &L) {
  573. LoopHeaders[L.getHeader()] = &L;
  574. for (LoopT *SL : L)
  575. addInnerLoopsToHeadersMap(LoopHeaders, LI, *SL);
  576. }
  577. #ifndef NDEBUG
  578. template <class BlockT, class LoopT>
  579. static void compareLoops(const LoopT *L, const LoopT *OtherL,
  580. DenseMap<BlockT *, const LoopT *> &OtherLoopHeaders) {
  581. BlockT *H = L->getHeader();
  582. BlockT *OtherH = OtherL->getHeader();
  583. assert(H == OtherH &&
  584. "Mismatched headers even though found in the same map entry!");
  585. assert(L->getLoopDepth() == OtherL->getLoopDepth() &&
  586. "Mismatched loop depth!");
  587. const LoopT *ParentL = L, *OtherParentL = OtherL;
  588. do {
  589. assert(ParentL->getHeader() == OtherParentL->getHeader() &&
  590. "Mismatched parent loop headers!");
  591. ParentL = ParentL->getParentLoop();
  592. OtherParentL = OtherParentL->getParentLoop();
  593. } while (ParentL);
  594. for (const LoopT *SubL : *L) {
  595. BlockT *SubH = SubL->getHeader();
  596. const LoopT *OtherSubL = OtherLoopHeaders.lookup(SubH);
  597. assert(OtherSubL && "Inner loop is missing in computed loop info!");
  598. OtherLoopHeaders.erase(SubH);
  599. compareLoops(SubL, OtherSubL, OtherLoopHeaders);
  600. }
  601. std::vector<BlockT *> BBs = L->getBlocks();
  602. std::vector<BlockT *> OtherBBs = OtherL->getBlocks();
  603. assert(compareVectors(BBs, OtherBBs) &&
  604. "Mismatched basic blocks in the loops!");
  605. const SmallPtrSetImpl<const BlockT *> &BlocksSet = L->getBlocksSet();
  606. const SmallPtrSetImpl<const BlockT *> &OtherBlocksSet =
  607. OtherL->getBlocksSet();
  608. assert(BlocksSet.size() == OtherBlocksSet.size() &&
  609. llvm::set_is_subset(BlocksSet, OtherBlocksSet) &&
  610. "Mismatched basic blocks in BlocksSets!");
  611. }
  612. #endif
  613. template <class BlockT, class LoopT>
  614. void LoopInfoBase<BlockT, LoopT>::verify(
  615. const DomTreeBase<BlockT> &DomTree) const {
  616. DenseSet<const LoopT *> Loops;
  617. for (iterator I = begin(), E = end(); I != E; ++I) {
  618. assert((*I)->isOutermost() && "Top-level loop has a parent!");
  619. (*I)->verifyLoopNest(&Loops);
  620. }
  621. // Verify that blocks are mapped to valid loops.
  622. #ifndef NDEBUG
  623. for (auto &Entry : BBMap) {
  624. const BlockT *BB = Entry.first;
  625. LoopT *L = Entry.second;
  626. assert(Loops.count(L) && "orphaned loop");
  627. assert(L->contains(BB) && "orphaned block");
  628. for (LoopT *ChildLoop : *L)
  629. assert(!ChildLoop->contains(BB) &&
  630. "BBMap should point to the innermost loop containing BB");
  631. }
  632. // Recompute LoopInfo to verify loops structure.
  633. LoopInfoBase<BlockT, LoopT> OtherLI;
  634. OtherLI.analyze(DomTree);
  635. // Build a map we can use to move from our LI to the computed one. This
  636. // allows us to ignore the particular order in any layer of the loop forest
  637. // while still comparing the structure.
  638. DenseMap<BlockT *, const LoopT *> OtherLoopHeaders;
  639. for (LoopT *L : OtherLI)
  640. addInnerLoopsToHeadersMap(OtherLoopHeaders, OtherLI, *L);
  641. // Walk the top level loops and ensure there is a corresponding top-level
  642. // loop in the computed version and then recursively compare those loop
  643. // nests.
  644. for (LoopT *L : *this) {
  645. BlockT *Header = L->getHeader();
  646. const LoopT *OtherL = OtherLoopHeaders.lookup(Header);
  647. assert(OtherL && "Top level loop is missing in computed loop info!");
  648. // Now that we've matched this loop, erase its header from the map.
  649. OtherLoopHeaders.erase(Header);
  650. // And recursively compare these loops.
  651. compareLoops(L, OtherL, OtherLoopHeaders);
  652. }
  653. // Any remaining entries in the map are loops which were found when computing
  654. // a fresh LoopInfo but not present in the current one.
  655. if (!OtherLoopHeaders.empty()) {
  656. for (const auto &HeaderAndLoop : OtherLoopHeaders)
  657. dbgs() << "Found new loop: " << *HeaderAndLoop.second << "\n";
  658. llvm_unreachable("Found new loops when recomputing LoopInfo!");
  659. }
  660. #endif
  661. }
  662. } // End llvm namespace
  663. #endif
  664. #ifdef __GNUC__
  665. #pragma GCC diagnostic pop
  666. #endif