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