a2bd6574e615b585ab5a0a350d76e0df7752bf22
[oota-llvm.git] / include / llvm / Analysis / LoopInfo.h
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
30 #ifndef LLVM_ANALYSIS_LOOPINFO_H
31 #define LLVM_ANALYSIS_LOOPINFO_H
32
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/GraphTraits.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/Pass.h"
42 #include <algorithm>
43
44 namespace llvm {
45
46 // FIXME: Replace this brittle forward declaration with the include of the new
47 // PassManager.h when doing so doesn't break the PassManagerBuilder.
48 template <typename IRUnitT> class AnalysisManager;
49 class PreservedAnalyses;
50
51 class DominatorTree;
52 class LoopInfo;
53 class Loop;
54 class MDNode;
55 class PHINode;
56 class raw_ostream;
57 template<class N> class DominatorTreeBase;
58 template<class N, class M> class LoopInfoBase;
59 template<class N, class M> class LoopBase;
60
61 //===----------------------------------------------------------------------===//
62 /// LoopBase class - Instances of this class are used to represent loops that
63 /// are detected in the flow graph
64 ///
65 template<class BlockT, class LoopT>
66 class LoopBase {
67   LoopT *ParentLoop;
68   // SubLoops - Loops contained entirely within this one.
69   std::vector<LoopT *> SubLoops;
70
71   // Blocks - The list of blocks in this loop.  First entry is the header node.
72   std::vector<BlockT*> Blocks;
73
74   SmallPtrSet<const BlockT*, 8> DenseBlockSet;
75
76   /// Indicator that this loop is no longer a valid loop.
77   bool IsInvalid = false;
78
79   LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
80   const LoopBase<BlockT, LoopT>&
81     operator=(const LoopBase<BlockT, LoopT> &) = delete;
82 public:
83   /// Loop ctor - This creates an empty loop.
84   LoopBase() : ParentLoop(nullptr) {}
85   ~LoopBase() {
86     for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
87       delete SubLoops[i];
88   }
89
90   /// getLoopDepth - Return the nesting level of this loop.  An outer-most
91   /// loop has depth 1, for consistency with loop depth values used for basic
92   /// blocks, where depth 0 is used for blocks not inside any loops.
93   unsigned getLoopDepth() const {
94     unsigned D = 1;
95     for (const LoopT *CurLoop = ParentLoop; CurLoop;
96          CurLoop = CurLoop->ParentLoop)
97       ++D;
98     return D;
99   }
100   BlockT *getHeader() const { return Blocks.front(); }
101   LoopT *getParentLoop() const { return ParentLoop; }
102
103   /// setParentLoop is a raw interface for bypassing addChildLoop.
104   void setParentLoop(LoopT *L) { ParentLoop = L; }
105
106   /// contains - Return true if the specified loop is contained within in
107   /// this loop.
108   ///
109   bool contains(const LoopT *L) const {
110     if (L == this) return true;
111     if (!L)        return false;
112     return contains(L->getParentLoop());
113   }
114
115   /// contains - Return true if the specified basic block is in this loop.
116   ///
117   bool contains(const BlockT *BB) const {
118     return DenseBlockSet.count(BB);
119   }
120
121   /// contains - Return true if the specified instruction is in this loop.
122   ///
123   template<class InstT>
124   bool contains(const InstT *Inst) const {
125     return contains(Inst->getParent());
126   }
127
128   /// iterator/begin/end - Return the loops contained entirely within this loop.
129   ///
130   const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
131   std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
132   typedef typename std::vector<LoopT *>::const_iterator iterator;
133   typedef typename std::vector<LoopT *>::const_reverse_iterator
134     reverse_iterator;
135   iterator begin() const { return SubLoops.begin(); }
136   iterator end() const { return SubLoops.end(); }
137   reverse_iterator rbegin() const { return SubLoops.rbegin(); }
138   reverse_iterator rend() const { return SubLoops.rend(); }
139   bool empty() const { return SubLoops.empty(); }
140
141   /// getBlocks - Get a list of the basic blocks which make up this loop.
142   ///
143   const std::vector<BlockT*> &getBlocks() const { return Blocks; }
144   typedef typename std::vector<BlockT*>::const_iterator block_iterator;
145   block_iterator block_begin() const { return Blocks.begin(); }
146   block_iterator block_end() const { return Blocks.end(); }
147   inline iterator_range<block_iterator> blocks() const {
148     return make_range(block_begin(), block_end());
149   }
150
151   /// getNumBlocks - Get the number of blocks in this loop in constant time.
152   unsigned getNumBlocks() const {
153     return Blocks.size();
154   }
155
156   /// Invalidate the loop, indicating that it is no longer a loop.
157   void invalidate() { IsInvalid = true; }
158
159   /// Return true if this loop is no longer valid.
160   bool isInvalid() { return IsInvalid; }
161
162   /// isLoopExiting - True if terminator in the block can branch to another
163   /// block that is outside of the current loop.
164   ///
165   bool isLoopExiting(const BlockT *BB) const {
166     typedef GraphTraits<const BlockT*> BlockTraits;
167     for (typename BlockTraits::ChildIteratorType SI =
168          BlockTraits::child_begin(BB),
169          SE = BlockTraits::child_end(BB); SI != SE; ++SI) {
170       if (!contains(*SI))
171         return true;
172     }
173     return false;
174   }
175
176   /// getNumBackEdges - Calculate the number of back edges to the loop header
177   ///
178   unsigned getNumBackEdges() const {
179     unsigned NumBackEdges = 0;
180     BlockT *H = getHeader();
181
182     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
183     for (typename InvBlockTraits::ChildIteratorType I =
184          InvBlockTraits::child_begin(H),
185          E = InvBlockTraits::child_end(H); I != E; ++I)
186       if (contains(*I))
187         ++NumBackEdges;
188
189     return NumBackEdges;
190   }
191
192   //===--------------------------------------------------------------------===//
193   // APIs for simple analysis of the loop.
194   //
195   // Note that all of these methods can fail on general loops (ie, there may not
196   // be a preheader, etc).  For best success, the loop simplification and
197   // induction variable canonicalization pass should be used to normalize loops
198   // for easy analysis.  These methods assume canonical loops.
199
200   /// getExitingBlocks - Return all blocks inside the loop that have successors
201   /// outside of the loop.  These are the blocks _inside of the current loop_
202   /// which branch out.  The returned list is always unique.
203   ///
204   void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
205
206   /// getExitingBlock - If getExitingBlocks would return exactly one block,
207   /// return that block. Otherwise return null.
208   BlockT *getExitingBlock() const;
209
210   /// getExitBlocks - Return all of the successor blocks of this loop.  These
211   /// are the blocks _outside of the current loop_ which are branched to.
212   ///
213   void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
214
215   /// getExitBlock - If getExitBlocks would return exactly one block,
216   /// return that block. Otherwise return null.
217   BlockT *getExitBlock() const;
218
219   /// Edge type.
220   typedef std::pair<const BlockT*, const BlockT*> Edge;
221
222   /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
223   void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
224
225   /// getLoopPreheader - If there is a preheader for this loop, return it.  A
226   /// loop has a preheader if there is only one edge to the header of the loop
227   /// from outside of the loop.  If this is the case, the block branching to the
228   /// header of the loop is the preheader node.
229   ///
230   /// This method returns null if there is no preheader for the loop.
231   ///
232   BlockT *getLoopPreheader() const;
233
234   /// getLoopPredecessor - If the given loop's header has exactly one unique
235   /// predecessor outside the loop, return it. Otherwise return null.
236   /// This is less strict that the loop "preheader" concept, which requires
237   /// the predecessor to have exactly one successor.
238   ///
239   BlockT *getLoopPredecessor() const;
240
241   /// getLoopLatch - If there is a single latch block for this loop, return it.
242   /// A latch block is a block that contains a branch back to the header.
243   BlockT *getLoopLatch() const;
244
245   /// getLoopLatches - Return all loop latch blocks of this loop. A latch block
246   /// is a block that contains a branch back to the header.
247   void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
248     BlockT *H = getHeader();
249     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
250     for (typename InvBlockTraits::ChildIteratorType I =
251          InvBlockTraits::child_begin(H),
252          E = InvBlockTraits::child_end(H); I != E; ++I)
253       if (contains(*I))
254         LoopLatches.push_back(*I);
255   }
256
257   //===--------------------------------------------------------------------===//
258   // APIs for updating loop information after changing the CFG
259   //
260
261   /// addBasicBlockToLoop - This method is used by other analyses to update loop
262   /// information.  NewBB is set to be a new member of the current loop.
263   /// Because of this, it is added as a member of all parent loops, and is added
264   /// to the specified LoopInfo object as being in the current basic block.  It
265   /// is not valid to replace the loop header with this method.
266   ///
267   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
268
269   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
270   /// the OldChild entry in our children list with NewChild, and updates the
271   /// parent pointer of OldChild to be null and the NewChild to be this loop.
272   /// This updates the loop depth of the new child.
273   void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
274
275   /// addChildLoop - Add the specified loop to be a child of this loop.  This
276   /// updates the loop depth of the new child.
277   ///
278   void addChildLoop(LoopT *NewChild) {
279     assert(!NewChild->ParentLoop && "NewChild already has a parent!");
280     NewChild->ParentLoop = static_cast<LoopT *>(this);
281     SubLoops.push_back(NewChild);
282   }
283
284   /// removeChildLoop - This removes the specified child from being a subloop of
285   /// this loop.  The loop is not deleted, as it will presumably be inserted
286   /// into another loop.
287   LoopT *removeChildLoop(iterator I) {
288     assert(I != SubLoops.end() && "Cannot remove end iterator!");
289     LoopT *Child = *I;
290     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
291     SubLoops.erase(SubLoops.begin()+(I-begin()));
292     Child->ParentLoop = nullptr;
293     return Child;
294   }
295
296   /// addBlockEntry - This adds a basic block directly to the basic block list.
297   /// This should only be used by transformations that create new loops.  Other
298   /// transformations should use addBasicBlockToLoop.
299   void addBlockEntry(BlockT *BB) {
300     Blocks.push_back(BB);
301     DenseBlockSet.insert(BB);
302   }
303
304   /// reverseBlocks - interface to reverse Blocks[from, end of loop] in this loop
305   void reverseBlock(unsigned from) {
306     std::reverse(Blocks.begin() + from, Blocks.end());
307   }
308
309   /// reserveBlocks- interface to do reserve() for Blocks
310   void reserveBlocks(unsigned size) {
311     Blocks.reserve(size);
312   }
313
314   /// moveToHeader - This method is used to move BB (which must be part of this
315   /// loop) to be the loop header of the loop (the block that dominates all
316   /// others).
317   void moveToHeader(BlockT *BB) {
318     if (Blocks[0] == BB) return;
319     for (unsigned i = 0; ; ++i) {
320       assert(i != Blocks.size() && "Loop does not contain BB!");
321       if (Blocks[i] == BB) {
322         Blocks[i] = Blocks[0];
323         Blocks[0] = BB;
324         return;
325       }
326     }
327   }
328
329   /// removeBlockFromLoop - This removes the specified basic block from the
330   /// current loop, updating the Blocks as appropriate.  This does not update
331   /// the mapping in the LoopInfo class.
332   void removeBlockFromLoop(BlockT *BB) {
333     auto I = std::find(Blocks.begin(), Blocks.end(), BB);
334     assert(I != Blocks.end() && "N is not in this list!");
335     Blocks.erase(I);
336
337     DenseBlockSet.erase(BB);
338   }
339
340   /// verifyLoop - Verify loop structure
341   void verifyLoop() const;
342
343   /// verifyLoop - Verify loop structure of this loop and all nested loops.
344   void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
345
346   void print(raw_ostream &OS, unsigned Depth = 0) const;
347
348 protected:
349   friend class LoopInfoBase<BlockT, LoopT>;
350   explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
351     Blocks.push_back(BB);
352     DenseBlockSet.insert(BB);
353   }
354 };
355
356 template<class BlockT, class LoopT>
357 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
358   Loop.print(OS);
359   return OS;
360 }
361
362 // Implementation in LoopInfoImpl.h
363 extern template class LoopBase<BasicBlock, Loop>;
364
365 class Loop : public LoopBase<BasicBlock, Loop> {
366 public:
367   Loop() {}
368
369   /// isLoopInvariant - Return true if the specified value is loop invariant
370   ///
371   bool isLoopInvariant(const Value *V) const;
372
373   /// hasLoopInvariantOperands - Return true if all the operands of the
374   /// specified instruction are loop invariant.
375   bool hasLoopInvariantOperands(const Instruction *I) const;
376
377   /// makeLoopInvariant - If the given value is an instruction inside of the
378   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
379   /// Return true if the value after any hoisting is loop invariant. This
380   /// function can be used as a slightly more aggressive replacement for
381   /// isLoopInvariant.
382   ///
383   /// If InsertPt is specified, it is the point to hoist instructions to.
384   /// If null, the terminator of the loop preheader is used.
385   ///
386   bool makeLoopInvariant(Value *V, bool &Changed,
387                          Instruction *InsertPt = nullptr) const;
388
389   /// makeLoopInvariant - If the given instruction is inside of the
390   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
391   /// Return true if the instruction after any hoisting is loop invariant. This
392   /// function can be used as a slightly more aggressive replacement for
393   /// isLoopInvariant.
394   ///
395   /// If InsertPt is specified, it is the point to hoist instructions to.
396   /// If null, the terminator of the loop preheader is used.
397   ///
398   bool makeLoopInvariant(Instruction *I, bool &Changed,
399                          Instruction *InsertPt = nullptr) const;
400
401   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
402   /// induction variable: an integer recurrence that starts at 0 and increments
403   /// by one each time through the loop.  If so, return the phi node that
404   /// corresponds to it.
405   ///
406   /// The IndVarSimplify pass transforms loops to have a canonical induction
407   /// variable.
408   ///
409   PHINode *getCanonicalInductionVariable() const;
410
411   /// isLCSSAForm - Return true if the Loop is in LCSSA form
412   bool isLCSSAForm(DominatorTree &DT) const;
413
414   /// \brief Return true if this Loop and all inner subloops are in LCSSA form.
415   bool isRecursivelyLCSSAForm(DominatorTree &DT) const;
416
417   /// isLoopSimplifyForm - Return true if the Loop is in the form that
418   /// the LoopSimplify form transforms loops to, which is sometimes called
419   /// normal form.
420   bool isLoopSimplifyForm() const;
421
422   /// isSafeToClone - Return true if the loop body is safe to clone in practice.
423   bool isSafeToClone() const;
424
425   /// Returns true if the loop is annotated parallel.
426   ///
427   /// A parallel loop can be assumed to not contain any dependencies between
428   /// iterations by the compiler. That is, any loop-carried dependency checking
429   /// can be skipped completely when parallelizing the loop on the target
430   /// machine. Thus, if the parallel loop information originates from the
431   /// programmer, e.g. via the OpenMP parallel for pragma, it is the
432   /// programmer's responsibility to ensure there are no loop-carried
433   /// dependencies. The final execution order of the instructions across
434   /// iterations is not guaranteed, thus, the end result might or might not
435   /// implement actual concurrent execution of instructions across multiple
436   /// iterations.
437   bool isAnnotatedParallel() const;
438
439   /// Return the llvm.loop loop id metadata node for this loop if it is present.
440   ///
441   /// If this loop contains the same llvm.loop metadata on each branch to the
442   /// header then the node is returned. If any latch instruction does not
443   /// contain llvm.loop or or if multiple latches contain different nodes then
444   /// 0 is returned.
445   MDNode *getLoopID() const;
446   /// Set the llvm.loop loop id metadata for this loop.
447   ///
448   /// The LoopID metadata node will be added to each terminator instruction in
449   /// the loop that branches to the loop header.
450   ///
451   /// The LoopID metadata node should have one or more operands and the first
452   /// operand should should be the node itself.
453   void setLoopID(MDNode *LoopID) const;
454
455   /// hasDedicatedExits - Return true if no exit block for the loop
456   /// has a predecessor that is outside the loop.
457   bool hasDedicatedExits() const;
458
459   /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
460   /// These are the blocks _outside of the current loop_ which are branched to.
461   /// This assumes that loop exits are in canonical form.
462   ///
463   void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
464
465   /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
466   /// block, return that block. Otherwise return null.
467   BasicBlock *getUniqueExitBlock() const;
468
469   void dump() const;
470
471   /// \brief Return the debug location of the start of this loop.
472   /// This looks for a BB terminating instruction with a known debug
473   /// location by looking at the preheader and header blocks. If it
474   /// cannot find a terminating instruction with location information,
475   /// it returns an unknown location.
476   DebugLoc getStartLoc() const {
477     BasicBlock *HeadBB;
478
479     // Try the pre-header first.
480     if ((HeadBB = getLoopPreheader()) != nullptr)
481       if (DebugLoc DL = HeadBB->getTerminator()->getDebugLoc())
482         return DL;
483
484     // If we have no pre-header or there are no instructions with debug
485     // info in it, try the header.
486     HeadBB = getHeader();
487     if (HeadBB)
488       return HeadBB->getTerminator()->getDebugLoc();
489
490     return DebugLoc();
491   }
492
493 private:
494   friend class LoopInfoBase<BasicBlock, Loop>;
495   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
496 };
497
498 //===----------------------------------------------------------------------===//
499 /// LoopInfo - This class builds and contains all of the top level loop
500 /// structures in the specified function.
501 ///
502
503 template<class BlockT, class LoopT>
504 class LoopInfoBase {
505   // BBMap - Mapping of basic blocks to the inner most loop they occur in
506   DenseMap<const BlockT *, LoopT *> BBMap;
507   std::vector<LoopT *> TopLevelLoops;
508   std::vector<LoopT *> RemovedLoops;
509
510   friend class LoopBase<BlockT, LoopT>;
511   friend class LoopInfo;
512
513   void operator=(const LoopInfoBase &) = delete;
514   LoopInfoBase(const LoopInfoBase &) = delete;
515 public:
516   LoopInfoBase() { }
517   ~LoopInfoBase() { releaseMemory(); }
518
519   LoopInfoBase(LoopInfoBase &&Arg)
520       : BBMap(std::move(Arg.BBMap)),
521         TopLevelLoops(std::move(Arg.TopLevelLoops)) {
522     // We have to clear the arguments top level loops as we've taken ownership.
523     Arg.TopLevelLoops.clear();
524   }
525   LoopInfoBase &operator=(LoopInfoBase &&RHS) {
526     BBMap = std::move(RHS.BBMap);
527
528     for (auto *L : TopLevelLoops)
529       delete L;
530     TopLevelLoops = std::move(RHS.TopLevelLoops);
531     RHS.TopLevelLoops.clear();
532     return *this;
533   }
534
535   void releaseMemory() {
536     BBMap.clear();
537
538     for (auto *L : TopLevelLoops)
539       delete L;
540     TopLevelLoops.clear();
541     for (auto *L : RemovedLoops)
542       delete L;
543     RemovedLoops.clear();
544   }
545
546   /// iterator/begin/end - The interface to the top-level loops in the current
547   /// function.
548   ///
549   typedef typename std::vector<LoopT *>::const_iterator iterator;
550   typedef typename std::vector<LoopT *>::const_reverse_iterator
551     reverse_iterator;
552   iterator begin() const { return TopLevelLoops.begin(); }
553   iterator end() const { return TopLevelLoops.end(); }
554   reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
555   reverse_iterator rend() const { return TopLevelLoops.rend(); }
556   bool empty() const { return TopLevelLoops.empty(); }
557
558   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
559   /// block is in no loop (for example the entry node), null is returned.
560   ///
561   LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
562
563   /// operator[] - same as getLoopFor...
564   ///
565   const LoopT *operator[](const BlockT *BB) const {
566     return getLoopFor(BB);
567   }
568
569   /// getLoopDepth - Return the loop nesting level of the specified block.  A
570   /// depth of 0 means the block is not inside any loop.
571   ///
572   unsigned getLoopDepth(const BlockT *BB) const {
573     const LoopT *L = getLoopFor(BB);
574     return L ? L->getLoopDepth() : 0;
575   }
576
577   // isLoopHeader - True if the block is a loop header node
578   bool isLoopHeader(const BlockT *BB) const {
579     const LoopT *L = getLoopFor(BB);
580     return L && L->getHeader() == BB;
581   }
582
583   /// removeLoop - This removes the specified top-level loop from this loop info
584   /// object.  The loop is not deleted, as it will presumably be inserted into
585   /// another loop.
586   LoopT *removeLoop(iterator I) {
587     assert(I != end() && "Cannot remove end iterator!");
588     LoopT *L = *I;
589     assert(!L->getParentLoop() && "Not a top-level loop!");
590     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
591     return L;
592   }
593
594   /// changeLoopFor - Change the top-level loop that contains BB to the
595   /// specified loop.  This should be used by transformations that restructure
596   /// the loop hierarchy tree.
597   void changeLoopFor(BlockT *BB, LoopT *L) {
598     if (!L) {
599       BBMap.erase(BB);
600       return;
601     }
602     BBMap[BB] = L;
603   }
604
605   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
606   /// list with the indicated loop.
607   void changeTopLevelLoop(LoopT *OldLoop,
608                           LoopT *NewLoop) {
609     auto I = std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
610     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
611     *I = NewLoop;
612     assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
613            "Loops already embedded into a subloop!");
614   }
615
616   /// addTopLevelLoop - This adds the specified loop to the collection of
617   /// top-level loops.
618   void addTopLevelLoop(LoopT *New) {
619     assert(!New->getParentLoop() && "Loop already in subloop!");
620     TopLevelLoops.push_back(New);
621   }
622
623   /// removeBlock - This method completely removes BB from all data structures,
624   /// including all of the Loop objects it is nested in and our mapping from
625   /// BasicBlocks to loops.
626   void removeBlock(BlockT *BB) {
627     auto I = BBMap.find(BB);
628     if (I != BBMap.end()) {
629       for (LoopT *L = I->second; L; L = L->getParentLoop())
630         L->removeBlockFromLoop(BB);
631
632       BBMap.erase(I);
633     }
634   }
635
636   // Internals
637
638   static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
639                                       const LoopT *ParentLoop) {
640     if (!SubLoop) return true;
641     if (SubLoop == ParentLoop) return false;
642     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
643   }
644
645   /// Create the loop forest using a stable algorithm.
646   void analyze(const DominatorTreeBase<BlockT> &DomTree);
647
648   // Debugging
649   void print(raw_ostream &OS) const;
650
651   void verify() const;
652 };
653
654 // Implementation in LoopInfoImpl.h
655 extern template class LoopInfoBase<BasicBlock, Loop>;
656
657 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
658   typedef LoopInfoBase<BasicBlock, Loop> BaseT;
659
660   friend class LoopBase<BasicBlock, Loop>;
661
662   void operator=(const LoopInfo &) = delete;
663   LoopInfo(const LoopInfo &) = delete;
664 public:
665   LoopInfo() {}
666   explicit LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree);
667
668   LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
669   LoopInfo &operator=(LoopInfo &&RHS) {
670     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
671     return *this;
672   }
673
674   // Most of the public interface is provided via LoopInfoBase.
675
676   /// Update LoopInfo after removing the last backedge from a loop. This updates
677   /// the loop forest and parent loops for each block so that \c L is no longer
678   /// referenced, but does not actually delete \c L immediately. The pointer
679   /// will remain valid until this LoopInfo's memory is released.
680   void markAsRemoved(Loop *L);
681
682   /// replacementPreservesLCSSAForm - Returns true if replacing From with To
683   /// everywhere is guaranteed to preserve LCSSA form.
684   bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
685     // Preserving LCSSA form is only problematic if the replacing value is an
686     // instruction.
687     Instruction *I = dyn_cast<Instruction>(To);
688     if (!I) return true;
689     // If both instructions are defined in the same basic block then replacement
690     // cannot break LCSSA form.
691     if (I->getParent() == From->getParent())
692       return true;
693     // If the instruction is not defined in a loop then it can safely replace
694     // anything.
695     Loop *ToLoop = getLoopFor(I->getParent());
696     if (!ToLoop) return true;
697     // If the replacing instruction is defined in the same loop as the original
698     // instruction, or in a loop that contains it as an inner loop, then using
699     // it as a replacement will not break LCSSA form.
700     return ToLoop->contains(getLoopFor(From->getParent()));
701   }
702
703   /// \brief Checks if moving a specific instruction can break LCSSA in any
704   /// loop.
705   ///
706   /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
707   /// assuming that the function containing \p Inst and \p NewLoc is currently
708   /// in LCSSA form.
709   bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
710     assert(Inst->getFunction() == NewLoc->getFunction() &&
711            "Can't reason about IPO!");
712
713     auto *OldBB = Inst->getParent();
714     auto *NewBB = NewLoc->getParent();
715
716     // Movement within the same loop does not break LCSSA (the equality check is
717     // to avoid doing a hashtable lookup in case of intra-block movement).
718     if (OldBB == NewBB)
719       return true;
720
721     auto *OldLoop = getLoopFor(OldBB);
722     auto *NewLoop = getLoopFor(NewBB);
723
724     if (OldLoop == NewLoop)
725       return true;
726
727     // Check if Outer contains Inner; with the null loop counting as the
728     // "outermost" loop.
729     auto Contains = [](const Loop *Outer, const Loop *Inner) {
730       return !Outer || Outer->contains(Inner);
731     };
732
733     // To check that the movement of Inst to before NewLoc does not break LCSSA,
734     // we need to check two sets of uses for possible LCSSA violations at
735     // NewLoc: the users of NewInst, and the operands of NewInst.
736
737     // If we know we're hoisting Inst out of an inner loop to an outer loop,
738     // then the uses *of* Inst don't need to be checked.
739
740     if (!Contains(NewLoop, OldLoop)) {
741       for (Use &U : Inst->uses()) {
742         auto *UI = cast<Instruction>(U.getUser());
743         auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
744                                      : UI->getParent();
745         if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
746           return false;
747       }
748     }
749
750     // If we know we're sinking Inst from an outer loop into an inner loop, then
751     // the *operands* of Inst don't need to be checked.
752
753     if (!Contains(OldLoop, NewLoop)) {
754       // See below on why we can't handle phi nodes here.
755       if (isa<PHINode>(Inst))
756         return false;
757
758       for (Use &U : Inst->operands()) {
759         auto *DefI = dyn_cast<Instruction>(U.get());
760         if (!DefI)
761           return false;
762
763         // This would need adjustment if we allow Inst to be a phi node -- the
764         // new use block won't simply be NewBB.
765
766         auto *DefBlock = DefI->getParent();
767         if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
768           return false;
769       }
770     }
771
772     return true;
773   }
774 };
775
776 // Allow clients to walk the list of nested loops...
777 template <> struct GraphTraits<const Loop*> {
778   typedef const Loop NodeType;
779   typedef LoopInfo::iterator ChildIteratorType;
780
781   static NodeType *getEntryNode(const Loop *L) { return L; }
782   static inline ChildIteratorType child_begin(NodeType *N) {
783     return N->begin();
784   }
785   static inline ChildIteratorType child_end(NodeType *N) {
786     return N->end();
787   }
788 };
789
790 template <> struct GraphTraits<Loop*> {
791   typedef Loop NodeType;
792   typedef LoopInfo::iterator ChildIteratorType;
793
794   static NodeType *getEntryNode(Loop *L) { return L; }
795   static inline ChildIteratorType child_begin(NodeType *N) {
796     return N->begin();
797   }
798   static inline ChildIteratorType child_end(NodeType *N) {
799     return N->end();
800   }
801 };
802
803 /// \brief Analysis pass that exposes the \c LoopInfo for a function.
804 class LoopAnalysis {
805   static char PassID;
806
807 public:
808   typedef LoopInfo Result;
809
810   /// \brief Opaque, unique identifier for this analysis pass.
811   static void *ID() { return (void *)&PassID; }
812
813   /// \brief Provide a name for the analysis for debugging and logging.
814   static StringRef name() { return "LoopAnalysis"; }
815
816   LoopInfo run(Function &F, AnalysisManager<Function> *AM);
817 };
818
819 /// \brief Printer pass for the \c LoopAnalysis results.
820 class LoopPrinterPass {
821   raw_ostream &OS;
822
823 public:
824   explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
825   PreservedAnalyses run(Function &F, AnalysisManager<Function> *AM);
826
827   static StringRef name() { return "LoopPrinterPass"; }
828 };
829
830 /// \brief The legacy pass manager's analysis pass to compute loop information.
831 class LoopInfoWrapperPass : public FunctionPass {
832   LoopInfo LI;
833
834 public:
835   static char ID; // Pass identification, replacement for typeid
836
837   LoopInfoWrapperPass() : FunctionPass(ID) {
838     initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
839   }
840
841   LoopInfo &getLoopInfo() { return LI; }
842   const LoopInfo &getLoopInfo() const { return LI; }
843
844   /// \brief Calculate the natural loop information for a given function.
845   bool runOnFunction(Function &F) override;
846
847   void verifyAnalysis() const override;
848
849   void releaseMemory() override { LI.releaseMemory(); }
850
851   void print(raw_ostream &O, const Module *M = nullptr) const override;
852
853   void getAnalysisUsage(AnalysisUsage &AU) const override;
854 };
855
856 /// \brief Pass for printing a loop's contents as LLVM's text IR assembly.
857 class PrintLoopPass {
858   raw_ostream &OS;
859   std::string Banner;
860
861 public:
862   PrintLoopPass();
863   PrintLoopPass(raw_ostream &OS, const std::string &Banner = "");
864
865   PreservedAnalyses run(Loop &L);
866   static StringRef name() { return "PrintLoopPass"; }
867 };
868
869 } // End llvm namespace
870
871 #endif