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