57695b46d6400ba281bd30c4b9c7e14b192eb0c8
[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   /// \brief Return true if this Loop and all inner subloops are in LCSSA form.
406   bool isRecursivelyLCSSAForm(DominatorTree &DT) const;
407
408   /// isLoopSimplifyForm - Return true if the Loop is in the form that
409   /// the LoopSimplify form transforms loops to, which is sometimes called
410   /// normal form.
411   bool isLoopSimplifyForm() const;
412
413   /// isSafeToClone - Return true if the loop body is safe to clone in practice.
414   bool isSafeToClone() const;
415
416   /// Returns true if the loop is annotated parallel.
417   ///
418   /// A parallel loop can be assumed to not contain any dependencies between
419   /// iterations by the compiler. That is, any loop-carried dependency checking
420   /// can be skipped completely when parallelizing the loop on the target
421   /// machine. Thus, if the parallel loop information originates from the
422   /// programmer, e.g. via the OpenMP parallel for pragma, it is the
423   /// programmer's responsibility to ensure there are no loop-carried
424   /// dependencies. The final execution order of the instructions across
425   /// iterations is not guaranteed, thus, the end result might or might not
426   /// implement actual concurrent execution of instructions across multiple
427   /// iterations.
428   bool isAnnotatedParallel() const;
429
430   /// Return the llvm.loop loop id metadata node for this loop if it is present.
431   ///
432   /// If this loop contains the same llvm.loop metadata on each branch to the
433   /// header then the node is returned. If any latch instruction does not
434   /// contain llvm.loop or or if multiple latches contain different nodes then
435   /// 0 is returned.
436   MDNode *getLoopID() const;
437   /// Set the llvm.loop loop id metadata for this loop.
438   ///
439   /// The LoopID metadata node will be added to each terminator instruction in
440   /// the loop that branches to the loop header.
441   ///
442   /// The LoopID metadata node should have one or more operands and the first
443   /// operand should should be the node itself.
444   void setLoopID(MDNode *LoopID) const;
445
446   /// hasDedicatedExits - Return true if no exit block for the loop
447   /// has a predecessor that is outside the loop.
448   bool hasDedicatedExits() const;
449
450   /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
451   /// These are the blocks _outside of the current loop_ which are branched to.
452   /// This assumes that loop exits are in canonical form.
453   ///
454   void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
455
456   /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
457   /// block, return that block. Otherwise return null.
458   BasicBlock *getUniqueExitBlock() const;
459
460   void dump() const;
461
462   /// \brief Return the debug location of the start of this loop.
463   /// This looks for a BB terminating instruction with a known debug
464   /// location by looking at the preheader and header blocks. If it
465   /// cannot find a terminating instruction with location information,
466   /// it returns an unknown location.
467   DebugLoc getStartLoc() const {
468     BasicBlock *HeadBB;
469
470     // Try the pre-header first.
471     if ((HeadBB = getLoopPreheader()) != nullptr)
472       if (DebugLoc DL = HeadBB->getTerminator()->getDebugLoc())
473         return DL;
474
475     // If we have no pre-header or there are no instructions with debug
476     // info in it, try the header.
477     HeadBB = getHeader();
478     if (HeadBB)
479       return HeadBB->getTerminator()->getDebugLoc();
480
481     return DebugLoc();
482   }
483
484 private:
485   friend class LoopInfoBase<BasicBlock, Loop>;
486   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
487 };
488
489 //===----------------------------------------------------------------------===//
490 /// LoopInfo - This class builds and contains all of the top level loop
491 /// structures in the specified function.
492 ///
493
494 template<class BlockT, class LoopT>
495 class LoopInfoBase {
496   // BBMap - Mapping of basic blocks to the inner most loop they occur in
497   DenseMap<const BlockT *, LoopT *> BBMap;
498   std::vector<LoopT *> TopLevelLoops;
499   friend class LoopBase<BlockT, LoopT>;
500   friend class LoopInfo;
501
502   void operator=(const LoopInfoBase &) = delete;
503   LoopInfoBase(const LoopInfoBase &) = delete;
504 public:
505   LoopInfoBase() { }
506   ~LoopInfoBase() { releaseMemory(); }
507
508   LoopInfoBase(LoopInfoBase &&Arg)
509       : BBMap(std::move(Arg.BBMap)),
510         TopLevelLoops(std::move(Arg.TopLevelLoops)) {
511     // We have to clear the arguments top level loops as we've taken ownership.
512     Arg.TopLevelLoops.clear();
513   }
514   LoopInfoBase &operator=(LoopInfoBase &&RHS) {
515     BBMap = std::move(RHS.BBMap);
516
517     for (auto *L : TopLevelLoops)
518       delete L;
519     TopLevelLoops = std::move(RHS.TopLevelLoops);
520     RHS.TopLevelLoops.clear();
521     return *this;
522   }
523
524   void releaseMemory() {
525     BBMap.clear();
526
527     for (auto *L : TopLevelLoops)
528       delete L;
529     TopLevelLoops.clear();
530   }
531
532   /// iterator/begin/end - The interface to the top-level loops in the current
533   /// function.
534   ///
535   typedef typename std::vector<LoopT *>::const_iterator iterator;
536   typedef typename std::vector<LoopT *>::const_reverse_iterator
537     reverse_iterator;
538   iterator begin() const { return TopLevelLoops.begin(); }
539   iterator end() const { return TopLevelLoops.end(); }
540   reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
541   reverse_iterator rend() const { return TopLevelLoops.rend(); }
542   bool empty() const { return TopLevelLoops.empty(); }
543
544   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
545   /// block is in no loop (for example the entry node), null is returned.
546   ///
547   LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
548
549   /// operator[] - same as getLoopFor...
550   ///
551   const LoopT *operator[](const BlockT *BB) const {
552     return getLoopFor(BB);
553   }
554
555   /// getLoopDepth - Return the loop nesting level of the specified block.  A
556   /// depth of 0 means the block is not inside any loop.
557   ///
558   unsigned getLoopDepth(const BlockT *BB) const {
559     const LoopT *L = getLoopFor(BB);
560     return L ? L->getLoopDepth() : 0;
561   }
562
563   // isLoopHeader - True if the block is a loop header node
564   bool isLoopHeader(const BlockT *BB) const {
565     const LoopT *L = getLoopFor(BB);
566     return L && L->getHeader() == BB;
567   }
568
569   /// removeLoop - This removes the specified top-level loop from this loop info
570   /// object.  The loop is not deleted, as it will presumably be inserted into
571   /// another loop.
572   LoopT *removeLoop(iterator I) {
573     assert(I != end() && "Cannot remove end iterator!");
574     LoopT *L = *I;
575     assert(!L->getParentLoop() && "Not a top-level loop!");
576     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
577     return L;
578   }
579
580   /// changeLoopFor - Change the top-level loop that contains BB to the
581   /// specified loop.  This should be used by transformations that restructure
582   /// the loop hierarchy tree.
583   void changeLoopFor(BlockT *BB, LoopT *L) {
584     if (!L) {
585       BBMap.erase(BB);
586       return;
587     }
588     BBMap[BB] = L;
589   }
590
591   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
592   /// list with the indicated loop.
593   void changeTopLevelLoop(LoopT *OldLoop,
594                           LoopT *NewLoop) {
595     auto I = std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
596     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
597     *I = NewLoop;
598     assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
599            "Loops already embedded into a subloop!");
600   }
601
602   /// addTopLevelLoop - This adds the specified loop to the collection of
603   /// top-level loops.
604   void addTopLevelLoop(LoopT *New) {
605     assert(!New->getParentLoop() && "Loop already in subloop!");
606     TopLevelLoops.push_back(New);
607   }
608
609   /// removeBlock - This method completely removes BB from all data structures,
610   /// including all of the Loop objects it is nested in and our mapping from
611   /// BasicBlocks to loops.
612   void removeBlock(BlockT *BB) {
613     auto I = BBMap.find(BB);
614     if (I != BBMap.end()) {
615       for (LoopT *L = I->second; L; L = L->getParentLoop())
616         L->removeBlockFromLoop(BB);
617
618       BBMap.erase(I);
619     }
620   }
621
622   // Internals
623
624   static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
625                                       const LoopT *ParentLoop) {
626     if (!SubLoop) return true;
627     if (SubLoop == ParentLoop) return false;
628     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
629   }
630
631   /// Create the loop forest using a stable algorithm.
632   void analyze(const DominatorTreeBase<BlockT> &DomTree);
633
634   // Debugging
635   void print(raw_ostream &OS) const;
636
637   void verify() const;
638 };
639
640 // Implementation in LoopInfoImpl.h
641 extern template class LoopInfoBase<BasicBlock, Loop>;
642
643 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
644   typedef LoopInfoBase<BasicBlock, Loop> BaseT;
645
646   friend class LoopBase<BasicBlock, Loop>;
647
648   void operator=(const LoopInfo &) = delete;
649   LoopInfo(const LoopInfo &) = delete;
650 public:
651   LoopInfo() {}
652   explicit LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree);
653
654   LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
655   LoopInfo &operator=(LoopInfo &&RHS) {
656     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
657     return *this;
658   }
659
660   // Most of the public interface is provided via LoopInfoBase.
661
662   /// updateUnloop - Update LoopInfo after removing the last backedge from a
663   /// loop--now the "unloop". This updates the loop forest and parent loops for
664   /// each block so that Unloop is no longer referenced, but the caller must
665   /// actually delete the Unloop object.
666   void updateUnloop(Loop *Unloop);
667
668   /// replacementPreservesLCSSAForm - Returns true if replacing From with To
669   /// everywhere is guaranteed to preserve LCSSA form.
670   bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
671     // Preserving LCSSA form is only problematic if the replacing value is an
672     // instruction.
673     Instruction *I = dyn_cast<Instruction>(To);
674     if (!I) return true;
675     // If both instructions are defined in the same basic block then replacement
676     // cannot break LCSSA form.
677     if (I->getParent() == From->getParent())
678       return true;
679     // If the instruction is not defined in a loop then it can safely replace
680     // anything.
681     Loop *ToLoop = getLoopFor(I->getParent());
682     if (!ToLoop) return true;
683     // If the replacing instruction is defined in the same loop as the original
684     // instruction, or in a loop that contains it as an inner loop, then using
685     // it as a replacement will not break LCSSA form.
686     return ToLoop->contains(getLoopFor(From->getParent()));
687   }
688
689   /// \brief Checks if moving a specific instruction can break LCSSA in any
690   /// loop.
691   ///
692   /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
693   /// assuming that the function containing \p Inst and \p NewLoc is currently
694   /// in LCSSA form.
695   bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
696     assert(Inst->getFunction() == NewLoc->getFunction() &&
697            "Can't reason about IPO!");
698
699     auto *OldBB = Inst->getParent();
700     auto *NewBB = NewLoc->getParent();
701
702     // Movement within the same loop does not break LCSSA (the equality check is
703     // to avoid doing a hashtable lookup in case of intra-block movement).
704     if (OldBB == NewBB)
705       return true;
706
707     auto *OldLoop = getLoopFor(OldBB);
708     auto *NewLoop = getLoopFor(NewBB);
709
710     if (OldLoop == NewLoop)
711       return true;
712
713     // Check if Outer contains Inner; with the null loop counting as the
714     // "outermost" loop.
715     auto Contains = [](const Loop *Outer, const Loop *Inner) {
716       return !Outer || Outer->contains(Inner);
717     };
718
719     // To check that the movement of Inst to before NewLoc does not break LCSSA,
720     // we need to check two sets of uses for possible LCSSA violations at
721     // NewLoc: the users of NewInst, and the operands of NewInst.
722
723     // If we know we're hoisting Inst out of an inner loop to an outer loop,
724     // then the uses *of* Inst don't need to be checked.
725
726     if (!Contains(NewLoop, OldLoop)) {
727       for (Use &U : Inst->uses()) {
728         auto *UI = cast<Instruction>(U.getUser());
729         auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
730                                      : UI->getParent();
731         if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
732           return false;
733       }
734     }
735
736     // If we know we're sinking Inst from an outer loop into an inner loop, then
737     // the *operands* of Inst don't need to be checked.
738
739     if (!Contains(OldLoop, NewLoop)) {
740       // See below on why we can't handle phi nodes here.
741       if (isa<PHINode>(Inst))
742         return false;
743
744       for (Use &U : Inst->operands()) {
745         auto *DefI = dyn_cast<Instruction>(U.get());
746         if (!DefI)
747           return false;
748
749         // This would need adjustment if we allow Inst to be a phi node -- the
750         // new use block won't simply be NewBB.
751
752         auto *DefBlock = DefI->getParent();
753         if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
754           return false;
755       }
756     }
757
758     return true;
759   }
760 };
761
762 // Allow clients to walk the list of nested loops...
763 template <> struct GraphTraits<const Loop*> {
764   typedef const Loop NodeType;
765   typedef LoopInfo::iterator ChildIteratorType;
766
767   static NodeType *getEntryNode(const Loop *L) { return L; }
768   static inline ChildIteratorType child_begin(NodeType *N) {
769     return N->begin();
770   }
771   static inline ChildIteratorType child_end(NodeType *N) {
772     return N->end();
773   }
774 };
775
776 template <> struct GraphTraits<Loop*> {
777   typedef Loop NodeType;
778   typedef LoopInfo::iterator ChildIteratorType;
779
780   static NodeType *getEntryNode(Loop *L) { return L; }
781   static inline ChildIteratorType child_begin(NodeType *N) {
782     return N->begin();
783   }
784   static inline ChildIteratorType child_end(NodeType *N) {
785     return N->end();
786   }
787 };
788
789 /// \brief Analysis pass that exposes the \c LoopInfo for a function.
790 class LoopAnalysis {
791   static char PassID;
792
793 public:
794   typedef LoopInfo Result;
795
796   /// \brief Opaque, unique identifier for this analysis pass.
797   static void *ID() { return (void *)&PassID; }
798
799   /// \brief Provide a name for the analysis for debugging and logging.
800   static StringRef name() { return "LoopAnalysis"; }
801
802   LoopInfo run(Function &F, AnalysisManager<Function> *AM);
803 };
804
805 /// \brief Printer pass for the \c LoopAnalysis results.
806 class LoopPrinterPass {
807   raw_ostream &OS;
808
809 public:
810   explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
811   PreservedAnalyses run(Function &F, AnalysisManager<Function> *AM);
812
813   static StringRef name() { return "LoopPrinterPass"; }
814 };
815
816 /// \brief The legacy pass manager's analysis pass to compute loop information.
817 class LoopInfoWrapperPass : public FunctionPass {
818   LoopInfo LI;
819
820 public:
821   static char ID; // Pass identification, replacement for typeid
822
823   LoopInfoWrapperPass() : FunctionPass(ID) {
824     initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
825   }
826
827   LoopInfo &getLoopInfo() { return LI; }
828   const LoopInfo &getLoopInfo() const { return LI; }
829
830   /// \brief Calculate the natural loop information for a given function.
831   bool runOnFunction(Function &F) override;
832
833   void verifyAnalysis() const override;
834
835   void releaseMemory() override { LI.releaseMemory(); }
836
837   void print(raw_ostream &O, const Module *M = nullptr) const override;
838
839   void getAnalysisUsage(AnalysisUsage &AU) const override;
840 };
841
842 /// \brief Pass for printing a loop's contents as LLVM's text IR assembly.
843 class PrintLoopPass {
844   raw_ostream &OS;
845   std::string Banner;
846
847 public:
848   PrintLoopPass();
849   PrintLoopPass(raw_ostream &OS, const std::string &Banner = "");
850
851   PreservedAnalyses run(Loop &L);
852   static StringRef name() { return "PrintLoopPass"; }
853 };
854
855 } // End llvm namespace
856
857 #endif