LoopInfo.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the LoopInfo class that is used to identify natural loops
  11. // and determine the loop depth of various nodes of the CFG. A natural loop
  12. // has exactly one entry-point, which is called the header. Note that natural
  13. // loops may actually be several loops that share the same header node.
  14. //
  15. // This analysis calculates the nesting structure of loops in a function. For
  16. // each natural loop identified, this analysis identifies natural loops
  17. // contained entirely within the loop and the basic blocks the make up the loop.
  18. //
  19. // It can calculate on the fly various bits of information, for example:
  20. //
  21. // * whether there is a preheader for the loop
  22. // * the number of back edges to the header
  23. // * whether or not a particular block branches out of the loop
  24. // * the successor blocks of the loop
  25. // * the loop depth
  26. // * etc...
  27. //
  28. //===----------------------------------------------------------------------===//
  29. #ifndef LLVM_ANALYSIS_LOOPINFO_H
  30. #define LLVM_ANALYSIS_LOOPINFO_H
  31. #include "llvm/ADT/DenseMap.h"
  32. #include "llvm/ADT/DenseSet.h"
  33. #include "llvm/ADT/GraphTraits.h"
  34. #include "llvm/ADT/SmallPtrSet.h"
  35. #include "llvm/ADT/SmallVector.h"
  36. #include "llvm/IR/CFG.h"
  37. #include "llvm/IR/Instruction.h"
  38. #include "llvm/Pass.h"
  39. #include <algorithm>
  40. namespace llvm {
  41. // FIXME: Replace this brittle forward declaration with the include of the new
  42. // PassManager.h when doing so doesn't break the PassManagerBuilder.
  43. template <typename IRUnitT> class AnalysisManager;
  44. class PreservedAnalyses;
  45. class DominatorTree;
  46. class LoopInfo;
  47. class Loop;
  48. class MDNode;
  49. class PHINode;
  50. class raw_ostream;
  51. template<class N> class DominatorTreeBase;
  52. template<class N, class M> class LoopInfoBase;
  53. template<class N, class M> class LoopBase;
  54. //===----------------------------------------------------------------------===//
  55. /// LoopBase class - Instances of this class are used to represent loops that
  56. /// are detected in the flow graph
  57. ///
  58. template<class BlockT, class LoopT>
  59. class LoopBase {
  60. LoopT *ParentLoop;
  61. // SubLoops - Loops contained entirely within this one.
  62. std::vector<LoopT *> SubLoops;
  63. // Blocks - The list of blocks in this loop. First entry is the header node.
  64. std::vector<BlockT*> Blocks;
  65. SmallPtrSet<const BlockT*, 8> DenseBlockSet;
  66. LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
  67. const LoopBase<BlockT, LoopT>&
  68. operator=(const LoopBase<BlockT, LoopT> &) = delete;
  69. public:
  70. /// Loop ctor - This creates an empty loop.
  71. LoopBase() : ParentLoop(nullptr) {}
  72. ~LoopBase() {
  73. for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
  74. delete SubLoops[i];
  75. }
  76. /// getLoopDepth - Return the nesting level of this loop. An outer-most
  77. /// loop has depth 1, for consistency with loop depth values used for basic
  78. /// blocks, where depth 0 is used for blocks not inside any loops.
  79. unsigned getLoopDepth() const {
  80. unsigned D = 1;
  81. for (const LoopT *CurLoop = ParentLoop; CurLoop;
  82. CurLoop = CurLoop->ParentLoop)
  83. ++D;
  84. return D;
  85. }
  86. BlockT *getHeader() const { return Blocks.front(); }
  87. LoopT *getParentLoop() const { return ParentLoop; }
  88. /// setParentLoop is a raw interface for bypassing addChildLoop.
  89. void setParentLoop(LoopT *L) { ParentLoop = L; }
  90. /// contains - Return true if the specified loop is contained within in
  91. /// this loop.
  92. ///
  93. bool contains(const LoopT *L) const {
  94. if (L == this) return true;
  95. if (!L) return false;
  96. #pragma warning(push)
  97. #pragma warning(suppress: 6011) // HLSL Change - suppress incorrect warning about null dereference
  98. return contains(L->getParentLoop());
  99. #pragma warning(pop)
  100. }
  101. /// contains - Return true if the specified basic block is in this loop.
  102. ///
  103. bool contains(const BlockT *BB) const {
  104. return DenseBlockSet.count(BB);
  105. }
  106. /// contains - Return true if the specified instruction is in this loop.
  107. ///
  108. template<class InstT>
  109. bool contains(const InstT *Inst) const {
  110. return contains(Inst->getParent());
  111. }
  112. /// iterator/begin/end - Return the loops contained entirely within this loop.
  113. ///
  114. const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
  115. std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
  116. typedef typename std::vector<LoopT *>::const_iterator iterator;
  117. typedef typename std::vector<LoopT *>::const_reverse_iterator
  118. reverse_iterator;
  119. iterator begin() const { return SubLoops.begin(); }
  120. iterator end() const { return SubLoops.end(); }
  121. reverse_iterator rbegin() const { return SubLoops.rbegin(); }
  122. reverse_iterator rend() const { return SubLoops.rend(); }
  123. bool empty() const { return SubLoops.empty(); }
  124. /// getBlocks - Get a list of the basic blocks which make up this loop.
  125. ///
  126. const std::vector<BlockT*> &getBlocks() const { return Blocks; }
  127. typedef typename std::vector<BlockT*>::const_iterator block_iterator;
  128. block_iterator block_begin() const { return Blocks.begin(); }
  129. block_iterator block_end() const { return Blocks.end(); }
  130. /// getNumBlocks - Get the number of blocks in this loop in constant time.
  131. unsigned getNumBlocks() const {
  132. return Blocks.size();
  133. }
  134. /// isLoopExiting - True if terminator in the block can branch to another
  135. /// block that is outside of the current loop.
  136. ///
  137. bool isLoopExiting(const BlockT *BB) const {
  138. typedef GraphTraits<const BlockT*> BlockTraits;
  139. for (typename BlockTraits::ChildIteratorType SI =
  140. BlockTraits::child_begin(BB),
  141. SE = BlockTraits::child_end(BB); SI != SE; ++SI) {
  142. if (!contains(*SI))
  143. return true;
  144. }
  145. return false;
  146. }
  147. /// getNumBackEdges - Calculate the number of back edges to the loop header
  148. ///
  149. unsigned getNumBackEdges() const {
  150. unsigned NumBackEdges = 0;
  151. BlockT *H = getHeader();
  152. typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
  153. for (typename InvBlockTraits::ChildIteratorType I =
  154. InvBlockTraits::child_begin(H),
  155. E = InvBlockTraits::child_end(H); I != E; ++I)
  156. if (contains(*I))
  157. ++NumBackEdges;
  158. return NumBackEdges;
  159. }
  160. //===--------------------------------------------------------------------===//
  161. // APIs for simple analysis of the loop.
  162. //
  163. // Note that all of these methods can fail on general loops (ie, there may not
  164. // be a preheader, etc). For best success, the loop simplification and
  165. // induction variable canonicalization pass should be used to normalize loops
  166. // for easy analysis. These methods assume canonical loops.
  167. /// getExitingBlocks - Return all blocks inside the loop that have successors
  168. /// outside of the loop. These are the blocks _inside of the current loop_
  169. /// which branch out. The returned list is always unique.
  170. ///
  171. void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
  172. /// getExitingBlock - If getExitingBlocks would return exactly one block,
  173. /// return that block. Otherwise return null.
  174. BlockT *getExitingBlock() const;
  175. /// getExitBlocks - Return all of the successor blocks of this loop. These
  176. /// are the blocks _outside of the current loop_ which are branched to.
  177. ///
  178. void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
  179. /// getExitBlock - If getExitBlocks would return exactly one block,
  180. /// return that block. Otherwise return null.
  181. BlockT *getExitBlock() const;
  182. /// Edge type.
  183. typedef std::pair<const BlockT*, const BlockT*> Edge;
  184. /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
  185. void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
  186. /// getLoopPreheader - If there is a preheader for this loop, return it. A
  187. /// loop has a preheader if there is only one edge to the header of the loop
  188. /// from outside of the loop. If this is the case, the block branching to the
  189. /// header of the loop is the preheader node.
  190. ///
  191. /// This method returns null if there is no preheader for the loop.
  192. ///
  193. BlockT *getLoopPreheader() const;
  194. /// getLoopPredecessor - If the given loop's header has exactly one unique
  195. /// predecessor outside the loop, return it. Otherwise return null.
  196. /// This is less strict that the loop "preheader" concept, which requires
  197. /// the predecessor to have exactly one successor.
  198. ///
  199. BlockT *getLoopPredecessor() const;
  200. /// getLoopLatch - If there is a single latch block for this loop, return it.
  201. /// A latch block is a block that contains a branch back to the header.
  202. BlockT *getLoopLatch() const;
  203. /// getLoopLatches - Return all loop latch blocks of this loop. A latch block
  204. /// is a block that contains a branch back to the header.
  205. void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
  206. BlockT *H = getHeader();
  207. typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
  208. for (typename InvBlockTraits::ChildIteratorType I =
  209. InvBlockTraits::child_begin(H),
  210. E = InvBlockTraits::child_end(H); I != E; ++I)
  211. if (contains(*I))
  212. LoopLatches.push_back(*I);
  213. }
  214. //===--------------------------------------------------------------------===//
  215. // APIs for updating loop information after changing the CFG
  216. //
  217. /// addBasicBlockToLoop - This method is used by other analyses to update loop
  218. /// information. NewBB is set to be a new member of the current loop.
  219. /// Because of this, it is added as a member of all parent loops, and is added
  220. /// to the specified LoopInfo object as being in the current basic block. It
  221. /// is not valid to replace the loop header with this method.
  222. ///
  223. void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
  224. /// replaceChildLoopWith - This is used when splitting loops up. It replaces
  225. /// the OldChild entry in our children list with NewChild, and updates the
  226. /// parent pointer of OldChild to be null and the NewChild to be this loop.
  227. /// This updates the loop depth of the new child.
  228. void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
  229. /// addChildLoop - Add the specified loop to be a child of this loop. This
  230. /// updates the loop depth of the new child.
  231. ///
  232. void addChildLoop(LoopT *NewChild) {
  233. assert(!NewChild->ParentLoop && "NewChild already has a parent!");
  234. NewChild->ParentLoop = static_cast<LoopT *>(this);
  235. SubLoops.push_back(NewChild);
  236. }
  237. /// removeChildLoop - This removes the specified child from being a subloop of
  238. /// this loop. The loop is not deleted, as it will presumably be inserted
  239. /// into another loop.
  240. LoopT *removeChildLoop(iterator I) {
  241. assert(I != SubLoops.end() && "Cannot remove end iterator!");
  242. LoopT *Child = *I;
  243. assert(Child->ParentLoop == this && "Child is not a child of this loop!");
  244. SubLoops.erase(SubLoops.begin()+(I-begin()));
  245. Child->ParentLoop = nullptr;
  246. return Child;
  247. }
  248. /// addBlockEntry - This adds a basic block directly to the basic block list.
  249. /// This should only be used by transformations that create new loops. Other
  250. /// transformations should use addBasicBlockToLoop.
  251. void addBlockEntry(BlockT *BB) {
  252. Blocks.push_back(BB);
  253. DenseBlockSet.insert(BB);
  254. }
  255. /// reverseBlocks - interface to reverse Blocks[from, end of loop] in this loop
  256. void reverseBlock(unsigned from) {
  257. std::reverse(Blocks.begin() + from, Blocks.end());
  258. }
  259. /// reserveBlocks- interface to do reserve() for Blocks
  260. void reserveBlocks(unsigned size) {
  261. Blocks.reserve(size);
  262. }
  263. /// moveToHeader - This method is used to move BB (which must be part of this
  264. /// loop) to be the loop header of the loop (the block that dominates all
  265. /// others).
  266. void moveToHeader(BlockT *BB) {
  267. if (Blocks[0] == BB) return;
  268. for (unsigned i = 0; ; ++i) {
  269. assert(i != Blocks.size() && "Loop does not contain BB!");
  270. if (Blocks[i] == BB) {
  271. Blocks[i] = Blocks[0];
  272. Blocks[0] = BB;
  273. return;
  274. }
  275. }
  276. }
  277. /// removeBlockFromLoop - This removes the specified basic block from the
  278. /// current loop, updating the Blocks as appropriate. This does not update
  279. /// the mapping in the LoopInfo class.
  280. void removeBlockFromLoop(BlockT *BB) {
  281. auto I = std::find(Blocks.begin(), Blocks.end(), BB);
  282. assert(I != Blocks.end() && "N is not in this list!");
  283. Blocks.erase(I);
  284. DenseBlockSet.erase(BB);
  285. }
  286. /// verifyLoop - Verify loop structure
  287. void verifyLoop() const;
  288. /// verifyLoop - Verify loop structure of this loop and all nested loops.
  289. void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
  290. void print(raw_ostream &OS, unsigned Depth = 0) const;
  291. protected:
  292. friend class LoopInfoBase<BlockT, LoopT>;
  293. explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
  294. Blocks.push_back(BB);
  295. DenseBlockSet.insert(BB);
  296. }
  297. };
  298. template<class BlockT, class LoopT>
  299. raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
  300. Loop.print(OS);
  301. return OS;
  302. }
  303. // Implementation in LoopInfoImpl.h
  304. extern template class LoopBase<BasicBlock, Loop>;
  305. class Loop : public LoopBase<BasicBlock, Loop> {
  306. public:
  307. Loop() {}
  308. /// isLoopInvariant - Return true if the specified value is loop invariant
  309. ///
  310. bool isLoopInvariant(const Value *V) const;
  311. /// hasLoopInvariantOperands - Return true if all the operands of the
  312. /// specified instruction are loop invariant.
  313. bool hasLoopInvariantOperands(const Instruction *I) const;
  314. /// makeLoopInvariant - If the given value is an instruction inside of the
  315. /// loop and it can be hoisted, do so to make it trivially loop-invariant.
  316. /// Return true if the value after any hoisting is loop invariant. This
  317. /// function can be used as a slightly more aggressive replacement for
  318. /// isLoopInvariant.
  319. ///
  320. /// If InsertPt is specified, it is the point to hoist instructions to.
  321. /// If null, the terminator of the loop preheader is used.
  322. ///
  323. bool makeLoopInvariant(Value *V, bool &Changed,
  324. Instruction *InsertPt = nullptr) const;
  325. /// makeLoopInvariant - If the given instruction is inside of the
  326. /// loop and it can be hoisted, do so to make it trivially loop-invariant.
  327. /// Return true if the instruction after any hoisting is loop invariant. This
  328. /// function can be used as a slightly more aggressive replacement for
  329. /// isLoopInvariant.
  330. ///
  331. /// If InsertPt is specified, it is the point to hoist instructions to.
  332. /// If null, the terminator of the loop preheader is used.
  333. ///
  334. bool makeLoopInvariant(Instruction *I, bool &Changed,
  335. Instruction *InsertPt = nullptr) const;
  336. /// getCanonicalInductionVariable - Check to see if the loop has a canonical
  337. /// induction variable: an integer recurrence that starts at 0 and increments
  338. /// by one each time through the loop. If so, return the phi node that
  339. /// corresponds to it.
  340. ///
  341. /// The IndVarSimplify pass transforms loops to have a canonical induction
  342. /// variable.
  343. ///
  344. PHINode *getCanonicalInductionVariable() const;
  345. /// isLCSSAForm - Return true if the Loop is in LCSSA form
  346. bool isLCSSAForm(DominatorTree &DT) const;
  347. /// isLoopSimplifyForm - Return true if the Loop is in the form that
  348. /// the LoopSimplify form transforms loops to, which is sometimes called
  349. /// normal form.
  350. bool isLoopSimplifyForm() const;
  351. /// isSafeToClone - Return true if the loop body is safe to clone in practice.
  352. bool isSafeToClone() const;
  353. /// Returns true if the loop is annotated parallel.
  354. ///
  355. /// A parallel loop can be assumed to not contain any dependencies between
  356. /// iterations by the compiler. That is, any loop-carried dependency checking
  357. /// can be skipped completely when parallelizing the loop on the target
  358. /// machine. Thus, if the parallel loop information originates from the
  359. /// programmer, e.g. via the OpenMP parallel for pragma, it is the
  360. /// programmer's responsibility to ensure there are no loop-carried
  361. /// dependencies. The final execution order of the instructions across
  362. /// iterations is not guaranteed, thus, the end result might or might not
  363. /// implement actual concurrent execution of instructions across multiple
  364. /// iterations.
  365. bool isAnnotatedParallel() const;
  366. /// Return the llvm.loop loop id metadata node for this loop if it is present.
  367. ///
  368. /// If this loop contains the same llvm.loop metadata on each branch to the
  369. /// header then the node is returned. If any latch instruction does not
  370. /// contain llvm.loop or or if multiple latches contain different nodes then
  371. /// 0 is returned.
  372. MDNode *getLoopID() const;
  373. /// Set the llvm.loop loop id metadata for this loop.
  374. ///
  375. /// The LoopID metadata node will be added to each terminator instruction in
  376. /// the loop that branches to the loop header.
  377. ///
  378. /// The LoopID metadata node should have one or more operands and the first
  379. /// operand should should be the node itself.
  380. void setLoopID(MDNode *LoopID) const;
  381. /// hasDedicatedExits - Return true if no exit block for the loop
  382. /// has a predecessor that is outside the loop.
  383. bool hasDedicatedExits() const;
  384. /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
  385. /// These are the blocks _outside of the current loop_ which are branched to.
  386. /// This assumes that loop exits are in canonical form.
  387. ///
  388. void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
  389. /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
  390. /// block, return that block. Otherwise return null.
  391. BasicBlock *getUniqueExitBlock() const;
  392. void dump() const;
  393. /// \brief Return the debug location of the start of this loop.
  394. /// This looks for a BB terminating instruction with a known debug
  395. /// location by looking at the preheader and header blocks. If it
  396. /// cannot find a terminating instruction with location information,
  397. /// it returns an unknown location.
  398. DebugLoc getStartLoc() const {
  399. BasicBlock *HeadBB;
  400. // Try the pre-header first.
  401. if ((HeadBB = getLoopPreheader()) != nullptr)
  402. if (DebugLoc DL = HeadBB->getTerminator()->getDebugLoc())
  403. return DL;
  404. // If we have no pre-header or there are no instructions with debug
  405. // info in it, try the header.
  406. HeadBB = getHeader();
  407. if (HeadBB)
  408. return HeadBB->getTerminator()->getDebugLoc();
  409. return DebugLoc();
  410. }
  411. private:
  412. friend class LoopInfoBase<BasicBlock, Loop>;
  413. explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
  414. };
  415. // //
  416. ///////////////////////////////////////////////////////////////////////////////
  417. /// LoopInfo - This class builds and contains all of the top level loop
  418. /// structures in the specified function.
  419. ///
  420. template<class BlockT, class LoopT>
  421. class LoopInfoBase {
  422. // BBMap - Mapping of basic blocks to the inner most loop they occur in
  423. DenseMap<const BlockT *, LoopT *> BBMap;
  424. std::vector<LoopT *> TopLevelLoops;
  425. friend class LoopBase<BlockT, LoopT>;
  426. friend class LoopInfo;
  427. void operator=(const LoopInfoBase &) = delete;
  428. LoopInfoBase(const LoopInfoBase &) = delete;
  429. public:
  430. LoopInfoBase() { }
  431. ~LoopInfoBase() { releaseMemory(); }
  432. LoopInfoBase(LoopInfoBase &&Arg)
  433. : BBMap(std::move(Arg.BBMap)),
  434. TopLevelLoops(std::move(Arg.TopLevelLoops)) {
  435. // We have to clear the arguments top level loops as we've taken ownership.
  436. Arg.TopLevelLoops.clear();
  437. }
  438. LoopInfoBase &operator=(LoopInfoBase &&RHS) {
  439. BBMap = std::move(RHS.BBMap);
  440. for (auto *L : TopLevelLoops)
  441. delete L;
  442. TopLevelLoops = std::move(RHS.TopLevelLoops);
  443. RHS.TopLevelLoops.clear();
  444. return *this;
  445. }
  446. void releaseMemory() {
  447. BBMap.clear();
  448. for (auto *L : TopLevelLoops)
  449. delete L;
  450. TopLevelLoops.clear();
  451. }
  452. /// iterator/begin/end - The interface to the top-level loops in the current
  453. /// function.
  454. ///
  455. typedef typename std::vector<LoopT *>::const_iterator iterator;
  456. typedef typename std::vector<LoopT *>::const_reverse_iterator
  457. reverse_iterator;
  458. iterator begin() const { return TopLevelLoops.begin(); }
  459. iterator end() const { return TopLevelLoops.end(); }
  460. reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
  461. reverse_iterator rend() const { return TopLevelLoops.rend(); }
  462. bool empty() const { return TopLevelLoops.empty(); }
  463. /// getLoopFor - Return the inner most loop that BB lives in. If a basic
  464. /// block is in no loop (for example the entry node), null is returned.
  465. ///
  466. LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
  467. /// operator[] - same as getLoopFor...
  468. ///
  469. const LoopT *operator[](const BlockT *BB) const {
  470. return getLoopFor(BB);
  471. }
  472. /// getLoopDepth - Return the loop nesting level of the specified block. A
  473. /// depth of 0 means the block is not inside any loop.
  474. ///
  475. unsigned getLoopDepth(const BlockT *BB) const {
  476. const LoopT *L = getLoopFor(BB);
  477. return L ? L->getLoopDepth() : 0;
  478. }
  479. // isLoopHeader - True if the block is a loop header node
  480. bool isLoopHeader(const BlockT *BB) const {
  481. const LoopT *L = getLoopFor(BB);
  482. return L && L->getHeader() == BB;
  483. }
  484. /// removeLoop - This removes the specified top-level loop from this loop info
  485. /// object. The loop is not deleted, as it will presumably be inserted into
  486. /// another loop.
  487. LoopT *removeLoop(iterator I) {
  488. assert(I != end() && "Cannot remove end iterator!");
  489. LoopT *L = *I;
  490. assert(!L->getParentLoop() && "Not a top-level loop!");
  491. TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
  492. return L;
  493. }
  494. /// changeLoopFor - Change the top-level loop that contains BB to the
  495. /// specified loop. This should be used by transformations that restructure
  496. /// the loop hierarchy tree.
  497. void changeLoopFor(BlockT *BB, LoopT *L) {
  498. if (!L) {
  499. BBMap.erase(BB);
  500. return;
  501. }
  502. BBMap[BB] = L;
  503. }
  504. /// changeTopLevelLoop - Replace the specified loop in the top-level loops
  505. /// list with the indicated loop.
  506. void changeTopLevelLoop(LoopT *OldLoop,
  507. LoopT *NewLoop) {
  508. auto I = std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
  509. assert(I != TopLevelLoops.end() && "Old loop not at top level!");
  510. *I = NewLoop;
  511. assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
  512. "Loops already embedded into a subloop!");
  513. }
  514. /// addTopLevelLoop - This adds the specified loop to the collection of
  515. /// top-level loops.
  516. void addTopLevelLoop(LoopT *New) {
  517. assert(!New->getParentLoop() && "Loop already in subloop!");
  518. TopLevelLoops.push_back(New);
  519. }
  520. /// removeBlock - This method completely removes BB from all data structures,
  521. /// including all of the Loop objects it is nested in and our mapping from
  522. /// BasicBlocks to loops.
  523. void removeBlock(BlockT *BB) {
  524. auto I = BBMap.find(BB);
  525. if (I != BBMap.end()) {
  526. for (LoopT *L = I->second; L; L = L->getParentLoop())
  527. L->removeBlockFromLoop(BB);
  528. BBMap.erase(I);
  529. }
  530. }
  531. // Internals
  532. static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
  533. const LoopT *ParentLoop) {
  534. if (!SubLoop) return true;
  535. if (SubLoop == ParentLoop) return false;
  536. return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
  537. }
  538. /// Create the loop forest using a stable algorithm.
  539. void Analyze(DominatorTreeBase<BlockT> &DomTree);
  540. // Debugging
  541. void print(raw_ostream &OS) const;
  542. void verify() const;
  543. };
  544. // Implementation in LoopInfoImpl.h
  545. extern template class LoopInfoBase<BasicBlock, Loop>;
  546. class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
  547. typedef LoopInfoBase<BasicBlock, Loop> BaseT;
  548. friend class LoopBase<BasicBlock, Loop>;
  549. void operator=(const LoopInfo &) = delete;
  550. LoopInfo(const LoopInfo &) = delete;
  551. public:
  552. LoopInfo() {}
  553. LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
  554. LoopInfo &operator=(LoopInfo &&RHS) {
  555. BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
  556. return *this;
  557. }
  558. // Most of the public interface is provided via LoopInfoBase.
  559. /// updateUnloop - Update LoopInfo after removing the last backedge from a
  560. /// loop--now the "unloop". This updates the loop forest and parent loops for
  561. /// each block so that Unloop is no longer referenced, but the caller must
  562. /// actually delete the Unloop object.
  563. void updateUnloop(Loop *Unloop);
  564. /// replacementPreservesLCSSAForm - Returns true if replacing From with To
  565. /// everywhere is guaranteed to preserve LCSSA form.
  566. bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
  567. // Preserving LCSSA form is only problematic if the replacing value is an
  568. // instruction.
  569. Instruction *I = dyn_cast<Instruction>(To);
  570. if (!I) return true;
  571. // If both instructions are defined in the same basic block then replacement
  572. // cannot break LCSSA form.
  573. if (I->getParent() == From->getParent())
  574. return true;
  575. // If the instruction is not defined in a loop then it can safely replace
  576. // anything.
  577. Loop *ToLoop = getLoopFor(I->getParent());
  578. if (!ToLoop) return true;
  579. // If the replacing instruction is defined in the same loop as the original
  580. // instruction, or in a loop that contains it as an inner loop, then using
  581. // it as a replacement will not break LCSSA form.
  582. return ToLoop->contains(getLoopFor(From->getParent()));
  583. }
  584. };
  585. // Allow clients to walk the list of nested loops...
  586. template <> struct GraphTraits<const Loop*> {
  587. typedef const Loop NodeType;
  588. typedef LoopInfo::iterator ChildIteratorType;
  589. static NodeType *getEntryNode(const Loop *L) { return L; }
  590. static inline ChildIteratorType child_begin(NodeType *N) {
  591. return N->begin();
  592. }
  593. static inline ChildIteratorType child_end(NodeType *N) {
  594. return N->end();
  595. }
  596. };
  597. template <> struct GraphTraits<Loop*> {
  598. typedef Loop NodeType;
  599. typedef LoopInfo::iterator ChildIteratorType;
  600. static NodeType *getEntryNode(Loop *L) { return L; }
  601. static inline ChildIteratorType child_begin(NodeType *N) {
  602. return N->begin();
  603. }
  604. static inline ChildIteratorType child_end(NodeType *N) {
  605. return N->end();
  606. }
  607. };
  608. /// \brief Analysis pass that exposes the \c LoopInfo for a function.
  609. class LoopAnalysis {
  610. static char PassID;
  611. public:
  612. typedef LoopInfo Result;
  613. /// \brief Opaque, unique identifier for this analysis pass.
  614. static void *ID() { return (void *)&PassID; }
  615. /// \brief Provide a name for the analysis for debugging and logging.
  616. static StringRef name() { return "LoopAnalysis"; }
  617. LoopInfo run(Function &F, AnalysisManager<Function> *AM);
  618. };
  619. /// \brief Printer pass for the \c LoopAnalysis results.
  620. class LoopPrinterPass {
  621. raw_ostream &OS;
  622. public:
  623. explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
  624. PreservedAnalyses run(Function &F, AnalysisManager<Function> *AM);
  625. static StringRef name() { return "LoopPrinterPass"; }
  626. };
  627. /// \brief The legacy pass manager's analysis pass to compute loop information.
  628. class LoopInfoWrapperPass : public FunctionPass {
  629. LoopInfo LI;
  630. public:
  631. static char ID; // Pass identification, replacement for typeid
  632. LoopInfoWrapperPass() : FunctionPass(ID) {
  633. initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
  634. }
  635. LoopInfo &getLoopInfo() { return LI; }
  636. const LoopInfo &getLoopInfo() const { return LI; }
  637. /// \brief Calculate the natural loop information for a given function.
  638. bool runOnFunction(Function &F) override;
  639. void verifyAnalysis() const override;
  640. void releaseMemory() override { LI.releaseMemory(); }
  641. void print(raw_ostream &O, const Module *M = nullptr) const override;
  642. void getAnalysisUsage(AnalysisUsage &AU) const override;
  643. };
  644. } // End llvm namespace
  645. #endif