LoopInfoImpl.h 28 KB

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