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"
59 template <class N, bool IsPostDom>
60 class DominatorTreeBase;
61 template<class N, class M> class LoopInfoBase;
62 template<class N, class M> class LoopBase;
64 //===----------------------------------------------------------------------===//
65 /// Instances of this class are used to represent loops that are detected in the
68 template<class BlockT, class LoopT>
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 /// Indicator that this loop is no longer a valid loop.
80 bool IsInvalid = false;
82 LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
83 const LoopBase<BlockT, LoopT>&
84 operator=(const LoopBase<BlockT, LoopT> &) = delete;
86 /// This creates an empty loop.
87 LoopBase() : ParentLoop(nullptr) {}
89 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
93 /// Return the nesting level of this loop. An outer-most loop has depth 1,
94 /// for consistency with loop depth values used for basic blocks, where depth
95 /// 0 is used for blocks not inside any loops.
96 unsigned getLoopDepth() const {
98 for (const LoopT *CurLoop = ParentLoop; CurLoop;
99 CurLoop = CurLoop->ParentLoop)
103 BlockT *getHeader() const { return Blocks.front(); }
104 LoopT *getParentLoop() const { return ParentLoop; }
106 /// This is a raw interface for bypassing addChildLoop.
107 void setParentLoop(LoopT *L) { ParentLoop = L; }
109 /// Return true if the specified loop is contained within in this loop.
110 bool contains(const LoopT *L) const {
111 if (L == this) return true;
112 if (!L) return false;
113 return contains(L->getParentLoop());
116 /// Return true if the specified basic block is in this loop.
117 bool contains(const BlockT *BB) const {
118 return DenseBlockSet.count(BB);
121 /// Return true if the specified instruction is in this loop.
122 template<class InstT>
123 bool contains(const InstT *Inst) const {
124 return contains(Inst->getParent());
127 /// Return the loops contained entirely within this loop.
128 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
129 std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
130 typedef typename std::vector<LoopT *>::const_iterator iterator;
131 typedef typename std::vector<LoopT *>::const_reverse_iterator
133 iterator begin() const { return SubLoops.begin(); }
134 iterator end() const { return SubLoops.end(); }
135 reverse_iterator rbegin() const { return SubLoops.rbegin(); }
136 reverse_iterator rend() const { return SubLoops.rend(); }
137 bool empty() const { return SubLoops.empty(); }
139 /// Get a list of the basic blocks which make up this loop.
140 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
141 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
142 block_iterator block_begin() const { return Blocks.begin(); }
143 block_iterator block_end() const { return Blocks.end(); }
144 inline iterator_range<block_iterator> blocks() const {
145 return make_range(block_begin(), block_end());
148 /// Get the number of blocks in this loop in constant time.
149 unsigned getNumBlocks() const {
150 return Blocks.size();
153 /// Invalidate the loop, indicating that it is no longer a loop.
154 void invalidate() { IsInvalid = true; }
156 /// Return true if this loop is no longer valid.
157 bool isInvalid() { return IsInvalid; }
159 /// True if terminator in the block can branch to another block that is
160 /// outside of the current loop.
161 bool isLoopExiting(const BlockT *BB) const {
162 for (const auto &Succ : children<const BlockT*>(BB)) {
169 /// Returns true if \p BB is a loop-latch.
170 /// A latch block is a block that contains a branch back to the header.
171 /// This function is useful when there are multiple latches in a loop
172 /// because \fn getLoopLatch will return nullptr in that case.
173 bool isLoopLatch(const BlockT *BB) const {
174 assert(contains(BB) && "block does not belong to the loop");
176 BlockT *Header = getHeader();
177 auto PredBegin = GraphTraits<Inverse<BlockT*> >::child_begin(Header);
178 auto PredEnd = GraphTraits<Inverse<BlockT*> >::child_end(Header);
179 return std::find(PredBegin, PredEnd, BB) != PredEnd;
182 /// Calculate the number of back edges to the loop header.
183 unsigned getNumBackEdges() const {
184 unsigned NumBackEdges = 0;
185 BlockT *H = getHeader();
187 for (const auto Pred : children<Inverse<BlockT*> >(H))
194 //===--------------------------------------------------------------------===//
195 // APIs for simple analysis of the loop.
197 // Note that all of these methods can fail on general loops (ie, there may not
198 // be a preheader, etc). For best success, the loop simplification and
199 // induction variable canonicalization pass should be used to normalize loops
200 // for easy analysis. These methods assume canonical loops.
202 /// Return all blocks inside the loop that have successors outside of the
203 /// loop. These are the blocks _inside of the current loop_ which branch out.
204 /// The returned list is always unique.
205 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
207 /// If getExitingBlocks would return exactly one block, return that block.
208 /// Otherwise return null.
209 BlockT *getExitingBlock() const;
211 /// Return all of the successor blocks of this loop. These are the blocks
212 /// _outside of the current loop_ which are branched to.
213 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
215 /// If getExitBlocks would return exactly one block, return that block.
216 /// Otherwise return null.
217 BlockT *getExitBlock() const;
220 typedef std::pair<const BlockT*, const BlockT*> Edge;
222 /// Return all pairs of (_inside_block_,_outside_block_).
223 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
225 /// If there is a preheader for this loop, return it. A loop has a preheader
226 /// if there is only one edge to the header of the loop from outside of the
227 /// loop. If this is the case, the block branching to the header of the loop
228 /// is the preheader node.
230 /// This method returns null if there is no preheader for the loop.
231 BlockT *getLoopPreheader() const;
233 /// If the given loop's header has exactly one unique predecessor outside the
234 /// loop, return it. Otherwise return null.
235 /// This is less strict that the loop "preheader" concept, which requires
236 /// the predecessor to have exactly one successor.
237 BlockT *getLoopPredecessor() const;
239 /// If there is a single latch block for this loop, return it.
240 /// A latch block is a block that contains a branch back to the header.
241 BlockT *getLoopLatch() const;
243 /// Return all loop latch blocks of this loop. A latch block is a block that
244 /// contains a branch back to the header.
245 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
246 BlockT *H = getHeader();
247 for (const auto Pred : children<Inverse<BlockT*>>(H))
249 LoopLatches.push_back(Pred);
252 //===--------------------------------------------------------------------===//
253 // APIs for updating loop information after changing the CFG
256 /// This method is used by other analyses to update loop information.
257 /// NewBB is set to be a new member of the current loop.
258 /// Because of this, it is added as a member of all parent loops, and is added
259 /// to the specified LoopInfo object as being in the current basic block. It
260 /// is not valid to replace the loop header with this method.
261 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
263 /// This is used when splitting loops up. It replaces the OldChild entry in
264 /// our children list with NewChild, and updates the parent pointer of
265 /// OldChild to be null and the NewChild to be this loop.
266 /// This updates the loop depth of the new child.
267 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
269 /// Add the specified loop to be a child of this loop.
270 /// This updates the loop depth of the new child.
271 void addChildLoop(LoopT *NewChild) {
272 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
273 NewChild->ParentLoop = static_cast<LoopT *>(this);
274 SubLoops.push_back(NewChild);
277 /// This removes the specified child from being a subloop of this loop. The
278 /// loop is not deleted, as it will presumably be inserted into another loop.
279 LoopT *removeChildLoop(iterator I) {
280 assert(I != SubLoops.end() && "Cannot remove end iterator!");
282 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
283 SubLoops.erase(SubLoops.begin()+(I-begin()));
284 Child->ParentLoop = nullptr;
288 /// This adds a basic block directly to the basic block list.
289 /// This should only be used by transformations that create new loops. Other
290 /// transformations should use addBasicBlockToLoop.
291 void addBlockEntry(BlockT *BB) {
292 Blocks.push_back(BB);
293 DenseBlockSet.insert(BB);
296 /// interface to reverse Blocks[from, end of loop] in this loop
297 void reverseBlock(unsigned from) {
298 std::reverse(Blocks.begin() + from, Blocks.end());
301 /// interface to do reserve() for Blocks
302 void reserveBlocks(unsigned size) {
303 Blocks.reserve(size);
306 /// This method is used to move BB (which must be part of this loop) to be the
307 /// loop header of the loop (the block that dominates all others).
308 void moveToHeader(BlockT *BB) {
309 if (Blocks[0] == BB) return;
310 for (unsigned i = 0; ; ++i) {
311 assert(i != Blocks.size() && "Loop does not contain BB!");
312 if (Blocks[i] == BB) {
313 Blocks[i] = Blocks[0];
320 /// This removes the specified basic block from the current loop, updating the
321 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
323 void removeBlockFromLoop(BlockT *BB) {
324 auto I = find(Blocks, BB);
325 assert(I != Blocks.end() && "N is not in this list!");
328 DenseBlockSet.erase(BB);
331 /// Verify loop structure
332 void verifyLoop() const;
334 /// Verify loop structure of this loop and all nested loops.
335 void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
337 /// Print loop with all the BBs inside it.
338 void print(raw_ostream &OS, unsigned Depth = 0, bool Verbose = false) const;
341 friend class LoopInfoBase<BlockT, LoopT>;
342 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
343 Blocks.push_back(BB);
344 DenseBlockSet.insert(BB);
348 template<class BlockT, class LoopT>
349 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
354 // Implementation in LoopInfoImpl.h
355 extern template class LoopBase<BasicBlock, Loop>;
358 /// Represents a single loop in the control flow graph. Note that not all SCCs
359 /// in the CFG are necessarily loops.
360 class Loop : public LoopBase<BasicBlock, Loop> {
362 /// \brief A range representing the start and end location of a loop.
369 LocRange(DebugLoc Start) : Start(std::move(Start)), End(std::move(Start)) {}
370 LocRange(DebugLoc Start, DebugLoc End) : Start(std::move(Start)),
371 End(std::move(End)) {}
373 const DebugLoc &getStart() const { return Start; }
374 const DebugLoc &getEnd() const { return End; }
376 /// \brief Check for null.
378 explicit operator bool() const {
385 /// Return true if the specified value is loop invariant.
386 bool isLoopInvariant(const Value *V) const;
388 /// Return true if all the operands of the specified instruction are loop
390 bool hasLoopInvariantOperands(const Instruction *I) const;
392 /// If the given value is an instruction inside of the loop and it can be
393 /// hoisted, do so to make it trivially loop-invariant.
394 /// Return true if the value after any hoisting is loop invariant. This
395 /// function can be used as a slightly more aggressive replacement for
398 /// If InsertPt is specified, it is the point to hoist instructions to.
399 /// If null, the terminator of the loop preheader is used.
400 bool makeLoopInvariant(Value *V, bool &Changed,
401 Instruction *InsertPt = nullptr) const;
403 /// If the given instruction is inside of the loop and it can be hoisted, do
404 /// so to make it trivially loop-invariant.
405 /// Return true if the instruction after any hoisting is loop invariant. This
406 /// function can be used as a slightly more aggressive replacement for
409 /// If InsertPt is specified, it is the point to hoist instructions to.
410 /// If null, the terminator of the loop preheader is used.
412 bool makeLoopInvariant(Instruction *I, bool &Changed,
413 Instruction *InsertPt = nullptr) const;
415 /// Check to see if the loop has a canonical induction variable: an integer
416 /// recurrence that starts at 0 and increments by one each time through the
417 /// loop. If so, return the phi node that corresponds to it.
419 /// The IndVarSimplify pass transforms loops to have a canonical induction
422 PHINode *getCanonicalInductionVariable() const;
424 /// Return true if the Loop is in LCSSA form.
425 bool isLCSSAForm(DominatorTree &DT) const;
427 /// Return true if this Loop and all inner subloops are in LCSSA form.
428 bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const;
430 /// Return true if the Loop is in the form that the LoopSimplify form
431 /// transforms loops to, which is sometimes called normal form.
432 bool isLoopSimplifyForm() const;
434 /// Return true if the loop body is safe to clone in practice.
435 bool isSafeToClone() const;
437 /// Returns true if the loop is annotated parallel.
439 /// A parallel loop can be assumed to not contain any dependencies between
440 /// iterations by the compiler. That is, any loop-carried dependency checking
441 /// can be skipped completely when parallelizing the loop on the target
442 /// machine. Thus, if the parallel loop information originates from the
443 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
444 /// programmer's responsibility to ensure there are no loop-carried
445 /// dependencies. The final execution order of the instructions across
446 /// iterations is not guaranteed, thus, the end result might or might not
447 /// implement actual concurrent execution of instructions across multiple
449 bool isAnnotatedParallel() const;
451 /// Return the llvm.loop loop id metadata node for this loop if it is present.
453 /// If this loop contains the same llvm.loop metadata on each branch to the
454 /// header then the node is returned. If any latch instruction does not
455 /// contain llvm.loop or or if multiple latches contain different nodes then
457 MDNode *getLoopID() const;
458 /// Set the llvm.loop loop id metadata for this loop.
460 /// The LoopID metadata node will be added to each terminator instruction in
461 /// the loop that branches to the loop header.
463 /// The LoopID metadata node should have one or more operands and the first
464 /// operand should be the node itself.
465 void setLoopID(MDNode *LoopID) const;
467 /// Return true if no exit block for the loop has a predecessor that is
468 /// outside the loop.
469 bool hasDedicatedExits() const;
471 /// Return all unique successor blocks of this loop.
472 /// These are the blocks _outside of the current loop_ which are branched to.
473 /// This assumes that loop exits are in canonical form, i.e. all exits are
475 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
477 /// If getUniqueExitBlocks would return exactly one block, return that block.
478 /// Otherwise return null.
479 BasicBlock *getUniqueExitBlock() const;
482 void dumpVerbose() const;
484 /// Return the debug location of the start of this loop.
485 /// This looks for a BB terminating instruction with a known debug
486 /// location by looking at the preheader and header blocks. If it
487 /// cannot find a terminating instruction with location information,
488 /// it returns an unknown location.
489 DebugLoc getStartLoc() const;
491 /// Return the source code span of the loop.
492 LocRange getLocRange() const;
494 StringRef getName() const {
495 if (BasicBlock *Header = getHeader())
496 if (Header->hasName())
497 return Header->getName();
498 return "<unnamed loop>";
502 friend class LoopInfoBase<BasicBlock, Loop>;
503 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
506 //===----------------------------------------------------------------------===//
507 /// This class builds and contains all of the top-level loop
508 /// structures in the specified function.
511 template<class BlockT, class LoopT>
513 // BBMap - Mapping of basic blocks to the inner most loop they occur in
514 DenseMap<const BlockT *, LoopT *> BBMap;
515 std::vector<LoopT *> TopLevelLoops;
516 std::vector<LoopT *> RemovedLoops;
518 friend class LoopBase<BlockT, LoopT>;
519 friend class LoopInfo;
521 void operator=(const LoopInfoBase &) = delete;
522 LoopInfoBase(const LoopInfoBase &) = delete;
525 ~LoopInfoBase() { releaseMemory(); }
527 LoopInfoBase(LoopInfoBase &&Arg)
528 : BBMap(std::move(Arg.BBMap)),
529 TopLevelLoops(std::move(Arg.TopLevelLoops)) {
530 // We have to clear the arguments top level loops as we've taken ownership.
531 Arg.TopLevelLoops.clear();
533 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
534 BBMap = std::move(RHS.BBMap);
536 for (auto *L : TopLevelLoops)
538 TopLevelLoops = std::move(RHS.TopLevelLoops);
539 RHS.TopLevelLoops.clear();
543 void releaseMemory() {
546 for (auto *L : TopLevelLoops)
548 TopLevelLoops.clear();
549 for (auto *L : RemovedLoops)
551 RemovedLoops.clear();
554 /// iterator/begin/end - The interface to the top-level loops in the current
557 typedef typename std::vector<LoopT *>::const_iterator iterator;
558 typedef typename std::vector<LoopT *>::const_reverse_iterator
560 iterator begin() const { return TopLevelLoops.begin(); }
561 iterator end() const { return TopLevelLoops.end(); }
562 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
563 reverse_iterator rend() const { return TopLevelLoops.rend(); }
564 bool empty() const { return TopLevelLoops.empty(); }
566 /// Return all of the loops in the function in preorder across the loop
567 /// nests, with siblings in forward program order.
569 /// Note that because loops form a forest of trees, preorder is equivalent to
570 /// reverse postorder.
571 SmallVector<LoopT *, 4> getLoopsInPreorder();
573 /// Return all of the loops in the function in preorder across the loop
574 /// nests, with siblings in *reverse* program order.
576 /// Note that because loops form a forest of trees, preorder is equivalent to
577 /// reverse postorder.
579 /// Also note that this is *not* a reverse preorder. Only the siblings are in
580 /// reverse program order.
581 SmallVector<LoopT *, 4> getLoopsInReverseSiblingPreorder();
583 /// Return the inner most loop that BB lives in. If a basic block is in no
584 /// loop (for example the entry node), null is returned.
585 LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
587 /// Same as getLoopFor.
588 const LoopT *operator[](const BlockT *BB) const {
589 return getLoopFor(BB);
592 /// Return the loop nesting level of the specified block. A depth of 0 means
593 /// the block is not inside any loop.
594 unsigned getLoopDepth(const BlockT *BB) const {
595 const LoopT *L = getLoopFor(BB);
596 return L ? L->getLoopDepth() : 0;
599 // True if the block is a loop header node
600 bool isLoopHeader(const BlockT *BB) const {
601 const LoopT *L = getLoopFor(BB);
602 return L && L->getHeader() == BB;
605 /// This removes the specified top-level loop from this loop info object.
606 /// The loop is not deleted, as it will presumably be inserted into
608 LoopT *removeLoop(iterator I) {
609 assert(I != end() && "Cannot remove end iterator!");
611 assert(!L->getParentLoop() && "Not a top-level loop!");
612 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
616 /// Change the top-level loop that contains BB to the specified loop.
617 /// This should be used by transformations that restructure the loop hierarchy
619 void changeLoopFor(BlockT *BB, LoopT *L) {
627 /// Replace the specified loop in the top-level loops list with the indicated
629 void changeTopLevelLoop(LoopT *OldLoop,
631 auto I = find(TopLevelLoops, OldLoop);
632 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
634 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
635 "Loops already embedded into a subloop!");
638 /// This adds the specified loop to the collection of top-level loops.
639 void addTopLevelLoop(LoopT *New) {
640 assert(!New->getParentLoop() && "Loop already in subloop!");
641 TopLevelLoops.push_back(New);
644 /// This method completely removes BB from all data structures,
645 /// including all of the Loop objects it is nested in and our mapping from
646 /// BasicBlocks to loops.
647 void removeBlock(BlockT *BB) {
648 auto I = BBMap.find(BB);
649 if (I != BBMap.end()) {
650 for (LoopT *L = I->second; L; L = L->getParentLoop())
651 L->removeBlockFromLoop(BB);
659 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
660 const LoopT *ParentLoop) {
661 if (!SubLoop) return true;
662 if (SubLoop == ParentLoop) return false;
663 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
666 /// Create the loop forest using a stable algorithm.
667 void analyze(const DominatorTreeBase<BlockT, false> &DomTree);
670 void print(raw_ostream &OS) const;
672 void verify(const DominatorTreeBase<BlockT, false> &DomTree) const;
675 // Implementation in LoopInfoImpl.h
676 extern template class LoopInfoBase<BasicBlock, Loop>;
678 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
679 typedef LoopInfoBase<BasicBlock, Loop> BaseT;
681 friend class LoopBase<BasicBlock, Loop>;
683 void operator=(const LoopInfo &) = delete;
684 LoopInfo(const LoopInfo &) = delete;
687 explicit LoopInfo(const DominatorTreeBase<BasicBlock, false> &DomTree);
689 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
690 LoopInfo &operator=(LoopInfo &&RHS) {
691 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
695 /// Handle invalidation explicitly.
696 bool invalidate(Function &F, const PreservedAnalyses &PA,
697 FunctionAnalysisManager::Invalidator &);
699 // Most of the public interface is provided via LoopInfoBase.
701 /// Update LoopInfo after removing the last backedge from a loop. This updates
702 /// the loop forest and parent loops for each block so that \c L is no longer
703 /// referenced, but does not actually delete \c L immediately. The pointer
704 /// will remain valid until this LoopInfo's memory is released.
705 void markAsRemoved(Loop *L);
707 /// Returns true if replacing From with To everywhere is guaranteed to
708 /// preserve LCSSA form.
709 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
710 // Preserving LCSSA form is only problematic if the replacing value is an
712 Instruction *I = dyn_cast<Instruction>(To);
714 // If both instructions are defined in the same basic block then replacement
715 // cannot break LCSSA form.
716 if (I->getParent() == From->getParent())
718 // If the instruction is not defined in a loop then it can safely replace
720 Loop *ToLoop = getLoopFor(I->getParent());
721 if (!ToLoop) return true;
722 // If the replacing instruction is defined in the same loop as the original
723 // instruction, or in a loop that contains it as an inner loop, then using
724 // it as a replacement will not break LCSSA form.
725 return ToLoop->contains(getLoopFor(From->getParent()));
728 /// Checks if moving a specific instruction can break LCSSA in any loop.
730 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
731 /// assuming that the function containing \p Inst and \p NewLoc is currently
733 bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
734 assert(Inst->getFunction() == NewLoc->getFunction() &&
735 "Can't reason about IPO!");
737 auto *OldBB = Inst->getParent();
738 auto *NewBB = NewLoc->getParent();
740 // Movement within the same loop does not break LCSSA (the equality check is
741 // to avoid doing a hashtable lookup in case of intra-block movement).
745 auto *OldLoop = getLoopFor(OldBB);
746 auto *NewLoop = getLoopFor(NewBB);
748 if (OldLoop == NewLoop)
751 // Check if Outer contains Inner; with the null loop counting as the
753 auto Contains = [](const Loop *Outer, const Loop *Inner) {
754 return !Outer || Outer->contains(Inner);
757 // To check that the movement of Inst to before NewLoc does not break LCSSA,
758 // we need to check two sets of uses for possible LCSSA violations at
759 // NewLoc: the users of NewInst, and the operands of NewInst.
761 // If we know we're hoisting Inst out of an inner loop to an outer loop,
762 // then the uses *of* Inst don't need to be checked.
764 if (!Contains(NewLoop, OldLoop)) {
765 for (Use &U : Inst->uses()) {
766 auto *UI = cast<Instruction>(U.getUser());
767 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
769 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
774 // If we know we're sinking Inst from an outer loop into an inner loop, then
775 // the *operands* of Inst don't need to be checked.
777 if (!Contains(OldLoop, NewLoop)) {
778 // See below on why we can't handle phi nodes here.
779 if (isa<PHINode>(Inst))
782 for (Use &U : Inst->operands()) {
783 auto *DefI = dyn_cast<Instruction>(U.get());
787 // This would need adjustment if we allow Inst to be a phi node -- the
788 // new use block won't simply be NewBB.
790 auto *DefBlock = DefI->getParent();
791 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
800 // Allow clients to walk the list of nested loops...
801 template <> struct GraphTraits<const Loop*> {
802 typedef const Loop *NodeRef;
803 typedef LoopInfo::iterator ChildIteratorType;
805 static NodeRef getEntryNode(const Loop *L) { return L; }
806 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
807 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
810 template <> struct GraphTraits<Loop*> {
811 typedef Loop *NodeRef;
812 typedef LoopInfo::iterator ChildIteratorType;
814 static NodeRef getEntryNode(Loop *L) { return L; }
815 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
816 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
819 /// \brief Analysis pass that exposes the \c LoopInfo for a function.
820 class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> {
821 friend AnalysisInfoMixin<LoopAnalysis>;
822 static AnalysisKey Key;
825 typedef LoopInfo Result;
827 LoopInfo run(Function &F, FunctionAnalysisManager &AM);
830 /// \brief Printer pass for the \c LoopAnalysis results.
831 class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> {
835 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
836 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
839 /// \brief Verifier pass for the \c LoopAnalysis results.
840 struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> {
841 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
844 /// \brief The legacy pass manager's analysis pass to compute loop information.
845 class LoopInfoWrapperPass : public FunctionPass {
849 static char ID; // Pass identification, replacement for typeid
851 LoopInfoWrapperPass() : FunctionPass(ID) {
852 initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
855 LoopInfo &getLoopInfo() { return LI; }
856 const LoopInfo &getLoopInfo() const { return LI; }
858 /// \brief Calculate the natural loop information for a given function.
859 bool runOnFunction(Function &F) override;
861 void verifyAnalysis() const override;
863 void releaseMemory() override { LI.releaseMemory(); }
865 void print(raw_ostream &O, const Module *M = nullptr) const override;
867 void getAnalysisUsage(AnalysisUsage &AU) const override;
870 /// Function to print a loop's contents as LLVM's text IR assembly.
871 void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner = "");
873 } // End llvm namespace