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