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