1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
19 // It can calculate on the fly various bits of information, for example:
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
28 // Note that this analysis specifically identifies *Loops* not cycles or SCCs
29 // in the CFG. There can be strongly connected components in the CFG which
30 // this analysis will not recognize and that will not be represented by a Loop
31 // instance. In particular, a Loop might be inside such a non-loop SCC, or a
32 // non-loop SCC might contain a sub-SCC which is a Loop.
34 //===----------------------------------------------------------------------===//
36 #ifndef LLVM_ANALYSIS_LOOPINFO_H
37 #define LLVM_ANALYSIS_LOOPINFO_H
39 #include "llvm/ADT/DenseMap.h"
40 #include "llvm/ADT/DenseSet.h"
41 #include "llvm/ADT/GraphTraits.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/IR/CFG.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/PassManager.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/Allocator.h"
61 template <class N, bool IsPostDom> class DominatorTreeBase;
62 template <class N, class M> class LoopInfoBase;
63 template <class N, class M> class LoopBase;
65 //===----------------------------------------------------------------------===//
66 /// Instances of this class are used to represent loops that are detected in the
69 template <class BlockT, class LoopT> class LoopBase {
71 // Loops contained entirely within this one.
72 std::vector<LoopT *> SubLoops;
74 // The list of blocks in this loop. First entry is the header node.
75 std::vector<BlockT *> Blocks;
77 SmallPtrSet<const BlockT *, 8> DenseBlockSet;
79 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
80 /// Indicator that this loop is no longer a valid loop.
81 bool IsInvalid = false;
84 LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
85 const LoopBase<BlockT, LoopT> &
86 operator=(const LoopBase<BlockT, LoopT> &) = delete;
89 /// Return the nesting level of this loop. An outer-most loop has depth 1,
90 /// for consistency with loop depth values used for basic blocks, where depth
91 /// 0 is used for blocks not inside any loops.
92 unsigned getLoopDepth() const {
93 assert(!isInvalid() && "Loop not in a valid state!");
95 for (const LoopT *CurLoop = ParentLoop; CurLoop;
96 CurLoop = CurLoop->ParentLoop)
100 BlockT *getHeader() const { return getBlocks().front(); }
101 LoopT *getParentLoop() const { return ParentLoop; }
103 /// This is a raw interface for bypassing addChildLoop.
104 void setParentLoop(LoopT *L) {
105 assert(!isInvalid() && "Loop not in a valid state!");
109 /// Return true if the specified loop is contained within in this loop.
110 bool contains(const LoopT *L) const {
111 assert(!isInvalid() && "Loop not in a valid state!");
116 return contains(L->getParentLoop());
119 /// Return true if the specified basic block is in this loop.
120 bool contains(const BlockT *BB) const {
121 assert(!isInvalid() && "Loop not in a valid state!");
122 return DenseBlockSet.count(BB);
125 /// Return true if the specified instruction is in this loop.
126 template <class InstT> bool contains(const InstT *Inst) const {
127 return contains(Inst->getParent());
130 /// Return the loops contained entirely within this loop.
131 const std::vector<LoopT *> &getSubLoops() const {
132 assert(!isInvalid() && "Loop not in a valid state!");
135 std::vector<LoopT *> &getSubLoopsVector() {
136 assert(!isInvalid() && "Loop not in a valid state!");
139 typedef typename std::vector<LoopT *>::const_iterator iterator;
141 typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
142 iterator begin() const { return getSubLoops().begin(); }
143 iterator end() const { return getSubLoops().end(); }
144 reverse_iterator rbegin() const { return getSubLoops().rbegin(); }
145 reverse_iterator rend() const { return getSubLoops().rend(); }
146 bool empty() const { return getSubLoops().empty(); }
148 /// Get a list of the basic blocks which make up this loop.
149 ArrayRef<BlockT *> getBlocks() const {
150 assert(!isInvalid() && "Loop not in a valid state!");
153 typedef typename ArrayRef<BlockT *>::const_iterator block_iterator;
154 block_iterator block_begin() const { return getBlocks().begin(); }
155 block_iterator block_end() const { return getBlocks().end(); }
156 inline iterator_range<block_iterator> blocks() const {
157 assert(!isInvalid() && "Loop not in a valid state!");
158 return make_range(block_begin(), block_end());
161 /// Get the number of blocks in this loop in constant time.
162 /// Invalidate the loop, indicating that it is no longer a loop.
163 unsigned getNumBlocks() const {
164 assert(!isInvalid() && "Loop not in a valid state!");
165 return Blocks.size();
168 /// Return a direct, mutable handle to the blocks vector so that we can
169 /// mutate it efficiently with techniques like `std::remove`.
170 std::vector<BlockT *> &getBlocksVector() {
171 assert(!isInvalid() && "Loop not in a valid state!");
174 /// Return a direct, mutable handle to the blocks set so that we can
175 /// mutate it efficiently.
176 SmallPtrSetImpl<const BlockT *> &getBlocksSet() {
177 assert(!isInvalid() && "Loop not in a valid state!");
178 return DenseBlockSet;
181 /// Return true if this loop is no longer valid. The only valid use of this
182 /// helper is "assert(L.isInvalid())" or equivalent, since IsInvalid is set to
183 /// true by the destructor. In other words, if this accessor returns true,
184 /// the caller has already triggered UB by calling this accessor; and so it
185 /// can only be called in a context where a return value of true indicates a
186 /// programmer error.
187 bool isInvalid() const {
188 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
195 /// True if terminator in the block can branch to another block that is
196 /// outside of the current loop.
197 bool isLoopExiting(const BlockT *BB) const {
198 assert(!isInvalid() && "Loop not in a valid state!");
199 for (const auto &Succ : children<const BlockT *>(BB)) {
206 /// Returns true if \p BB is a loop-latch.
207 /// A latch block is a block that contains a branch back to the header.
208 /// This function is useful when there are multiple latches in a loop
209 /// because \fn getLoopLatch will return nullptr in that case.
210 bool isLoopLatch(const BlockT *BB) const {
211 assert(!isInvalid() && "Loop not in a valid state!");
212 assert(contains(BB) && "block does not belong to the loop");
214 BlockT *Header = getHeader();
215 auto PredBegin = GraphTraits<Inverse<BlockT *>>::child_begin(Header);
216 auto PredEnd = GraphTraits<Inverse<BlockT *>>::child_end(Header);
217 return std::find(PredBegin, PredEnd, BB) != PredEnd;
220 /// Calculate the number of back edges to the loop header.
221 unsigned getNumBackEdges() const {
222 assert(!isInvalid() && "Loop not in a valid state!");
223 unsigned NumBackEdges = 0;
224 BlockT *H = getHeader();
226 for (const auto Pred : children<Inverse<BlockT *>>(H))
233 //===--------------------------------------------------------------------===//
234 // APIs for simple analysis of the loop.
236 // Note that all of these methods can fail on general loops (ie, there may not
237 // be a preheader, etc). For best success, the loop simplification and
238 // induction variable canonicalization pass should be used to normalize loops
239 // for easy analysis. These methods assume canonical loops.
241 /// Return all blocks inside the loop that have successors outside of the
242 /// loop. These are the blocks _inside of the current loop_ which branch out.
243 /// The returned list is always unique.
244 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
246 /// If getExitingBlocks would return exactly one block, return that block.
247 /// Otherwise return null.
248 BlockT *getExitingBlock() const;
250 /// Return all of the successor blocks of this loop. These are the blocks
251 /// _outside of the current loop_ which are branched to.
252 void getExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
254 /// If getExitBlocks would return exactly one block, return that block.
255 /// Otherwise return null.
256 BlockT *getExitBlock() const;
259 typedef std::pair<const BlockT *, const BlockT *> Edge;
261 /// Return all pairs of (_inside_block_,_outside_block_).
262 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
264 /// If there is a preheader for this loop, return it. A loop has a preheader
265 /// if there is only one edge to the header of the loop from outside of the
266 /// loop. If this is the case, the block branching to the header of the loop
267 /// is the preheader node.
269 /// This method returns null if there is no preheader for the loop.
270 BlockT *getLoopPreheader() const;
272 /// If the given loop's header has exactly one unique predecessor outside the
273 /// loop, return it. Otherwise return null.
274 /// This is less strict that the loop "preheader" concept, which requires
275 /// the predecessor to have exactly one successor.
276 BlockT *getLoopPredecessor() const;
278 /// If there is a single latch block for this loop, return it.
279 /// A latch block is a block that contains a branch back to the header.
280 BlockT *getLoopLatch() const;
282 /// Return all loop latch blocks of this loop. A latch block is a block that
283 /// contains a branch back to the header.
284 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
285 assert(!isInvalid() && "Loop not in a valid state!");
286 BlockT *H = getHeader();
287 for (const auto Pred : children<Inverse<BlockT *>>(H))
289 LoopLatches.push_back(Pred);
292 //===--------------------------------------------------------------------===//
293 // APIs for updating loop information after changing the CFG
296 /// This method is used by other analyses to update loop information.
297 /// NewBB is set to be a new member of the current loop.
298 /// Because of this, it is added as a member of all parent loops, and is added
299 /// to the specified LoopInfo object as being in the current basic block. It
300 /// is not valid to replace the loop header with this method.
301 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
303 /// This is used when splitting loops up. It replaces the OldChild entry in
304 /// our children list with NewChild, and updates the parent pointer of
305 /// OldChild to be null and the NewChild to be this loop.
306 /// This updates the loop depth of the new child.
307 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
309 /// Add the specified loop to be a child of this loop.
310 /// This updates the loop depth of the new child.
311 void addChildLoop(LoopT *NewChild) {
312 assert(!isInvalid() && "Loop not in a valid state!");
313 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
314 NewChild->ParentLoop = static_cast<LoopT *>(this);
315 SubLoops.push_back(NewChild);
318 /// This removes the specified child from being a subloop of this loop. The
319 /// loop is not deleted, as it will presumably be inserted into another loop.
320 LoopT *removeChildLoop(iterator I) {
321 assert(!isInvalid() && "Loop not in a valid state!");
322 assert(I != SubLoops.end() && "Cannot remove end iterator!");
324 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
325 SubLoops.erase(SubLoops.begin() + (I - begin()));
326 Child->ParentLoop = nullptr;
330 /// This removes the specified child from being a subloop of this loop. The
331 /// loop is not deleted, as it will presumably be inserted into another loop.
332 LoopT *removeChildLoop(LoopT *Child) {
333 return removeChildLoop(llvm::find(*this, Child));
336 /// This adds a basic block directly to the basic block list.
337 /// This should only be used by transformations that create new loops. Other
338 /// transformations should use addBasicBlockToLoop.
339 void addBlockEntry(BlockT *BB) {
340 assert(!isInvalid() && "Loop not in a valid state!");
341 Blocks.push_back(BB);
342 DenseBlockSet.insert(BB);
345 /// interface to reverse Blocks[from, end of loop] in this loop
346 void reverseBlock(unsigned from) {
347 assert(!isInvalid() && "Loop not in a valid state!");
348 std::reverse(Blocks.begin() + from, Blocks.end());
351 /// interface to do reserve() for Blocks
352 void reserveBlocks(unsigned size) {
353 assert(!isInvalid() && "Loop not in a valid state!");
354 Blocks.reserve(size);
357 /// This method is used to move BB (which must be part of this loop) to be the
358 /// loop header of the loop (the block that dominates all others).
359 void moveToHeader(BlockT *BB) {
360 assert(!isInvalid() && "Loop not in a valid state!");
363 for (unsigned i = 0;; ++i) {
364 assert(i != Blocks.size() && "Loop does not contain BB!");
365 if (Blocks[i] == BB) {
366 Blocks[i] = Blocks[0];
373 /// This removes the specified basic block from the current loop, updating the
374 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
376 void removeBlockFromLoop(BlockT *BB) {
377 assert(!isInvalid() && "Loop not in a valid state!");
378 auto I = find(Blocks, BB);
379 assert(I != Blocks.end() && "N is not in this list!");
382 DenseBlockSet.erase(BB);
385 /// Verify loop structure
386 void verifyLoop() const;
388 /// Verify loop structure of this loop and all nested loops.
389 void verifyLoopNest(DenseSet<const LoopT *> *Loops) const;
391 /// Print loop with all the BBs inside it.
392 void print(raw_ostream &OS, unsigned Depth = 0, bool Verbose = false) const;
395 friend class LoopInfoBase<BlockT, LoopT>;
397 /// This creates an empty loop.
398 LoopBase() : ParentLoop(nullptr) {}
400 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
401 Blocks.push_back(BB);
402 DenseBlockSet.insert(BB);
405 // Since loop passes like SCEV are allowed to key analysis results off of
406 // `Loop` pointers, we cannot re-use pointers within a loop pass manager.
407 // This means loop passes should not be `delete` ing `Loop` objects directly
408 // (and risk a later `Loop` allocation re-using the address of a previous one)
409 // but should be using LoopInfo::markAsRemoved, which keeps around the `Loop`
410 // pointer till the end of the lifetime of the `LoopInfo` object.
412 // To make it easier to follow this rule, we mark the destructor as
415 for (auto *SubLoop : SubLoops)
418 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
423 DenseBlockSet.clear();
424 ParentLoop = nullptr;
428 template <class BlockT, class LoopT>
429 raw_ostream &operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
434 // Implementation in LoopInfoImpl.h
435 extern template class LoopBase<BasicBlock, Loop>;
437 /// Represents a single loop in the control flow graph. Note that not all SCCs
438 /// in the CFG are necessarily loops.
439 class Loop : public LoopBase<BasicBlock, Loop> {
441 /// \brief A range representing the start and end location of a loop.
448 LocRange(DebugLoc Start) : Start(std::move(Start)), End(std::move(Start)) {}
449 LocRange(DebugLoc Start, DebugLoc End)
450 : Start(std::move(Start)), End(std::move(End)) {}
452 const DebugLoc &getStart() const { return Start; }
453 const DebugLoc &getEnd() const { return End; }
455 /// \brief Check for null.
457 explicit operator bool() const { return Start && End; }
460 /// Return true if the specified value is loop invariant.
461 bool isLoopInvariant(const Value *V) const;
463 /// Return true if all the operands of the specified instruction are loop
465 bool hasLoopInvariantOperands(const Instruction *I) const;
467 /// If the given value is an instruction inside of the loop and it can be
468 /// hoisted, do so to make it trivially loop-invariant.
469 /// Return true if the value after any hoisting is loop invariant. This
470 /// function can be used as a slightly more aggressive replacement for
473 /// If InsertPt is specified, it is the point to hoist instructions to.
474 /// If null, the terminator of the loop preheader is used.
475 bool makeLoopInvariant(Value *V, bool &Changed,
476 Instruction *InsertPt = nullptr) const;
478 /// If the given instruction is inside of the loop and it can be hoisted, do
479 /// so to make it trivially loop-invariant.
480 /// Return true if the instruction after any hoisting is loop invariant. This
481 /// function can be used as a slightly more aggressive replacement for
484 /// If InsertPt is specified, it is the point to hoist instructions to.
485 /// If null, the terminator of the loop preheader is used.
487 bool makeLoopInvariant(Instruction *I, bool &Changed,
488 Instruction *InsertPt = nullptr) const;
490 /// Check to see if the loop has a canonical induction variable: an integer
491 /// recurrence that starts at 0 and increments by one each time through the
492 /// loop. If so, return the phi node that corresponds to it.
494 /// The IndVarSimplify pass transforms loops to have a canonical induction
497 PHINode *getCanonicalInductionVariable() const;
499 /// Return true if the Loop is in LCSSA form.
500 bool isLCSSAForm(DominatorTree &DT) const;
502 /// Return true if this Loop and all inner subloops are in LCSSA form.
503 bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const;
505 /// Return true if the Loop is in the form that the LoopSimplify form
506 /// transforms loops to, which is sometimes called normal form.
507 bool isLoopSimplifyForm() const;
509 /// Return true if the loop body is safe to clone in practice.
510 bool isSafeToClone() const;
512 /// Returns true if the loop is annotated parallel.
514 /// A parallel loop can be assumed to not contain any dependencies between
515 /// iterations by the compiler. That is, any loop-carried dependency checking
516 /// can be skipped completely when parallelizing the loop on the target
517 /// machine. Thus, if the parallel loop information originates from the
518 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
519 /// programmer's responsibility to ensure there are no loop-carried
520 /// dependencies. The final execution order of the instructions across
521 /// iterations is not guaranteed, thus, the end result might or might not
522 /// implement actual concurrent execution of instructions across multiple
524 bool isAnnotatedParallel() const;
526 /// Return the llvm.loop loop id metadata node for this loop if it is present.
528 /// If this loop contains the same llvm.loop metadata on each branch to the
529 /// header then the node is returned. If any latch instruction does not
530 /// contain llvm.loop or or if multiple latches contain different nodes then
532 MDNode *getLoopID() const;
533 /// Set the llvm.loop loop id metadata for this loop.
535 /// The LoopID metadata node will be added to each terminator instruction in
536 /// the loop that branches to the loop header.
538 /// The LoopID metadata node should have one or more operands and the first
539 /// operand should be the node itself.
540 void setLoopID(MDNode *LoopID) const;
542 /// Add llvm.loop.unroll.disable to this loop's loop id metadata.
544 /// Remove existing unroll metadata and add unroll disable metadata to
545 /// indicate the loop has already been unrolled. This prevents a loop
546 /// from being unrolled more than is directed by a pragma if the loop
547 /// unrolling pass is run more than once (which it generally is).
548 void setLoopAlreadyUnrolled();
550 /// Return true if no exit block for the loop has a predecessor that is
551 /// outside the loop.
552 bool hasDedicatedExits() const;
554 /// Return all unique successor blocks of this loop.
555 /// These are the blocks _outside of the current loop_ which are branched to.
556 /// This assumes that loop exits are in canonical form, i.e. all exits are
558 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
560 /// If getUniqueExitBlocks would return exactly one block, return that block.
561 /// Otherwise return null.
562 BasicBlock *getUniqueExitBlock() const;
565 void dumpVerbose() const;
567 /// Return the debug location of the start of this loop.
568 /// This looks for a BB terminating instruction with a known debug
569 /// location by looking at the preheader and header blocks. If it
570 /// cannot find a terminating instruction with location information,
571 /// it returns an unknown location.
572 DebugLoc getStartLoc() const;
574 /// Return the source code span of the loop.
575 LocRange getLocRange() const;
577 StringRef getName() const {
578 if (BasicBlock *Header = getHeader())
579 if (Header->hasName())
580 return Header->getName();
581 return "<unnamed loop>";
587 friend class LoopInfoBase<BasicBlock, Loop>;
588 friend class LoopBase<BasicBlock, Loop>;
589 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
593 //===----------------------------------------------------------------------===//
594 /// This class builds and contains all of the top-level loop
595 /// structures in the specified function.
598 template <class BlockT, class LoopT> class LoopInfoBase {
599 // BBMap - Mapping of basic blocks to the inner most loop they occur in
600 DenseMap<const BlockT *, LoopT *> BBMap;
601 std::vector<LoopT *> TopLevelLoops;
602 BumpPtrAllocator LoopAllocator;
604 friend class LoopBase<BlockT, LoopT>;
605 friend class LoopInfo;
607 void operator=(const LoopInfoBase &) = delete;
608 LoopInfoBase(const LoopInfoBase &) = delete;
612 ~LoopInfoBase() { releaseMemory(); }
614 LoopInfoBase(LoopInfoBase &&Arg)
615 : BBMap(std::move(Arg.BBMap)),
616 TopLevelLoops(std::move(Arg.TopLevelLoops)),
617 LoopAllocator(std::move(Arg.LoopAllocator)) {
618 // We have to clear the arguments top level loops as we've taken ownership.
619 Arg.TopLevelLoops.clear();
621 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
622 BBMap = std::move(RHS.BBMap);
624 for (auto *L : TopLevelLoops)
627 TopLevelLoops = std::move(RHS.TopLevelLoops);
628 LoopAllocator = std::move(RHS.LoopAllocator);
629 RHS.TopLevelLoops.clear();
633 void releaseMemory() {
636 for (auto *L : TopLevelLoops)
638 TopLevelLoops.clear();
639 LoopAllocator.Reset();
642 template <typename... ArgsTy> LoopT *AllocateLoop(ArgsTy &&... Args) {
643 LoopT *Storage = LoopAllocator.Allocate<LoopT>();
644 return new (Storage) LoopT(std::forward<ArgsTy>(Args)...);
647 /// iterator/begin/end - The interface to the top-level loops in the current
650 typedef typename std::vector<LoopT *>::const_iterator iterator;
652 typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
653 iterator begin() const { return TopLevelLoops.begin(); }
654 iterator end() const { return TopLevelLoops.end(); }
655 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
656 reverse_iterator rend() const { return TopLevelLoops.rend(); }
657 bool empty() const { return TopLevelLoops.empty(); }
659 /// Return all of the loops in the function in preorder across the loop
660 /// nests, with siblings in forward program order.
662 /// Note that because loops form a forest of trees, preorder is equivalent to
663 /// reverse postorder.
664 SmallVector<LoopT *, 4> getLoopsInPreorder();
666 /// Return all of the loops in the function in preorder across the loop
667 /// nests, with siblings in *reverse* program order.
669 /// Note that because loops form a forest of trees, preorder is equivalent to
670 /// reverse postorder.
672 /// Also note that this is *not* a reverse preorder. Only the siblings are in
673 /// reverse program order.
674 SmallVector<LoopT *, 4> getLoopsInReverseSiblingPreorder();
676 /// Return the inner most loop that BB lives in. If a basic block is in no
677 /// loop (for example the entry node), null is returned.
678 LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
680 /// Same as getLoopFor.
681 const LoopT *operator[](const BlockT *BB) const { return getLoopFor(BB); }
683 /// Return the loop nesting level of the specified block. A depth of 0 means
684 /// the block is not inside any loop.
685 unsigned getLoopDepth(const BlockT *BB) const {
686 const LoopT *L = getLoopFor(BB);
687 return L ? L->getLoopDepth() : 0;
690 // True if the block is a loop header node
691 bool isLoopHeader(const BlockT *BB) const {
692 const LoopT *L = getLoopFor(BB);
693 return L && L->getHeader() == BB;
696 /// This removes the specified top-level loop from this loop info object.
697 /// The loop is not deleted, as it will presumably be inserted into
699 LoopT *removeLoop(iterator I) {
700 assert(I != end() && "Cannot remove end iterator!");
702 assert(!L->getParentLoop() && "Not a top-level loop!");
703 TopLevelLoops.erase(TopLevelLoops.begin() + (I - begin()));
707 /// Change the top-level loop that contains BB to the specified loop.
708 /// This should be used by transformations that restructure the loop hierarchy
710 void changeLoopFor(BlockT *BB, LoopT *L) {
718 /// Replace the specified loop in the top-level loops list with the indicated
720 void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop) {
721 auto I = find(TopLevelLoops, OldLoop);
722 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
724 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
725 "Loops already embedded into a subloop!");
728 /// This adds the specified loop to the collection of top-level loops.
729 void addTopLevelLoop(LoopT *New) {
730 assert(!New->getParentLoop() && "Loop already in subloop!");
731 TopLevelLoops.push_back(New);
734 /// This method completely removes BB from all data structures,
735 /// including all of the Loop objects it is nested in and our mapping from
736 /// BasicBlocks to loops.
737 void removeBlock(BlockT *BB) {
738 auto I = BBMap.find(BB);
739 if (I != BBMap.end()) {
740 for (LoopT *L = I->second; L; L = L->getParentLoop())
741 L->removeBlockFromLoop(BB);
749 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
750 const LoopT *ParentLoop) {
753 if (SubLoop == ParentLoop)
755 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
758 /// Create the loop forest using a stable algorithm.
759 void analyze(const DominatorTreeBase<BlockT, false> &DomTree);
762 void print(raw_ostream &OS) const;
764 void verify(const DominatorTreeBase<BlockT, false> &DomTree) const;
766 /// Destroy a loop that has been removed from the `LoopInfo` nest.
768 /// This runs the destructor of the loop object making it invalid to
769 /// reference afterward. The memory is retained so that the *pointer* to the
770 /// loop remains valid.
772 /// The caller is responsible for removing this loop from the loop nest and
773 /// otherwise disconnecting it from the broader `LoopInfo` data structures.
774 /// Callers that don't naturally handle this themselves should probably call
776 void destroy(LoopT *L) {
779 // Since LoopAllocator is a BumpPtrAllocator, this Deallocate only poisons
780 // \c L, but the pointer remains valid for non-dereferencing uses.
781 LoopAllocator.Deallocate(L);
785 // Implementation in LoopInfoImpl.h
786 extern template class LoopInfoBase<BasicBlock, Loop>;
788 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
789 typedef LoopInfoBase<BasicBlock, Loop> BaseT;
791 friend class LoopBase<BasicBlock, Loop>;
793 void operator=(const LoopInfo &) = delete;
794 LoopInfo(const LoopInfo &) = delete;
798 explicit LoopInfo(const DominatorTreeBase<BasicBlock, false> &DomTree);
800 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
801 LoopInfo &operator=(LoopInfo &&RHS) {
802 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
806 /// Handle invalidation explicitly.
807 bool invalidate(Function &F, const PreservedAnalyses &PA,
808 FunctionAnalysisManager::Invalidator &);
810 // Most of the public interface is provided via LoopInfoBase.
812 /// Update LoopInfo after removing the last backedge from a loop. This updates
813 /// the loop forest and parent loops for each block so that \c L is no longer
814 /// referenced, but does not actually delete \c L immediately. The pointer
815 /// will remain valid until this LoopInfo's memory is released.
818 /// Returns true if replacing From with To everywhere is guaranteed to
819 /// preserve LCSSA form.
820 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
821 // Preserving LCSSA form is only problematic if the replacing value is an
823 Instruction *I = dyn_cast<Instruction>(To);
826 // If both instructions are defined in the same basic block then replacement
827 // cannot break LCSSA form.
828 if (I->getParent() == From->getParent())
830 // If the instruction is not defined in a loop then it can safely replace
832 Loop *ToLoop = getLoopFor(I->getParent());
835 // If the replacing instruction is defined in the same loop as the original
836 // instruction, or in a loop that contains it as an inner loop, then using
837 // it as a replacement will not break LCSSA form.
838 return ToLoop->contains(getLoopFor(From->getParent()));
841 /// Checks if moving a specific instruction can break LCSSA in any loop.
843 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
844 /// assuming that the function containing \p Inst and \p NewLoc is currently
846 bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
847 assert(Inst->getFunction() == NewLoc->getFunction() &&
848 "Can't reason about IPO!");
850 auto *OldBB = Inst->getParent();
851 auto *NewBB = NewLoc->getParent();
853 // Movement within the same loop does not break LCSSA (the equality check is
854 // to avoid doing a hashtable lookup in case of intra-block movement).
858 auto *OldLoop = getLoopFor(OldBB);
859 auto *NewLoop = getLoopFor(NewBB);
861 if (OldLoop == NewLoop)
864 // Check if Outer contains Inner; with the null loop counting as the
866 auto Contains = [](const Loop *Outer, const Loop *Inner) {
867 return !Outer || Outer->contains(Inner);
870 // To check that the movement of Inst to before NewLoc does not break LCSSA,
871 // we need to check two sets of uses for possible LCSSA violations at
872 // NewLoc: the users of NewInst, and the operands of NewInst.
874 // If we know we're hoisting Inst out of an inner loop to an outer loop,
875 // then the uses *of* Inst don't need to be checked.
877 if (!Contains(NewLoop, OldLoop)) {
878 for (Use &U : Inst->uses()) {
879 auto *UI = cast<Instruction>(U.getUser());
880 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
882 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
887 // If we know we're sinking Inst from an outer loop into an inner loop, then
888 // the *operands* of Inst don't need to be checked.
890 if (!Contains(OldLoop, NewLoop)) {
891 // See below on why we can't handle phi nodes here.
892 if (isa<PHINode>(Inst))
895 for (Use &U : Inst->operands()) {
896 auto *DefI = dyn_cast<Instruction>(U.get());
900 // This would need adjustment if we allow Inst to be a phi node -- the
901 // new use block won't simply be NewBB.
903 auto *DefBlock = DefI->getParent();
904 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
913 // Allow clients to walk the list of nested loops...
914 template <> struct GraphTraits<const Loop *> {
915 typedef const Loop *NodeRef;
916 typedef LoopInfo::iterator ChildIteratorType;
918 static NodeRef getEntryNode(const Loop *L) { return L; }
919 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
920 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
923 template <> struct GraphTraits<Loop *> {
924 typedef Loop *NodeRef;
925 typedef LoopInfo::iterator ChildIteratorType;
927 static NodeRef getEntryNode(Loop *L) { return L; }
928 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
929 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
932 /// \brief Analysis pass that exposes the \c LoopInfo for a function.
933 class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> {
934 friend AnalysisInfoMixin<LoopAnalysis>;
935 static AnalysisKey Key;
938 typedef LoopInfo Result;
940 LoopInfo run(Function &F, FunctionAnalysisManager &AM);
943 /// \brief Printer pass for the \c LoopAnalysis results.
944 class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> {
948 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
949 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
952 /// \brief Verifier pass for the \c LoopAnalysis results.
953 struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> {
954 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
957 /// \brief The legacy pass manager's analysis pass to compute loop information.
958 class LoopInfoWrapperPass : public FunctionPass {
962 static char ID; // Pass identification, replacement for typeid
964 LoopInfoWrapperPass() : FunctionPass(ID) {
965 initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
968 LoopInfo &getLoopInfo() { return LI; }
969 const LoopInfo &getLoopInfo() const { return LI; }
971 /// \brief Calculate the natural loop information for a given function.
972 bool runOnFunction(Function &F) override;
974 void verifyAnalysis() const override;
976 void releaseMemory() override { LI.releaseMemory(); }
978 void print(raw_ostream &O, const Module *M = nullptr) const override;
980 void getAnalysisUsage(AnalysisUsage &AU) const override;
983 /// Function to print a loop's contents as LLVM's text IR assembly.
984 void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner = "");
986 } // End llvm namespace