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