LLVM  9.0.0svn
LoopInfo.h
Go to the documentation of this file.
1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the LoopInfo class that is used to identify natural loops
10 // and determine the loop depth of various nodes of the CFG. A natural loop
11 // has exactly one entry-point, which is called the header. Note that natural
12 // loops may actually be several loops that share the same header node.
13 //
14 // This analysis calculates the nesting structure of loops in a function. For
15 // each natural loop identified, this analysis identifies natural loops
16 // contained entirely within the loop and the basic blocks the make up the loop.
17 //
18 // It can calculate on the fly various bits of information, for example:
19 //
20 // * whether there is a preheader for the loop
21 // * the number of back edges to the header
22 // * whether or not a particular block branches out of the loop
23 // * the successor blocks of the loop
24 // * the loop depth
25 // * etc...
26 //
27 // Note that this analysis specifically identifies *Loops* not cycles or SCCs
28 // in the CFG. There can be strongly connected components in the CFG which
29 // this analysis will not recognize and that will not be represented by a Loop
30 // instance. In particular, a Loop might be inside such a non-loop SCC, or a
31 // non-loop SCC might contain a sub-SCC which is a Loop.
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #ifndef LLVM_ANALYSIS_LOOPINFO_H
36 #define LLVM_ANALYSIS_LOOPINFO_H
37 
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/DenseSet.h"
40 #include "llvm/ADT/GraphTraits.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/PassManager.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/Allocator.h"
49 #include <algorithm>
50 #include <utility>
51 
52 namespace llvm {
53 
54 class DominatorTree;
55 class LoopInfo;
56 class Loop;
57 class MDNode;
58 class PHINode;
59 class raw_ostream;
60 template <class N, bool IsPostDom> class DominatorTreeBase;
61 template <class N, class M> class LoopInfoBase;
62 template <class N, class M> class LoopBase;
63 
64 //===----------------------------------------------------------------------===//
65 /// Instances of this class are used to represent loops that are detected in the
66 /// flow graph.
67 ///
68 template <class BlockT, class LoopT> 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 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
79  /// Indicator that this loop is no longer a valid loop.
80  bool IsInvalid = false;
81 #endif
82 
83  LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
85  operator=(const LoopBase<BlockT, LoopT> &) = delete;
86 
87 public:
88  /// Return the nesting level of this loop. An outer-most loop has depth 1,
89  /// for consistency with loop depth values used for basic blocks, where depth
90  /// 0 is used for blocks not inside any loops.
91  unsigned getLoopDepth() const {
92  assert(!isInvalid() && "Loop not in a valid state!");
93  unsigned D = 1;
94  for (const LoopT *CurLoop = ParentLoop; CurLoop;
95  CurLoop = CurLoop->ParentLoop)
96  ++D;
97  return D;
98  }
99  BlockT *getHeader() const { return getBlocks().front(); }
100  LoopT *getParentLoop() const { return ParentLoop; }
101 
102  /// This is a raw interface for bypassing addChildLoop.
103  void setParentLoop(LoopT *L) {
104  assert(!isInvalid() && "Loop not in a valid state!");
105  ParentLoop = L;
106  }
107 
108  /// Return true if the specified loop is contained within in this loop.
109  bool contains(const LoopT *L) const {
110  assert(!isInvalid() && "Loop not in a valid state!");
111  if (L == this)
112  return true;
113  if (!L)
114  return false;
115  return contains(L->getParentLoop());
116  }
117 
118  /// Return true if the specified basic block is in this loop.
119  bool contains(const BlockT *BB) const {
120  assert(!isInvalid() && "Loop not in a valid state!");
121  return DenseBlockSet.count(BB);
122  }
123 
124  /// Return true if the specified instruction is in this loop.
125  template <class InstT> bool contains(const InstT *Inst) const {
126  return contains(Inst->getParent());
127  }
128 
129  /// Return the loops contained entirely within this loop.
130  const std::vector<LoopT *> &getSubLoops() const {
131  assert(!isInvalid() && "Loop not in a valid state!");
132  return SubLoops;
133  }
134  std::vector<LoopT *> &getSubLoopsVector() {
135  assert(!isInvalid() && "Loop not in a valid state!");
136  return SubLoops;
137  }
138  typedef typename std::vector<LoopT *>::const_iterator iterator;
139  typedef
140  typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
141  iterator begin() const { return getSubLoops().begin(); }
142  iterator end() const { return getSubLoops().end(); }
143  reverse_iterator rbegin() const { return getSubLoops().rbegin(); }
144  reverse_iterator rend() const { return getSubLoops().rend(); }
145  bool empty() const { return getSubLoops().empty(); }
146 
147  /// Get a list of the basic blocks which make up this loop.
149  assert(!isInvalid() && "Loop not in a valid state!");
150  return Blocks;
151  }
153  block_iterator block_begin() const { return getBlocks().begin(); }
154  block_iterator block_end() const { return getBlocks().end(); }
156  assert(!isInvalid() && "Loop not in a valid state!");
157  return make_range(block_begin(), block_end());
158  }
159 
160  /// Get the number of blocks in this loop in constant time.
161  /// Invalidate the loop, indicating that it is no longer a loop.
162  unsigned getNumBlocks() const {
163  assert(!isInvalid() && "Loop not in a valid state!");
164  return Blocks.size();
165  }
166 
167  /// Return a direct, mutable handle to the blocks vector so that we can
168  /// mutate it efficiently with techniques like `std::remove`.
169  std::vector<BlockT *> &getBlocksVector() {
170  assert(!isInvalid() && "Loop not in a valid state!");
171  return Blocks;
172  }
173  /// Return a direct, mutable handle to the blocks set so that we can
174  /// mutate it efficiently.
176  assert(!isInvalid() && "Loop not in a valid state!");
177  return DenseBlockSet;
178  }
179 
180  /// Return a direct, immutable handle to the blocks set.
182  assert(!isInvalid() && "Loop not in a valid state!");
183  return DenseBlockSet;
184  }
185 
186  /// Return true if this loop is no longer valid. The only valid use of this
187  /// helper is "assert(L.isInvalid())" or equivalent, since IsInvalid is set to
188  /// true by the destructor. In other words, if this accessor returns true,
189  /// the caller has already triggered UB by calling this accessor; and so it
190  /// can only be called in a context where a return value of true indicates a
191  /// programmer error.
192  bool isInvalid() const {
193 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
194  return IsInvalid;
195 #else
196  return false;
197 #endif
198  }
199 
200  /// True if terminator in the block can branch to another block that is
201  /// outside of the current loop.
202  bool isLoopExiting(const BlockT *BB) const {
203  assert(!isInvalid() && "Loop not in a valid state!");
204  for (const auto &Succ : children<const BlockT *>(BB)) {
205  if (!contains(Succ))
206  return true;
207  }
208  return false;
209  }
210 
211  /// Returns true if \p BB is a loop-latch.
212  /// A latch block is a block that contains a branch back to the header.
213  /// This function is useful when there are multiple latches in a loop
214  /// because \fn getLoopLatch will return nullptr in that case.
215  bool isLoopLatch(const BlockT *BB) const {
216  assert(!isInvalid() && "Loop not in a valid state!");
217  assert(contains(BB) && "block does not belong to the loop");
218 
219  BlockT *Header = getHeader();
220  auto PredBegin = GraphTraits<Inverse<BlockT *>>::child_begin(Header);
221  auto PredEnd = GraphTraits<Inverse<BlockT *>>::child_end(Header);
222  return std::find(PredBegin, PredEnd, BB) != PredEnd;
223  }
224 
225  /// Calculate the number of back edges to the loop header.
226  unsigned getNumBackEdges() const {
227  assert(!isInvalid() && "Loop not in a valid state!");
228  unsigned NumBackEdges = 0;
229  BlockT *H = getHeader();
230 
231  for (const auto Pred : children<Inverse<BlockT *>>(H))
232  if (contains(Pred))
233  ++NumBackEdges;
234 
235  return NumBackEdges;
236  }
237 
238  //===--------------------------------------------------------------------===//
239  // APIs for simple analysis of the loop.
240  //
241  // Note that all of these methods can fail on general loops (ie, there may not
242  // be a preheader, etc). For best success, the loop simplification and
243  // induction variable canonicalization pass should be used to normalize loops
244  // for easy analysis. These methods assume canonical loops.
245 
246  /// Return all blocks inside the loop that have successors outside of the
247  /// loop. These are the blocks _inside of the current loop_ which branch out.
248  /// The returned list is always unique.
249  void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
250 
251  /// If getExitingBlocks would return exactly one block, return that block.
252  /// Otherwise return null.
253  BlockT *getExitingBlock() const;
254 
255  /// Return all of the successor blocks of this loop. These are the blocks
256  /// _outside of the current loop_ which are branched to.
257  void getExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
258 
259  /// If getExitBlocks would return exactly one block, return that block.
260  /// Otherwise return null.
261  BlockT *getExitBlock() const;
262 
263  /// Return true if no exit block for the loop has a predecessor that is
264  /// outside the loop.
265  bool hasDedicatedExits() const;
266 
267  /// Return all unique successor blocks of this loop.
268  /// These are the blocks _outside of the current loop_ which are branched to.
269  /// This assumes that loop exits are in canonical form, i.e. all exits are
270  /// dedicated exits.
271  void getUniqueExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
272 
273  /// If getUniqueExitBlocks would return exactly one block, return that block.
274  /// Otherwise return null.
275  BlockT *getUniqueExitBlock() const;
276 
277  /// Edge type.
278  typedef std::pair<const BlockT *, const BlockT *> Edge;
279 
280  /// Return all pairs of (_inside_block_,_outside_block_).
281  void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
282 
283  /// If there is a preheader for this loop, return it. A loop has a preheader
284  /// if there is only one edge to the header of the loop from outside of the
285  /// loop. If this is the case, the block branching to the header of the loop
286  /// is the preheader node.
287  ///
288  /// This method returns null if there is no preheader for the loop.
289  BlockT *getLoopPreheader() const;
290 
291  /// If the given loop's header has exactly one unique predecessor outside the
292  /// loop, return it. Otherwise return null.
293  /// This is less strict that the loop "preheader" concept, which requires
294  /// the predecessor to have exactly one successor.
295  BlockT *getLoopPredecessor() const;
296 
297  /// If there is a single latch block for this loop, return it.
298  /// A latch block is a block that contains a branch back to the header.
299  BlockT *getLoopLatch() const;
300 
301  /// Return all loop latch blocks of this loop. A latch block is a block that
302  /// contains a branch back to the header.
303  void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
304  assert(!isInvalid() && "Loop not in a valid state!");
305  BlockT *H = getHeader();
306  for (const auto Pred : children<Inverse<BlockT *>>(H))
307  if (contains(Pred))
308  LoopLatches.push_back(Pred);
309  }
310 
311  //===--------------------------------------------------------------------===//
312  // APIs for updating loop information after changing the CFG
313  //
314 
315  /// This method is used by other analyses to update loop information.
316  /// NewBB is set to be a new member of the current loop.
317  /// Because of this, it is added as a member of all parent loops, and is added
318  /// to the specified LoopInfo object as being in the current basic block. It
319  /// is not valid to replace the loop header with this method.
320  void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
321 
322  /// This is used when splitting loops up. It replaces the OldChild entry in
323  /// our children list with NewChild, and updates the parent pointer of
324  /// OldChild to be null and the NewChild to be this loop.
325  /// This updates the loop depth of the new child.
326  void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
327 
328  /// Add the specified loop to be a child of this loop.
329  /// This updates the loop depth of the new child.
330  void addChildLoop(LoopT *NewChild) {
331  assert(!isInvalid() && "Loop not in a valid state!");
332  assert(!NewChild->ParentLoop && "NewChild already has a parent!");
333  NewChild->ParentLoop = static_cast<LoopT *>(this);
334  SubLoops.push_back(NewChild);
335  }
336 
337  /// This removes the specified child from being a subloop of this loop. The
338  /// loop is not deleted, as it will presumably be inserted into another loop.
339  LoopT *removeChildLoop(iterator I) {
340  assert(!isInvalid() && "Loop not in a valid state!");
341  assert(I != SubLoops.end() && "Cannot remove end iterator!");
342  LoopT *Child = *I;
343  assert(Child->ParentLoop == this && "Child is not a child of this loop!");
344  SubLoops.erase(SubLoops.begin() + (I - begin()));
345  Child->ParentLoop = nullptr;
346  return Child;
347  }
348 
349  /// This removes the specified child from being a subloop of this loop. The
350  /// loop is not deleted, as it will presumably be inserted into another loop.
351  LoopT *removeChildLoop(LoopT *Child) {
352  return removeChildLoop(llvm::find(*this, Child));
353  }
354 
355  /// This adds a basic block directly to the basic block list.
356  /// This should only be used by transformations that create new loops. Other
357  /// transformations should use addBasicBlockToLoop.
358  void addBlockEntry(BlockT *BB) {
359  assert(!isInvalid() && "Loop not in a valid state!");
360  Blocks.push_back(BB);
361  DenseBlockSet.insert(BB);
362  }
363 
364  /// interface to reverse Blocks[from, end of loop] in this loop
365  void reverseBlock(unsigned from) {
366  assert(!isInvalid() && "Loop not in a valid state!");
367  std::reverse(Blocks.begin() + from, Blocks.end());
368  }
369 
370  /// interface to do reserve() for Blocks
371  void reserveBlocks(unsigned size) {
372  assert(!isInvalid() && "Loop not in a valid state!");
373  Blocks.reserve(size);
374  }
375 
376  /// This method is used to move BB (which must be part of this loop) to be the
377  /// loop header of the loop (the block that dominates all others).
378  void moveToHeader(BlockT *BB) {
379  assert(!isInvalid() && "Loop not in a valid state!");
380  if (Blocks[0] == BB)
381  return;
382  for (unsigned i = 0;; ++i) {
383  assert(i != Blocks.size() && "Loop does not contain BB!");
384  if (Blocks[i] == BB) {
385  Blocks[i] = Blocks[0];
386  Blocks[0] = BB;
387  return;
388  }
389  }
390  }
391 
392  /// This removes the specified basic block from the current loop, updating the
393  /// Blocks as appropriate. This does not update the mapping in the LoopInfo
394  /// class.
395  void removeBlockFromLoop(BlockT *BB) {
396  assert(!isInvalid() && "Loop not in a valid state!");
397  auto I = find(Blocks, BB);
398  assert(I != Blocks.end() && "N is not in this list!");
399  Blocks.erase(I);
400 
401  DenseBlockSet.erase(BB);
402  }
403 
404  /// Verify loop structure
405  void verifyLoop() const;
406 
407  /// Verify loop structure of this loop and all nested loops.
409 
410  /// Returns true if the loop is annotated parallel.
411  ///
412  /// Derived classes can override this method using static template
413  /// polymorphism.
414  bool isAnnotatedParallel() const { return false; }
415 
416  /// Print loop with all the BBs inside it.
417  void print(raw_ostream &OS, unsigned Depth = 0, bool Verbose = false) const;
418 
419 protected:
420  friend class LoopInfoBase<BlockT, LoopT>;
421 
422  /// This creates an empty loop.
423  LoopBase() : ParentLoop(nullptr) {}
424 
425  explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
426  Blocks.push_back(BB);
427  DenseBlockSet.insert(BB);
428  }
429 
430  // Since loop passes like SCEV are allowed to key analysis results off of
431  // `Loop` pointers, we cannot re-use pointers within a loop pass manager.
432  // This means loop passes should not be `delete` ing `Loop` objects directly
433  // (and risk a later `Loop` allocation re-using the address of a previous one)
434  // but should be using LoopInfo::markAsRemoved, which keeps around the `Loop`
435  // pointer till the end of the lifetime of the `LoopInfo` object.
436  //
437  // To make it easier to follow this rule, we mark the destructor as
438  // non-public.
440  for (auto *SubLoop : SubLoops)
441  SubLoop->~LoopT();
442 
443 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
444  IsInvalid = true;
445 #endif
446  SubLoops.clear();
447  Blocks.clear();
448  DenseBlockSet.clear();
449  ParentLoop = nullptr;
450  }
451 };
452 
453 template <class BlockT, class LoopT>
454 raw_ostream &operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
455  Loop.print(OS);
456  return OS;
457 }
458 
459 // Implementation in LoopInfoImpl.h
460 extern template class LoopBase<BasicBlock, Loop>;
461 
462 /// Represents a single loop in the control flow graph. Note that not all SCCs
463 /// in the CFG are necessarily loops.
465 public:
466  /// A range representing the start and end location of a loop.
467  class LocRange {
468  DebugLoc Start;
469  DebugLoc End;
470 
471  public:
472  LocRange() {}
473  LocRange(DebugLoc Start) : Start(std::move(Start)), End(std::move(Start)) {}
475  : Start(std::move(Start)), End(std::move(End)) {}
476 
477  const DebugLoc &getStart() const { return Start; }
478  const DebugLoc &getEnd() const { return End; }
479 
480  /// Check for null.
481  ///
482  explicit operator bool() const { return Start && End; }
483  };
484 
485  /// Return true if the specified value is loop invariant.
486  bool isLoopInvariant(const Value *V) const;
487 
488  /// Return true if all the operands of the specified instruction are loop
489  /// invariant.
490  bool hasLoopInvariantOperands(const Instruction *I) const;
491 
492  /// If the given value is an instruction inside of the loop and it can be
493  /// hoisted, do so to make it trivially loop-invariant.
494  /// Return true if the value after any hoisting is loop invariant. This
495  /// function can be used as a slightly more aggressive replacement for
496  /// isLoopInvariant.
497  ///
498  /// If InsertPt is specified, it is the point to hoist instructions to.
499  /// If null, the terminator of the loop preheader is used.
500  bool makeLoopInvariant(Value *V, bool &Changed,
501  Instruction *InsertPt = nullptr) const;
502 
503  /// If the given instruction is inside of the loop and it can be hoisted, do
504  /// so to make it trivially loop-invariant.
505  /// Return true if the instruction after any hoisting is loop invariant. This
506  /// function can be used as a slightly more aggressive replacement for
507  /// isLoopInvariant.
508  ///
509  /// If InsertPt is specified, it is the point to hoist instructions to.
510  /// If null, the terminator of the loop preheader is used.
511  ///
512  bool makeLoopInvariant(Instruction *I, bool &Changed,
513  Instruction *InsertPt = nullptr) const;
514 
515  /// Check to see if the loop has a canonical induction variable: an integer
516  /// recurrence that starts at 0 and increments by one each time through the
517  /// loop. If so, return the phi node that corresponds to it.
518  ///
519  /// The IndVarSimplify pass transforms loops to have a canonical induction
520  /// variable.
521  ///
522  PHINode *getCanonicalInductionVariable() const;
523 
524  /// Obtain the unique incoming and back edge. Return false if they are
525  /// non-unique or the loop is dead; otherwise, return true.
526  bool getIncomingAndBackEdge(BasicBlock *&Incoming,
527  BasicBlock *&Backedge) const;
528 
529  /// Return true if the Loop is in LCSSA form.
530  bool isLCSSAForm(DominatorTree &DT) const;
531 
532  /// Return true if this Loop and all inner subloops are in LCSSA form.
533  bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const;
534 
535  /// Return true if the Loop is in the form that the LoopSimplify form
536  /// transforms loops to, which is sometimes called normal form.
537  bool isLoopSimplifyForm() const;
538 
539  /// Return true if the loop body is safe to clone in practice.
540  bool isSafeToClone() const;
541 
542  /// Returns true if the loop is annotated parallel.
543  ///
544  /// A parallel loop can be assumed to not contain any dependencies between
545  /// iterations by the compiler. That is, any loop-carried dependency checking
546  /// can be skipped completely when parallelizing the loop on the target
547  /// machine. Thus, if the parallel loop information originates from the
548  /// programmer, e.g. via the OpenMP parallel for pragma, it is the
549  /// programmer's responsibility to ensure there are no loop-carried
550  /// dependencies. The final execution order of the instructions across
551  /// iterations is not guaranteed, thus, the end result might or might not
552  /// implement actual concurrent execution of instructions across multiple
553  /// iterations.
554  bool isAnnotatedParallel() const;
555 
556  /// Return the llvm.loop loop id metadata node for this loop if it is present.
557  ///
558  /// If this loop contains the same llvm.loop metadata on each branch to the
559  /// header then the node is returned. If any latch instruction does not
560  /// contain llvm.loop or if multiple latches contain different nodes then
561  /// 0 is returned.
562  MDNode *getLoopID() const;
563  /// Set the llvm.loop loop id metadata for this loop.
564  ///
565  /// The LoopID metadata node will be added to each terminator instruction in
566  /// the loop that branches to the loop header.
567  ///
568  /// The LoopID metadata node should have one or more operands and the first
569  /// operand should be the node itself.
570  void setLoopID(MDNode *LoopID) const;
571 
572  /// Add llvm.loop.unroll.disable to this loop's loop id metadata.
573  ///
574  /// Remove existing unroll metadata and add unroll disable metadata to
575  /// indicate the loop has already been unrolled. This prevents a loop
576  /// from being unrolled more than is directed by a pragma if the loop
577  /// unrolling pass is run more than once (which it generally is).
578  void setLoopAlreadyUnrolled();
579 
580  void dump() const;
581  void dumpVerbose() const;
582 
583  /// Return the debug location of the start of this loop.
584  /// This looks for a BB terminating instruction with a known debug
585  /// location by looking at the preheader and header blocks. If it
586  /// cannot find a terminating instruction with location information,
587  /// it returns an unknown location.
588  DebugLoc getStartLoc() const;
589 
590  /// Return the source code span of the loop.
591  LocRange getLocRange() const;
592 
593  StringRef getName() const {
594  if (BasicBlock *Header = getHeader())
595  if (Header->hasName())
596  return Header->getName();
597  return "<unnamed loop>";
598  }
599 
600 private:
601  Loop() = default;
602 
605  explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
606  ~Loop() = default;
607 };
608 
609 //===----------------------------------------------------------------------===//
610 /// This class builds and contains all of the top-level loop
611 /// structures in the specified function.
612 ///
613 
614 template <class BlockT, class LoopT> class LoopInfoBase {
615  // BBMap - Mapping of basic blocks to the inner most loop they occur in
617  std::vector<LoopT *> TopLevelLoops;
618  BumpPtrAllocator LoopAllocator;
619 
621  friend class LoopInfo;
622 
623  void operator=(const LoopInfoBase &) = delete;
624  LoopInfoBase(const LoopInfoBase &) = delete;
625 
626 public:
628  ~LoopInfoBase() { releaseMemory(); }
629 
631  : BBMap(std::move(Arg.BBMap)),
632  TopLevelLoops(std::move(Arg.TopLevelLoops)),
633  LoopAllocator(std::move(Arg.LoopAllocator)) {
634  // We have to clear the arguments top level loops as we've taken ownership.
635  Arg.TopLevelLoops.clear();
636  }
638  BBMap = std::move(RHS.BBMap);
639 
640  for (auto *L : TopLevelLoops)
641  L->~LoopT();
642 
643  TopLevelLoops = std::move(RHS.TopLevelLoops);
644  LoopAllocator = std::move(RHS.LoopAllocator);
645  RHS.TopLevelLoops.clear();
646  return *this;
647  }
648 
649  void releaseMemory() {
650  BBMap.clear();
651 
652  for (auto *L : TopLevelLoops)
653  L->~LoopT();
654  TopLevelLoops.clear();
655  LoopAllocator.Reset();
656  }
657 
658  template <typename... ArgsTy> LoopT *AllocateLoop(ArgsTy &&... Args) {
659  LoopT *Storage = LoopAllocator.Allocate<LoopT>();
660  return new (Storage) LoopT(std::forward<ArgsTy>(Args)...);
661  }
662 
663  /// iterator/begin/end - The interface to the top-level loops in the current
664  /// function.
665  ///
666  typedef typename std::vector<LoopT *>::const_iterator iterator;
667  typedef
668  typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
669  iterator begin() const { return TopLevelLoops.begin(); }
670  iterator end() const { return TopLevelLoops.end(); }
671  reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
672  reverse_iterator rend() const { return TopLevelLoops.rend(); }
673  bool empty() const { return TopLevelLoops.empty(); }
674 
675  /// Return all of the loops in the function in preorder across the loop
676  /// nests, with siblings in forward program order.
677  ///
678  /// Note that because loops form a forest of trees, preorder is equivalent to
679  /// reverse postorder.
680  SmallVector<LoopT *, 4> getLoopsInPreorder();
681 
682  /// Return all of the loops in the function in preorder across the loop
683  /// nests, with siblings in *reverse* program order.
684  ///
685  /// Note that because loops form a forest of trees, preorder is equivalent to
686  /// reverse postorder.
687  ///
688  /// Also note that this is *not* a reverse preorder. Only the siblings are in
689  /// reverse program order.
690  SmallVector<LoopT *, 4> getLoopsInReverseSiblingPreorder();
691 
692  /// Return the inner most loop that BB lives in. If a basic block is in no
693  /// loop (for example the entry node), null is returned.
694  LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
695 
696  /// Same as getLoopFor.
697  const LoopT *operator[](const BlockT *BB) const { return getLoopFor(BB); }
698 
699  /// Return the loop nesting level of the specified block. A depth of 0 means
700  /// the block is not inside any loop.
701  unsigned getLoopDepth(const BlockT *BB) const {
702  const LoopT *L = getLoopFor(BB);
703  return L ? L->getLoopDepth() : 0;
704  }
705 
706  // True if the block is a loop header node
707  bool isLoopHeader(const BlockT *BB) const {
708  const LoopT *L = getLoopFor(BB);
709  return L && L->getHeader() == BB;
710  }
711 
712  /// This removes the specified top-level loop from this loop info object.
713  /// The loop is not deleted, as it will presumably be inserted into
714  /// another loop.
715  LoopT *removeLoop(iterator I) {
716  assert(I != end() && "Cannot remove end iterator!");
717  LoopT *L = *I;
718  assert(!L->getParentLoop() && "Not a top-level loop!");
719  TopLevelLoops.erase(TopLevelLoops.begin() + (I - begin()));
720  return L;
721  }
722 
723  /// Change the top-level loop that contains BB to the specified loop.
724  /// This should be used by transformations that restructure the loop hierarchy
725  /// tree.
726  void changeLoopFor(BlockT *BB, LoopT *L) {
727  if (!L) {
728  BBMap.erase(BB);
729  return;
730  }
731  BBMap[BB] = L;
732  }
733 
734  /// Replace the specified loop in the top-level loops list with the indicated
735  /// loop.
736  void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop) {
737  auto I = find(TopLevelLoops, OldLoop);
738  assert(I != TopLevelLoops.end() && "Old loop not at top level!");
739  *I = NewLoop;
740  assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
741  "Loops already embedded into a subloop!");
742  }
743 
744  /// This adds the specified loop to the collection of top-level loops.
745  void addTopLevelLoop(LoopT *New) {
746  assert(!New->getParentLoop() && "Loop already in subloop!");
747  TopLevelLoops.push_back(New);
748  }
749 
750  /// This method completely removes BB from all data structures,
751  /// including all of the Loop objects it is nested in and our mapping from
752  /// BasicBlocks to loops.
753  void removeBlock(BlockT *BB) {
754  auto I = BBMap.find(BB);
755  if (I != BBMap.end()) {
756  for (LoopT *L = I->second; L; L = L->getParentLoop())
757  L->removeBlockFromLoop(BB);
758 
759  BBMap.erase(I);
760  }
761  }
762 
763  // Internals
764 
765  static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
766  const LoopT *ParentLoop) {
767  if (!SubLoop)
768  return true;
769  if (SubLoop == ParentLoop)
770  return false;
771  return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
772  }
773 
774  /// Create the loop forest using a stable algorithm.
775  void analyze(const DominatorTreeBase<BlockT, false> &DomTree);
776 
777  // Debugging
778  void print(raw_ostream &OS) const;
779 
780  void verify(const DominatorTreeBase<BlockT, false> &DomTree) const;
781 
782  /// Destroy a loop that has been removed from the `LoopInfo` nest.
783  ///
784  /// This runs the destructor of the loop object making it invalid to
785  /// reference afterward. The memory is retained so that the *pointer* to the
786  /// loop remains valid.
787  ///
788  /// The caller is responsible for removing this loop from the loop nest and
789  /// otherwise disconnecting it from the broader `LoopInfo` data structures.
790  /// Callers that don't naturally handle this themselves should probably call
791  /// `erase' instead.
792  void destroy(LoopT *L) {
793  L->~LoopT();
794 
795  // Since LoopAllocator is a BumpPtrAllocator, this Deallocate only poisons
796  // \c L, but the pointer remains valid for non-dereferencing uses.
797  LoopAllocator.Deallocate(L);
798  }
799 };
800 
801 // Implementation in LoopInfoImpl.h
802 extern template class LoopInfoBase<BasicBlock, Loop>;
803 
806 
808 
809  void operator=(const LoopInfo &) = delete;
810  LoopInfo(const LoopInfo &) = delete;
811 
812 public:
813  LoopInfo() {}
814  explicit LoopInfo(const DominatorTreeBase<BasicBlock, false> &DomTree);
815 
816  LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
818  BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
819  return *this;
820  }
821 
822  /// Handle invalidation explicitly.
823  bool invalidate(Function &F, const PreservedAnalyses &PA,
825 
826  // Most of the public interface is provided via LoopInfoBase.
827 
828  /// Update LoopInfo after removing the last backedge from a loop. This updates
829  /// the loop forest and parent loops for each block so that \c L is no longer
830  /// referenced, but does not actually delete \c L immediately. The pointer
831  /// will remain valid until this LoopInfo's memory is released.
832  void erase(Loop *L);
833 
834  /// Returns true if replacing From with To everywhere is guaranteed to
835  /// preserve LCSSA form.
837  // Preserving LCSSA form is only problematic if the replacing value is an
838  // instruction.
840  if (!I)
841  return true;
842  // If both instructions are defined in the same basic block then replacement
843  // cannot break LCSSA form.
844  if (I->getParent() == From->getParent())
845  return true;
846  // If the instruction is not defined in a loop then it can safely replace
847  // anything.
848  Loop *ToLoop = getLoopFor(I->getParent());
849  if (!ToLoop)
850  return true;
851  // If the replacing instruction is defined in the same loop as the original
852  // instruction, or in a loop that contains it as an inner loop, then using
853  // it as a replacement will not break LCSSA form.
854  return ToLoop->contains(getLoopFor(From->getParent()));
855  }
856 
857  /// Checks if moving a specific instruction can break LCSSA in any loop.
858  ///
859  /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
860  /// assuming that the function containing \p Inst and \p NewLoc is currently
861  /// in LCSSA form.
863  assert(Inst->getFunction() == NewLoc->getFunction() &&
864  "Can't reason about IPO!");
865 
866  auto *OldBB = Inst->getParent();
867  auto *NewBB = NewLoc->getParent();
868 
869  // Movement within the same loop does not break LCSSA (the equality check is
870  // to avoid doing a hashtable lookup in case of intra-block movement).
871  if (OldBB == NewBB)
872  return true;
873 
874  auto *OldLoop = getLoopFor(OldBB);
875  auto *NewLoop = getLoopFor(NewBB);
876 
877  if (OldLoop == NewLoop)
878  return true;
879 
880  // Check if Outer contains Inner; with the null loop counting as the
881  // "outermost" loop.
882  auto Contains = [](const Loop *Outer, const Loop *Inner) {
883  return !Outer || Outer->contains(Inner);
884  };
885 
886  // To check that the movement of Inst to before NewLoc does not break LCSSA,
887  // we need to check two sets of uses for possible LCSSA violations at
888  // NewLoc: the users of NewInst, and the operands of NewInst.
889 
890  // If we know we're hoisting Inst out of an inner loop to an outer loop,
891  // then the uses *of* Inst don't need to be checked.
892 
893  if (!Contains(NewLoop, OldLoop)) {
894  for (Use &U : Inst->uses()) {
895  auto *UI = cast<Instruction>(U.getUser());
896  auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
897  : UI->getParent();
898  if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
899  return false;
900  }
901  }
902 
903  // If we know we're sinking Inst from an outer loop into an inner loop, then
904  // the *operands* of Inst don't need to be checked.
905 
906  if (!Contains(OldLoop, NewLoop)) {
907  // See below on why we can't handle phi nodes here.
908  if (isa<PHINode>(Inst))
909  return false;
910 
911  for (Use &U : Inst->operands()) {
912  auto *DefI = dyn_cast<Instruction>(U.get());
913  if (!DefI)
914  return false;
915 
916  // This would need adjustment if we allow Inst to be a phi node -- the
917  // new use block won't simply be NewBB.
918 
919  auto *DefBlock = DefI->getParent();
920  if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
921  return false;
922  }
923  }
924 
925  return true;
926  }
927 };
928 
929 // Allow clients to walk the list of nested loops...
930 template <> struct GraphTraits<const Loop *> {
931  typedef const Loop *NodeRef;
933 
934  static NodeRef getEntryNode(const Loop *L) { return L; }
935  static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
936  static ChildIteratorType child_end(NodeRef N) { return N->end(); }
937 };
938 
939 template <> struct GraphTraits<Loop *> {
940  typedef Loop *NodeRef;
942 
943  static NodeRef getEntryNode(Loop *L) { return L; }
944  static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
945  static ChildIteratorType child_end(NodeRef N) { return N->end(); }
946 };
947 
948 /// Analysis pass that exposes the \c LoopInfo for a function.
949 class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> {
951  static AnalysisKey Key;
952 
953 public:
954  typedef LoopInfo Result;
955 
957 };
958 
959 /// Printer pass for the \c LoopAnalysis results.
960 class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> {
961  raw_ostream &OS;
962 
963 public:
964  explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
966 };
967 
968 /// Verifier pass for the \c LoopAnalysis results.
969 struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> {
971 };
972 
973 /// The legacy pass manager's analysis pass to compute loop information.
975  LoopInfo LI;
976 
977 public:
978  static char ID; // Pass identification, replacement for typeid
979 
982  }
983 
984  LoopInfo &getLoopInfo() { return LI; }
985  const LoopInfo &getLoopInfo() const { return LI; }
986 
987  /// Calculate the natural loop information for a given function.
988  bool runOnFunction(Function &F) override;
989 
990  void verifyAnalysis() const override;
991 
992  void releaseMemory() override { LI.releaseMemory(); }
993 
994  void print(raw_ostream &O, const Module *M = nullptr) const override;
995 
996  void getAnalysisUsage(AnalysisUsage &AU) const override;
997 };
998 
999 /// Function to print a loop's contents as LLVM's text IR assembly.
1000 void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner = "");
1001 
1002 /// Find and return the loop attribute node for the attribute @p Name in
1003 /// @p LoopID. Return nullptr if there is no such attribute.
1005 
1006 /// Find string metadata for a loop.
1007 ///
1008 /// Returns the MDNode where the first operand is the metadata's name. The
1009 /// following operands are the metadata's values. If no metadata with @p Name is
1010 /// found, return nullptr.
1011 MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name);
1012 
1013 /// Return whether an MDNode might represent an access group.
1014 ///
1015 /// Access group metadata nodes have to be distinct and empty. Being
1016 /// always-empty ensures that it never needs to be changed (which -- because
1017 /// MDNodes are designed immutable -- would require creating a new MDNode). Note
1018 /// that this is not a sufficient condition: not every distinct and empty NDNode
1019 /// is representing an access group.
1020 bool isValidAsAccessGroup(MDNode *AccGroup);
1021 
1022 /// Create a new LoopID after the loop has been transformed.
1023 ///
1024 /// This can be used when no follow-up loop attributes are defined
1025 /// (llvm::makeFollowupLoopID returning None) to stop transformations to be
1026 /// applied again.
1027 ///
1028 /// @param Context The LLVMContext in which to create the new LoopID.
1029 /// @param OrigLoopID The original LoopID; can be nullptr if the original
1030 /// loop has no LoopID.
1031 /// @param RemovePrefixes Remove all loop attributes that have these prefixes.
1032 /// Use to remove metadata of the transformation that has
1033 /// been applied.
1034 /// @param AddAttrs Add these loop attributes to the new LoopID.
1035 ///
1036 /// @return A new LoopID that can be applied using Loop::setLoopID().
1037 llvm::MDNode *
1039  llvm::ArrayRef<llvm::StringRef> RemovePrefixes,
1041 
1042 } // End llvm namespace
1043 
1044 #endif
LoopInfo::iterator ChildIteratorType
Definition: LoopInfo.h:932
void destroy(LoopT *L)
Destroy a loop that has been removed from the LoopInfo nest.
Definition: LoopInfo.h:792
LoopInfo Result
Definition: LoopInfo.h:954
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
Definition: GraphTraits.h:121
iterator_range< use_iterator > uses()
Definition: Value.h:354
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:224
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
std::vector< BlockT * > & getBlocksVector()
Return a direct, mutable handle to the blocks vector so that we can mutate it efficiently with techni...
Definition: LoopInfo.h:169
LLVMContext & Context
bool empty() const
Definition: LoopInfo.h:673
static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT)
Perform a quick domtree based check for loop invariance assuming that V is used within the loop...
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void setParentLoop(LoopT *L)
This is a raw interface for bypassing addChildLoop.
Definition: LoopInfo.h:103
ArrayRef< BlockT * >::const_iterator block_iterator
Definition: LoopInfo.h:152
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Definition: LoopInfoImpl.h:85
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
Definition: LoopInfo.h:701
Implements a dense probed hash-table based set.
Definition: DenseSet.h:249
unsigned getLoopDepth() const
Return the nesting level of this loop.
Definition: LoopInfo.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:211
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
Definition: LoopInfo.h:378
llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode *> AddAttrs)
Create a new LoopID after the loop has been transformed.
Definition: LoopInfo.cpp:754
void reserveBlocks(unsigned size)
interface to do reserve() for Blocks
Definition: LoopInfo.h:371
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
Definition: LoopInfo.h:339
std::pair< const BlockT *, const BlockT * > Edge
Edge type.
Definition: LoopInfo.h:278
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:173
void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild)
This is used when splitting loops up.
Definition: LoopInfoImpl.h:280
std::vector< LoopT * > & getSubLoopsVector()
Definition: LoopInfo.h:134
A debug info location.
Definition: DebugLoc.h:33
Metadata node.
Definition: Metadata.h:863
F(f)
const SmallPtrSetImpl< const BlockT * > & getBlocksSet() const
Return a direct, immutable handle to the blocks set.
Definition: LoopInfo.h:181
LoopBase()
This creates an empty loop.
Definition: LoopInfo.h:423
Instances of this class are used to represent loops that are detected in the flow graph...
Definition: LoopInfo.h:62
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
bool isInvalid() const
Return true if this loop is no longer valid.
Definition: LoopInfo.h:192
void print(raw_ostream &OS, unsigned Depth=0, bool Verbose=false) const
Print loop with all the BBs inside it.
Definition: LoopInfoImpl.h:392
Hexagon Hardware Loops
Definition: BitVector.h:937
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
Definition: LoopInfo.h:226
void initializeLoopInfoWrapperPassPass(PassRegistry &)
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it...
Definition: Allocator.h:194
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Definition: LoopInfo.h:694
SmallPtrSetImpl< const BlockT * > & getBlocksSet()
Return a direct, mutable handle to the blocks set so that we can mutate it efficiently.
Definition: LoopInfo.h:175
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
Definition: LoopInfo.h:358
static bool isNotAlreadyContainedIn(const LoopT *SubLoop, const LoopT *ParentLoop)
Definition: LoopInfo.h:765
std::vector< LoopT * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
Definition: LoopInfo.h:666
void getLoopLatches(SmallVectorImpl< BlockT *> &LoopLatches) const
Return all loop latch blocks of this loop.
Definition: LoopInfo.h:303
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
Definition: LoopInfo.h:414
Printer pass for the LoopAnalysis results.
Definition: LoopInfo.h:960
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:949
void Deallocate(const void *Ptr, size_t Size)
Definition: Allocator.h:277
BlockT * getHeader() const
Definition: LoopInfo.h:99
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
Definition: LoopInfoImpl.h:62
const LoopInfo & getLoopInfo() const
Definition: LoopInfo.h:985
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:266
std::vector< LoopT * >::const_iterator iterator
Definition: LoopInfo.h:138
Key
PAL metadata keys.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
Definition: LoopInfoImpl.h:250
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:365
MDNode * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a loop.
Definition: LoopInfo.cpp:746
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
Definition: LoopInfo.h:745
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
LoopInfo & operator=(LoopInfo &&RHS)
Definition: LoopInfo.h:817
LocRange(DebugLoc Start, DebugLoc End)
Definition: LoopInfo.h:474
const DebugLoc & getEnd() const
Definition: LoopInfo.h:478
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: LoopInfo.h:992
Core dominator tree base class.
Definition: LoopInfo.h:60
static bool runOnFunction(Function &F, bool PostInlining)
reverse_iterator rend() const
Definition: LoopInfo.h:144
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
reverse_iterator rbegin() const
Definition: LoopInfo.h:143
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
Definition: LoopInfo.h:202
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:140
static ChildIteratorType child_begin(NodeRef N)
Definition: LoopInfo.h:935
iterator end() const
Definition: LoopInfo.h:670
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:214
#define H(x, y, z)
Definition: MD5.cpp:57
LoopPrinterPass(raw_ostream &OS)
Definition: LoopInfo.h:964
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:382
Represent the analysis usage information of a pass.
bool contains(const BlockT *BB) const
Return true if the specified basic block is in this loop.
Definition: LoopInfo.h:119
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
op_range operands()
Definition: User.h:237
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:59
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:75
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
Definition: LoopInfoImpl.h:34
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:144
A range representing the start and end location of a loop.
Definition: LoopInfo.h:467
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1206
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
void getExitEdges(SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
Definition: LoopInfoImpl.h:154
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LoopInfoBase & operator=(LoopInfoBase &&RHS)
Definition: LoopInfo.h:637
BlockT * getLoopPredecessor() const
If the given loop&#39;s header has exactly one unique predecessor outside the loop, return it...
Definition: LoopInfoImpl.h:201
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:109
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1166
BlockVerifier::State From
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Definition: SmallPtrSet.h:377
bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc)
Checks if moving a specific instruction can break LCSSA in any loop.
Definition: LoopInfo.h:862
reverse_iterator rend() const
Definition: LoopInfo.h:672
Verifier pass for the LoopAnalysis results.
Definition: LoopInfo.h:969
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
const T * const_iterator
Definition: ArrayRef.h:44
iterator begin() const
Definition: LoopInfo.h:141
LoopInfo & getLoopInfo()
Definition: LoopInfo.h:984
LoopT * removeLoop(iterator I)
This removes the specified top-level loop from this loop info object.
Definition: LoopInfo.h:715
bool contains(const InstT *Inst) const
Return true if the specified instruction is in this loop.
Definition: LoopInfo.h:125
MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
Definition: LoopInfo.cpp:720
static NodeRef getEntryNode(const Loop *L)
Definition: LoopInfo.h:934
LoopT * AllocateLoop(ArgsTy &&... Args)
Definition: LoopInfo.h:658
LoopInfo(LoopInfo &&Arg)
Definition: LoopInfo.h:816
static ChildIteratorType child_end(NodeRef N)
Definition: LoopInfo.h:936
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
std::vector< LoopT * >::const_reverse_iterator reverse_iterator
Definition: LoopInfo.h:140
bool isLoopLatch(const BlockT *BB) const
Definition: LoopInfo.h:215
iterator begin() const
Definition: LoopInfo.h:669
A range adaptor for a pair of iterators.
LoopInfo::iterator ChildIteratorType
Definition: LoopInfo.h:941
bool isLoopHeader(const BlockT *BB) const
Definition: LoopInfo.h:707
reverse_iterator rbegin() const
Definition: LoopInfo.h:671
LoopT * getParentLoop() const
Definition: LoopInfo.h:100
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
Definition: LoopInfo.h:130
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
Definition: LoopInfo.h:162
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
void verifyLoopNest(DenseSet< const LoopT *> *Loops) const
Verify loop structure of this loop and all nested loops.
Definition: LoopInfoImpl.h:380
static NodeRef getEntryNode(Loop *L)
Definition: LoopInfo.h:943
const DebugLoc & getStart() const
Definition: LoopInfo.h:477
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
Definition: LoopInfo.h:330
StringRef getName() const
Definition: LoopInfo.h:593
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:464
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
Definition: LoopInfo.h:148
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
static ChildIteratorType child_end(NodeRef N)
Definition: LoopInfo.h:945
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
Replace the specified loop in the top-level loops list with the indicated loop.
Definition: LoopInfo.h:736
iterator end() const
Definition: LoopInfo.h:142
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
block_iterator block_end() const
Definition: LoopInfo.h:154
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
Definition: LoopInfo.h:726
friend class LoopInfo
Definition: LoopInfo.h:621
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate...
Definition: LoopInfo.h:395
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:211
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:641
bool empty() const
Definition: LoopInfo.h:145
LoopT * removeChildLoop(LoopT *Child)
This removes the specified child from being a subloop of this loop.
Definition: LoopInfo.h:351
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:72
const LoopT * operator[](const BlockT *BB) const
Same as getLoopFor.
Definition: LoopInfo.h:697
void reverseBlock(unsigned from)
interface to reverse Blocks[from, end of loop] in this loop
Definition: LoopInfo.h:365
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
The legacy pass manager&#39;s analysis pass to compute loop information.
Definition: LoopInfo.h:974
void verifyLoop() const
Verify loop structure.
Definition: LoopInfoImpl.h:294
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
Definition: LoopInfoImpl.h:99
LoopInfoBase(LoopInfoBase &&Arg)
Definition: LoopInfo.h:630
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
A container for analyses that lazily runs them and caches their results.
void releaseMemory()
Definition: LoopInfo.h:649
std::vector< LoopT * >::const_reverse_iterator reverse_iterator
Definition: LoopInfo.h:668
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
Definition: LoopInfo.h:836
This header defines various interfaces for pass management in LLVM.
iterator_range< block_iterator > blocks() const
Definition: LoopInfo.h:155
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop&#39;s contents as LLVM&#39;s text IR assembly.
Definition: LoopInfo.cpp:680
block_iterator block_begin() const
Definition: LoopInfo.h:153
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:49
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
static ChildIteratorType child_begin(NodeRef N)
Definition: LoopInfo.h:944
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
Definition: LoopInfo.h:753
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
Definition: LoopInfo.cpp:750
const BasicBlock * getParent() const
Definition: Instruction.h:66
LoopBase(BlockT *BB)
Definition: LoopInfo.h:425
LocRange(DebugLoc Start)
Definition: LoopInfo.h:473
This class builds and contains all of the top-level loop structures in the specified function...
Definition: LoopInfo.h:61