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