1193323Sed//===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file defines the LoopInfo class that is used to identify natural loops
11198090Srdivacky// and determine the loop depth of various nodes of the CFG.  A natural loop
12198090Srdivacky// has exactly one entry-point, which is called the header. Note that natural
13193323Sed// loops may actually be several loops that share the same header node.
14193323Sed//
15193323Sed// This analysis calculates the nesting structure of loops in a function.  For
16193323Sed// each natural loop identified, this analysis identifies natural loops
17193323Sed// contained entirely within the loop and the basic blocks the make up the loop.
18193323Sed//
19193323Sed// It can calculate on the fly various bits of information, for example:
20193323Sed//
21193323Sed//  * whether there is a preheader for the loop
22193323Sed//  * the number of back edges to the header
23193323Sed//  * whether or not a particular block branches out of the loop
24193323Sed//  * the successor blocks of the loop
25193323Sed//  * the loop depth
26193323Sed//  * etc...
27193323Sed//
28193323Sed//===----------------------------------------------------------------------===//
29193323Sed
30252723Sdim#ifndef LLVM_ANALYSIS_LOOPINFO_H
31252723Sdim#define LLVM_ANALYSIS_LOOPINFO_H
32193323Sed
33218893Sdim#include "llvm/ADT/DenseMap.h"
34226890Sdim#include "llvm/ADT/DenseSet.h"
35193323Sed#include "llvm/ADT/GraphTraits.h"
36193323Sed#include "llvm/ADT/SmallVector.h"
37193323Sed#include "llvm/Analysis/Dominators.h"
38252723Sdim#include "llvm/Pass.h"
39193323Sed#include <algorithm>
40193323Sed
41193323Sednamespace llvm {
42193323Sed
43193323Sedtemplate<typename T>
44245431Sdiminline void RemoveFromVector(std::vector<T*> &V, T *N) {
45193323Sed  typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
46193323Sed  assert(I != V.end() && "N is not in this list!");
47193323Sed  V.erase(I);
48193323Sed}
49193323Sed
50193323Sedclass DominatorTree;
51193323Sedclass LoopInfo;
52198090Srdivackyclass Loop;
53263509Sdimclass MDNode;
54218893Sdimclass PHINode;
55252723Sdimclass raw_ostream;
56198090Srdivackytemplate<class N, class M> class LoopInfoBase;
57198090Srdivackytemplate<class N, class M> class LoopBase;
58193323Sed
59193323Sed//===----------------------------------------------------------------------===//
60193323Sed/// LoopBase class - Instances of this class are used to represent loops that
61193323Sed/// are detected in the flow graph
62193323Sed///
63198090Srdivackytemplate<class BlockT, class LoopT>
64193323Sedclass LoopBase {
65198090Srdivacky  LoopT *ParentLoop;
66193323Sed  // SubLoops - Loops contained entirely within this one.
67198090Srdivacky  std::vector<LoopT *> SubLoops;
68193323Sed
69193323Sed  // Blocks - The list of blocks in this loop.  First entry is the header node.
70193323Sed  std::vector<BlockT*> Blocks;
71193323Sed
72263509Sdim  SmallPtrSet<const BlockT*, 8> DenseBlockSet;
73263509Sdim
74245431Sdim  LoopBase(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
75245431Sdim  const LoopBase<BlockT, LoopT>&
76245431Sdim    operator=(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
77193323Sedpublic:
78193323Sed  /// Loop ctor - This creates an empty loop.
79193323Sed  LoopBase() : ParentLoop(0) {}
80193323Sed  ~LoopBase() {
81193323Sed    for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
82193323Sed      delete SubLoops[i];
83193323Sed  }
84193323Sed
85193323Sed  /// getLoopDepth - Return the nesting level of this loop.  An outer-most
86193323Sed  /// loop has depth 1, for consistency with loop depth values used for basic
87193323Sed  /// blocks, where depth 0 is used for blocks not inside any loops.
88193323Sed  unsigned getLoopDepth() const {
89193323Sed    unsigned D = 1;
90198090Srdivacky    for (const LoopT *CurLoop = ParentLoop; CurLoop;
91193323Sed         CurLoop = CurLoop->ParentLoop)
92193323Sed      ++D;
93193323Sed    return D;
94193323Sed  }
95193323Sed  BlockT *getHeader() const { return Blocks.front(); }
96198090Srdivacky  LoopT *getParentLoop() const { return ParentLoop; }
97193323Sed
98245431Sdim  /// setParentLoop is a raw interface for bypassing addChildLoop.
99245431Sdim  void setParentLoop(LoopT *L) { ParentLoop = L; }
100245431Sdim
101201360Srdivacky  /// contains - Return true if the specified loop is contained within in
102201360Srdivacky  /// this loop.
103193323Sed  ///
104201360Srdivacky  bool contains(const LoopT *L) const {
105201360Srdivacky    if (L == this) return true;
106201360Srdivacky    if (L == 0)    return false;
107201360Srdivacky    return contains(L->getParentLoop());
108201360Srdivacky  }
109226890Sdim
110201360Srdivacky  /// contains - Return true if the specified basic block is in this loop.
111201360Srdivacky  ///
112193323Sed  bool contains(const BlockT *BB) const {
113263509Sdim    return DenseBlockSet.count(BB);
114193323Sed  }
115193323Sed
116201360Srdivacky  /// contains - Return true if the specified instruction is in this loop.
117201360Srdivacky  ///
118201360Srdivacky  template<class InstT>
119201360Srdivacky  bool contains(const InstT *Inst) const {
120201360Srdivacky    return contains(Inst->getParent());
121201360Srdivacky  }
122201360Srdivacky
123193323Sed  /// iterator/begin/end - Return the loops contained entirely within this loop.
124193323Sed  ///
125198090Srdivacky  const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
126245431Sdim  std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
127198090Srdivacky  typedef typename std::vector<LoopT *>::const_iterator iterator;
128245431Sdim  typedef typename std::vector<LoopT *>::const_reverse_iterator
129245431Sdim    reverse_iterator;
130193323Sed  iterator begin() const { return SubLoops.begin(); }
131193323Sed  iterator end() const { return SubLoops.end(); }
132245431Sdim  reverse_iterator rbegin() const { return SubLoops.rbegin(); }
133245431Sdim  reverse_iterator rend() const { return SubLoops.rend(); }
134193323Sed  bool empty() const { return SubLoops.empty(); }
135193323Sed
136193323Sed  /// getBlocks - Get a list of the basic blocks which make up this loop.
137193323Sed  ///
138193323Sed  const std::vector<BlockT*> &getBlocks() const { return Blocks; }
139193323Sed  typedef typename std::vector<BlockT*>::const_iterator block_iterator;
140193323Sed  block_iterator block_begin() const { return Blocks.begin(); }
141193323Sed  block_iterator block_end() const { return Blocks.end(); }
142193323Sed
143226890Sdim  /// getNumBlocks - Get the number of blocks in this loop in constant time.
144226890Sdim  unsigned getNumBlocks() const {
145226890Sdim    return Blocks.size();
146226890Sdim  }
147226890Sdim
148199481Srdivacky  /// isLoopExiting - True if terminator in the block can branch to another
149199481Srdivacky  /// block that is outside of the current loop.
150193323Sed  ///
151198892Srdivacky  bool isLoopExiting(const BlockT *BB) const {
152252723Sdim    typedef GraphTraits<const BlockT*> BlockTraits;
153193323Sed    for (typename BlockTraits::ChildIteratorType SI =
154252723Sdim         BlockTraits::child_begin(BB),
155252723Sdim         SE = BlockTraits::child_end(BB); SI != SE; ++SI) {
156193323Sed      if (!contains(*SI))
157193323Sed        return true;
158193323Sed    }
159193323Sed    return false;
160193323Sed  }
161193323Sed
162193323Sed  /// getNumBackEdges - Calculate the number of back edges to the loop header
163193323Sed  ///
164193323Sed  unsigned getNumBackEdges() const {
165193323Sed    unsigned NumBackEdges = 0;
166193323Sed    BlockT *H = getHeader();
167193323Sed
168193323Sed    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
169193323Sed    for (typename InvBlockTraits::ChildIteratorType I =
170252723Sdim         InvBlockTraits::child_begin(H),
171252723Sdim         E = InvBlockTraits::child_end(H); I != E; ++I)
172193323Sed      if (contains(*I))
173193323Sed        ++NumBackEdges;
174193323Sed
175193323Sed    return NumBackEdges;
176193323Sed  }
177193323Sed
178193323Sed  //===--------------------------------------------------------------------===//
179193323Sed  // APIs for simple analysis of the loop.
180193323Sed  //
181193323Sed  // Note that all of these methods can fail on general loops (ie, there may not
182193323Sed  // be a preheader, etc).  For best success, the loop simplification and
183193323Sed  // induction variable canonicalization pass should be used to normalize loops
184193323Sed  // for easy analysis.  These methods assume canonical loops.
185193323Sed
186193323Sed  /// getExitingBlocks - Return all blocks inside the loop that have successors
187193323Sed  /// outside of the loop.  These are the blocks _inside of the current loop_
188193323Sed  /// which branch out.  The returned list is always unique.
189193323Sed  ///
190245431Sdim  void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
191193323Sed
192193323Sed  /// getExitingBlock - If getExitingBlocks would return exactly one block,
193193323Sed  /// return that block. Otherwise return null.
194245431Sdim  BlockT *getExitingBlock() const;
195193323Sed
196193323Sed  /// getExitBlocks - Return all of the successor blocks of this loop.  These
197193323Sed  /// are the blocks _outside of the current loop_ which are branched to.
198193323Sed  ///
199245431Sdim  void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
200193323Sed
201193323Sed  /// getExitBlock - If getExitBlocks would return exactly one block,
202193323Sed  /// return that block. Otherwise return null.
203245431Sdim  BlockT *getExitBlock() const;
204193323Sed
205212904Sdim  /// Edge type.
206245431Sdim  typedef std::pair<const BlockT*, const BlockT*> Edge;
207212904Sdim
208198090Srdivacky  /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
209245431Sdim  void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
210193323Sed
211193323Sed  /// getLoopPreheader - If there is a preheader for this loop, return it.  A
212193323Sed  /// loop has a preheader if there is only one edge to the header of the loop
213193323Sed  /// from outside of the loop.  If this is the case, the block branching to the
214193323Sed  /// header of the loop is the preheader node.
215193323Sed  ///
216193323Sed  /// This method returns null if there is no preheader for the loop.
217193323Sed  ///
218245431Sdim  BlockT *getLoopPreheader() const;
219210299Sed
220210299Sed  /// getLoopPredecessor - If the given loop's header has exactly one unique
221210299Sed  /// predecessor outside the loop, return it. Otherwise return null.
222210299Sed  /// This is less strict that the loop "preheader" concept, which requires
223210299Sed  /// the predecessor to have exactly one successor.
224210299Sed  ///
225245431Sdim  BlockT *getLoopPredecessor() const;
226193323Sed
227193323Sed  /// getLoopLatch - If there is a single latch block for this loop, return it.
228193323Sed  /// A latch block is a block that contains a branch back to the header.
229245431Sdim  BlockT *getLoopLatch() const;
230193323Sed
231193323Sed  //===--------------------------------------------------------------------===//
232193323Sed  // APIs for updating loop information after changing the CFG
233193323Sed  //
234193323Sed
235193323Sed  /// addBasicBlockToLoop - This method is used by other analyses to update loop
236193323Sed  /// information.  NewBB is set to be a new member of the current loop.
237193323Sed  /// Because of this, it is added as a member of all parent loops, and is added
238193323Sed  /// to the specified LoopInfo object as being in the current basic block.  It
239193323Sed  /// is not valid to replace the loop header with this method.
240193323Sed  ///
241198090Srdivacky  void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
242193323Sed
243193323Sed  /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
244193323Sed  /// the OldChild entry in our children list with NewChild, and updates the
245193323Sed  /// parent pointer of OldChild to be null and the NewChild to be this loop.
246193323Sed  /// This updates the loop depth of the new child.
247245431Sdim  void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
248193323Sed
249193323Sed  /// addChildLoop - Add the specified loop to be a child of this loop.  This
250193323Sed  /// updates the loop depth of the new child.
251193323Sed  ///
252198090Srdivacky  void addChildLoop(LoopT *NewChild) {
253193323Sed    assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
254198090Srdivacky    NewChild->ParentLoop = static_cast<LoopT *>(this);
255193323Sed    SubLoops.push_back(NewChild);
256193323Sed  }
257193323Sed
258193323Sed  /// removeChildLoop - This removes the specified child from being a subloop of
259193323Sed  /// this loop.  The loop is not deleted, as it will presumably be inserted
260193323Sed  /// into another loop.
261198090Srdivacky  LoopT *removeChildLoop(iterator I) {
262193323Sed    assert(I != SubLoops.end() && "Cannot remove end iterator!");
263198090Srdivacky    LoopT *Child = *I;
264193323Sed    assert(Child->ParentLoop == this && "Child is not a child of this loop!");
265193323Sed    SubLoops.erase(SubLoops.begin()+(I-begin()));
266193323Sed    Child->ParentLoop = 0;
267193323Sed    return Child;
268193323Sed  }
269193323Sed
270193323Sed  /// addBlockEntry - This adds a basic block directly to the basic block list.
271193323Sed  /// This should only be used by transformations that create new loops.  Other
272193323Sed  /// transformations should use addBasicBlockToLoop.
273193323Sed  void addBlockEntry(BlockT *BB) {
274193323Sed    Blocks.push_back(BB);
275263509Sdim    DenseBlockSet.insert(BB);
276193323Sed  }
277193323Sed
278263509Sdim  /// reverseBlocks - interface to reverse Blocks[from, end of loop] in this loop
279263509Sdim  void reverseBlock(unsigned from) {
280263509Sdim    std::reverse(Blocks.begin() + from, Blocks.end());
281263509Sdim  }
282263509Sdim
283263509Sdim  /// reserveBlocks- interface to do reserve() for Blocks
284263509Sdim  void reserveBlocks(unsigned size) {
285263509Sdim    Blocks.reserve(size);
286263509Sdim  }
287263509Sdim
288193323Sed  /// moveToHeader - This method is used to move BB (which must be part of this
289193323Sed  /// loop) to be the loop header of the loop (the block that dominates all
290193323Sed  /// others).
291193323Sed  void moveToHeader(BlockT *BB) {
292193323Sed    if (Blocks[0] == BB) return;
293193323Sed    for (unsigned i = 0; ; ++i) {
294193323Sed      assert(i != Blocks.size() && "Loop does not contain BB!");
295193323Sed      if (Blocks[i] == BB) {
296193323Sed        Blocks[i] = Blocks[0];
297193323Sed        Blocks[0] = BB;
298193323Sed        return;
299193323Sed      }
300193323Sed    }
301193323Sed  }
302193323Sed
303193323Sed  /// removeBlockFromLoop - This removes the specified basic block from the
304193323Sed  /// current loop, updating the Blocks as appropriate.  This does not update
305193323Sed  /// the mapping in the LoopInfo class.
306193323Sed  void removeBlockFromLoop(BlockT *BB) {
307193323Sed    RemoveFromVector(Blocks, BB);
308263509Sdim    DenseBlockSet.erase(BB);
309193323Sed  }
310193323Sed
311193323Sed  /// verifyLoop - Verify loop structure
312245431Sdim  void verifyLoop() const;
313198090Srdivacky
314198090Srdivacky  /// verifyLoop - Verify loop structure of this loop and all nested loops.
315245431Sdim  void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
316198090Srdivacky
317245431Sdim  void print(raw_ostream &OS, unsigned Depth = 0) const;
318193323Sed
319198090Srdivackyprotected:
320198090Srdivacky  friend class LoopInfoBase<BlockT, LoopT>;
321193323Sed  explicit LoopBase(BlockT *BB) : ParentLoop(0) {
322193323Sed    Blocks.push_back(BB);
323263509Sdim    DenseBlockSet.insert(BB);
324193323Sed  }
325193323Sed};
326193323Sed
327212904Sdimtemplate<class BlockT, class LoopT>
328212904Sdimraw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
329212904Sdim  Loop.print(OS);
330212904Sdim  return OS;
331212904Sdim}
332212904Sdim
333245431Sdim// Implementation in LoopInfoImpl.h
334245431Sdim#ifdef __GNUC__
335245431Sdim__extension__ extern template class LoopBase<BasicBlock, Loop>;
336245431Sdim#endif
337245431Sdim
338198090Srdivackyclass Loop : public LoopBase<BasicBlock, Loop> {
339198090Srdivackypublic:
340198090Srdivacky  Loop() {}
341193323Sed
342198090Srdivacky  /// isLoopInvariant - Return true if the specified value is loop invariant
343198090Srdivacky  ///
344198090Srdivacky  bool isLoopInvariant(Value *V) const;
345198090Srdivacky
346218893Sdim  /// hasLoopInvariantOperands - Return true if all the operands of the
347226890Sdim  /// specified instruction are loop invariant.
348218893Sdim  bool hasLoopInvariantOperands(Instruction *I) const;
349198090Srdivacky
350198090Srdivacky  /// makeLoopInvariant - If the given value is an instruction inside of the
351198090Srdivacky  /// loop and it can be hoisted, do so to make it trivially loop-invariant.
352198090Srdivacky  /// Return true if the value after any hoisting is loop invariant. This
353198090Srdivacky  /// function can be used as a slightly more aggressive replacement for
354198090Srdivacky  /// isLoopInvariant.
355198090Srdivacky  ///
356198090Srdivacky  /// If InsertPt is specified, it is the point to hoist instructions to.
357198090Srdivacky  /// If null, the terminator of the loop preheader is used.
358198090Srdivacky  ///
359198090Srdivacky  bool makeLoopInvariant(Value *V, bool &Changed,
360198090Srdivacky                         Instruction *InsertPt = 0) const;
361198090Srdivacky
362198090Srdivacky  /// makeLoopInvariant - If the given instruction is inside of the
363198090Srdivacky  /// loop and it can be hoisted, do so to make it trivially loop-invariant.
364198090Srdivacky  /// Return true if the instruction after any hoisting is loop invariant. This
365198090Srdivacky  /// function can be used as a slightly more aggressive replacement for
366198090Srdivacky  /// isLoopInvariant.
367198090Srdivacky  ///
368198090Srdivacky  /// If InsertPt is specified, it is the point to hoist instructions to.
369198090Srdivacky  /// If null, the terminator of the loop preheader is used.
370198090Srdivacky  ///
371198090Srdivacky  bool makeLoopInvariant(Instruction *I, bool &Changed,
372198090Srdivacky                         Instruction *InsertPt = 0) const;
373198090Srdivacky
374198090Srdivacky  /// getCanonicalInductionVariable - Check to see if the loop has a canonical
375198090Srdivacky  /// induction variable: an integer recurrence that starts at 0 and increments
376198090Srdivacky  /// by one each time through the loop.  If so, return the phi node that
377198090Srdivacky  /// corresponds to it.
378198090Srdivacky  ///
379198090Srdivacky  /// The IndVarSimplify pass transforms loops to have a canonical induction
380198090Srdivacky  /// variable.
381198090Srdivacky  ///
382198090Srdivacky  PHINode *getCanonicalInductionVariable() const;
383198090Srdivacky
384198090Srdivacky  /// isLCSSAForm - Return true if the Loop is in LCSSA form
385205218Srdivacky  bool isLCSSAForm(DominatorTree &DT) const;
386198090Srdivacky
387198090Srdivacky  /// isLoopSimplifyForm - Return true if the Loop is in the form that
388198090Srdivacky  /// the LoopSimplify form transforms loops to, which is sometimes called
389198090Srdivacky  /// normal form.
390198090Srdivacky  bool isLoopSimplifyForm() const;
391198090Srdivacky
392235633Sdim  /// isSafeToClone - Return true if the loop body is safe to clone in practice.
393235633Sdim  bool isSafeToClone() const;
394235633Sdim
395252723Sdim  /// Returns true if the loop is annotated parallel.
396252723Sdim  ///
397252723Sdim  /// A parallel loop can be assumed to not contain any dependencies between
398252723Sdim  /// iterations by the compiler. That is, any loop-carried dependency checking
399252723Sdim  /// can be skipped completely when parallelizing the loop on the target
400252723Sdim  /// machine. Thus, if the parallel loop information originates from the
401252723Sdim  /// programmer, e.g. via the OpenMP parallel for pragma, it is the
402252723Sdim  /// programmer's responsibility to ensure there are no loop-carried
403252723Sdim  /// dependencies. The final execution order of the instructions across
404252723Sdim  /// iterations is not guaranteed, thus, the end result might or might not
405252723Sdim  /// implement actual concurrent execution of instructions across multiple
406252723Sdim  /// iterations.
407252723Sdim  bool isAnnotatedParallel() const;
408252723Sdim
409263509Sdim  /// Return the llvm.loop loop id metadata node for this loop if it is present.
410263509Sdim  ///
411263509Sdim  /// If this loop contains the same llvm.loop metadata on each branch to the
412263509Sdim  /// header then the node is returned. If any latch instruction does not
413263509Sdim  /// contain llvm.loop or or if multiple latches contain different nodes then
414263509Sdim  /// 0 is returned.
415263509Sdim  MDNode *getLoopID() const;
416263509Sdim  /// Set the llvm.loop loop id metadata for this loop.
417263509Sdim  ///
418263509Sdim  /// The LoopID metadata node will be added to each terminator instruction in
419263509Sdim  /// the loop that branches to the loop header.
420263509Sdim  ///
421263509Sdim  /// The LoopID metadata node should have one or more operands and the first
422263509Sdim  /// operand should should be the node itself.
423263509Sdim  void setLoopID(MDNode *LoopID) const;
424263509Sdim
425199481Srdivacky  /// hasDedicatedExits - Return true if no exit block for the loop
426199481Srdivacky  /// has a predecessor that is outside the loop.
427199481Srdivacky  bool hasDedicatedExits() const;
428199481Srdivacky
429226890Sdim  /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
430198090Srdivacky  /// These are the blocks _outside of the current loop_ which are branched to.
431200581Srdivacky  /// This assumes that loop exits are in canonical form.
432198090Srdivacky  ///
433198090Srdivacky  void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
434198090Srdivacky
435198090Srdivacky  /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
436198090Srdivacky  /// block, return that block. Otherwise return null.
437198090Srdivacky  BasicBlock *getUniqueExitBlock() const;
438198090Srdivacky
439202375Srdivacky  void dump() const;
440226890Sdim
441198090Srdivackyprivate:
442198090Srdivacky  friend class LoopInfoBase<BasicBlock, Loop>;
443198090Srdivacky  explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
444198090Srdivacky};
445198090Srdivacky
446193323Sed//===----------------------------------------------------------------------===//
447193323Sed/// LoopInfo - This class builds and contains all of the top level loop
448193323Sed/// structures in the specified function.
449193323Sed///
450193323Sed
451198090Srdivackytemplate<class BlockT, class LoopT>
452193323Sedclass LoopInfoBase {
453193323Sed  // BBMap - Mapping of basic blocks to the inner most loop they occur in
454218893Sdim  DenseMap<BlockT *, LoopT *> BBMap;
455198090Srdivacky  std::vector<LoopT *> TopLevelLoops;
456198090Srdivacky  friend class LoopBase<BlockT, LoopT>;
457226890Sdim  friend class LoopInfo;
458195340Sed
459245431Sdim  void operator=(const LoopInfoBase &) LLVM_DELETED_FUNCTION;
460245431Sdim  LoopInfoBase(const LoopInfo &) LLVM_DELETED_FUNCTION;
461193323Sedpublic:
462193323Sed  LoopInfoBase() { }
463193323Sed  ~LoopInfoBase() { releaseMemory(); }
464226890Sdim
465193323Sed  void releaseMemory() {
466198090Srdivacky    for (typename std::vector<LoopT *>::iterator I =
467193323Sed         TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
468193323Sed      delete *I;   // Delete all of the loops...
469193323Sed
470193323Sed    BBMap.clear();                           // Reset internal state of analysis
471193323Sed    TopLevelLoops.clear();
472193323Sed  }
473226890Sdim
474193323Sed  /// iterator/begin/end - The interface to the top-level loops in the current
475193323Sed  /// function.
476193323Sed  ///
477198090Srdivacky  typedef typename std::vector<LoopT *>::const_iterator iterator;
478245431Sdim  typedef typename std::vector<LoopT *>::const_reverse_iterator
479245431Sdim    reverse_iterator;
480193323Sed  iterator begin() const { return TopLevelLoops.begin(); }
481193323Sed  iterator end() const { return TopLevelLoops.end(); }
482245431Sdim  reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
483245431Sdim  reverse_iterator rend() const { return TopLevelLoops.rend(); }
484193323Sed  bool empty() const { return TopLevelLoops.empty(); }
485226890Sdim
486193323Sed  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
487193323Sed  /// block is in no loop (for example the entry node), null is returned.
488193323Sed  ///
489198090Srdivacky  LoopT *getLoopFor(const BlockT *BB) const {
490235633Sdim    return BBMap.lookup(const_cast<BlockT*>(BB));
491193323Sed  }
492226890Sdim
493193323Sed  /// operator[] - same as getLoopFor...
494193323Sed  ///
495198090Srdivacky  const LoopT *operator[](const BlockT *BB) const {
496193323Sed    return getLoopFor(BB);
497193323Sed  }
498226890Sdim
499193323Sed  /// getLoopDepth - Return the loop nesting level of the specified block.  A
500193323Sed  /// depth of 0 means the block is not inside any loop.
501193323Sed  ///
502193323Sed  unsigned getLoopDepth(const BlockT *BB) const {
503198090Srdivacky    const LoopT *L = getLoopFor(BB);
504193323Sed    return L ? L->getLoopDepth() : 0;
505193323Sed  }
506193323Sed
507193323Sed  // isLoopHeader - True if the block is a loop header node
508193323Sed  bool isLoopHeader(BlockT *BB) const {
509198090Srdivacky    const LoopT *L = getLoopFor(BB);
510193323Sed    return L && L->getHeader() == BB;
511193323Sed  }
512226890Sdim
513193323Sed  /// removeLoop - This removes the specified top-level loop from this loop info
514193323Sed  /// object.  The loop is not deleted, as it will presumably be inserted into
515193323Sed  /// another loop.
516198090Srdivacky  LoopT *removeLoop(iterator I) {
517193323Sed    assert(I != end() && "Cannot remove end iterator!");
518198090Srdivacky    LoopT *L = *I;
519193323Sed    assert(L->getParentLoop() == 0 && "Not a top-level loop!");
520193323Sed    TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
521193323Sed    return L;
522193323Sed  }
523226890Sdim
524193323Sed  /// changeLoopFor - Change the top-level loop that contains BB to the
525193323Sed  /// specified loop.  This should be used by transformations that restructure
526193323Sed  /// the loop hierarchy tree.
527198090Srdivacky  void changeLoopFor(BlockT *BB, LoopT *L) {
528226890Sdim    if (!L) {
529235633Sdim      BBMap.erase(BB);
530226890Sdim      return;
531226890Sdim    }
532226890Sdim    BBMap[BB] = L;
533193323Sed  }
534226890Sdim
535193323Sed  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
536193323Sed  /// list with the indicated loop.
537198090Srdivacky  void changeTopLevelLoop(LoopT *OldLoop,
538198090Srdivacky                          LoopT *NewLoop) {
539198090Srdivacky    typename std::vector<LoopT *>::iterator I =
540193323Sed                 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
541193323Sed    assert(I != TopLevelLoops.end() && "Old loop not at top level!");
542193323Sed    *I = NewLoop;
543193323Sed    assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
544193323Sed           "Loops already embedded into a subloop!");
545193323Sed  }
546226890Sdim
547193323Sed  /// addTopLevelLoop - This adds the specified loop to the collection of
548193323Sed  /// top-level loops.
549198090Srdivacky  void addTopLevelLoop(LoopT *New) {
550193323Sed    assert(New->getParentLoop() == 0 && "Loop already in subloop!");
551193323Sed    TopLevelLoops.push_back(New);
552193323Sed  }
553226890Sdim
554193323Sed  /// removeBlock - This method completely removes BB from all data structures,
555193323Sed  /// including all of the Loop objects it is nested in and our mapping from
556193323Sed  /// BasicBlocks to loops.
557193323Sed  void removeBlock(BlockT *BB) {
558218893Sdim    typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
559193323Sed    if (I != BBMap.end()) {
560198090Srdivacky      for (LoopT *L = I->second; L; L = L->getParentLoop())
561193323Sed        L->removeBlockFromLoop(BB);
562193323Sed
563193323Sed      BBMap.erase(I);
564193323Sed    }
565193323Sed  }
566226890Sdim
567193323Sed  // Internals
568226890Sdim
569198090Srdivacky  static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
570198090Srdivacky                                      const LoopT *ParentLoop) {
571193323Sed    if (SubLoop == 0) return true;
572193323Sed    if (SubLoop == ParentLoop) return false;
573193323Sed    return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
574193323Sed  }
575226890Sdim
576245431Sdim  /// Create the loop forest using a stable algorithm.
577245431Sdim  void Analyze(DominatorTreeBase<BlockT> &DomTree);
578193323Sed
579193323Sed  // Debugging
580226890Sdim
581245431Sdim  void print(raw_ostream &OS) const;
582193323Sed};
583193323Sed
584245431Sdim// Implementation in LoopInfoImpl.h
585245431Sdim#ifdef __GNUC__
586245431Sdim__extension__ extern template class LoopInfoBase<BasicBlock, Loop>;
587245431Sdim#endif
588245431Sdim
589193323Sedclass LoopInfo : public FunctionPass {
590198090Srdivacky  LoopInfoBase<BasicBlock, Loop> LI;
591198090Srdivacky  friend class LoopBase<BasicBlock, Loop>;
592195340Sed
593245431Sdim  void operator=(const LoopInfo &) LLVM_DELETED_FUNCTION;
594245431Sdim  LoopInfo(const LoopInfo &) LLVM_DELETED_FUNCTION;
595193323Sedpublic:
596193323Sed  static char ID; // Pass identification, replacement for typeid
597193323Sed
598218893Sdim  LoopInfo() : FunctionPass(ID) {
599218893Sdim    initializeLoopInfoPass(*PassRegistry::getPassRegistry());
600218893Sdim  }
601193323Sed
602198090Srdivacky  LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
603193323Sed
604193323Sed  /// iterator/begin/end - The interface to the top-level loops in the current
605193323Sed  /// function.
606193323Sed  ///
607198090Srdivacky  typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
608245431Sdim  typedef LoopInfoBase<BasicBlock, Loop>::reverse_iterator reverse_iterator;
609195340Sed  inline iterator begin() const { return LI.begin(); }
610195340Sed  inline iterator end() const { return LI.end(); }
611245431Sdim  inline reverse_iterator rbegin() const { return LI.rbegin(); }
612245431Sdim  inline reverse_iterator rend() const { return LI.rend(); }
613195340Sed  bool empty() const { return LI.empty(); }
614193323Sed
615193323Sed  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
616193323Sed  /// block is in no loop (for example the entry node), null is returned.
617193323Sed  ///
618193323Sed  inline Loop *getLoopFor(const BasicBlock *BB) const {
619195340Sed    return LI.getLoopFor(BB);
620193323Sed  }
621193323Sed
622193323Sed  /// operator[] - same as getLoopFor...
623193323Sed  ///
624193323Sed  inline const Loop *operator[](const BasicBlock *BB) const {
625195340Sed    return LI.getLoopFor(BB);
626193323Sed  }
627193323Sed
628193323Sed  /// getLoopDepth - Return the loop nesting level of the specified block.  A
629193323Sed  /// depth of 0 means the block is not inside any loop.
630193323Sed  ///
631193323Sed  inline unsigned getLoopDepth(const BasicBlock *BB) const {
632195340Sed    return LI.getLoopDepth(BB);
633193323Sed  }
634193323Sed
635193323Sed  // isLoopHeader - True if the block is a loop header node
636193323Sed  inline bool isLoopHeader(BasicBlock *BB) const {
637195340Sed    return LI.isLoopHeader(BB);
638193323Sed  }
639193323Sed
640193323Sed  /// runOnFunction - Calculate the natural loop information.
641193323Sed  ///
642193323Sed  virtual bool runOnFunction(Function &F);
643193323Sed
644198090Srdivacky  virtual void verifyAnalysis() const;
645198090Srdivacky
646195340Sed  virtual void releaseMemory() { LI.releaseMemory(); }
647193323Sed
648198090Srdivacky  virtual void print(raw_ostream &O, const Module* M = 0) const;
649226890Sdim
650193323Sed  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
651193323Sed
652193323Sed  /// removeLoop - This removes the specified top-level loop from this loop info
653193323Sed  /// object.  The loop is not deleted, as it will presumably be inserted into
654193323Sed  /// another loop.
655195340Sed  inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
656193323Sed
657193323Sed  /// changeLoopFor - Change the top-level loop that contains BB to the
658193323Sed  /// specified loop.  This should be used by transformations that restructure
659193323Sed  /// the loop hierarchy tree.
660193323Sed  inline void changeLoopFor(BasicBlock *BB, Loop *L) {
661195340Sed    LI.changeLoopFor(BB, L);
662193323Sed  }
663193323Sed
664193323Sed  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
665193323Sed  /// list with the indicated loop.
666193323Sed  inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
667195340Sed    LI.changeTopLevelLoop(OldLoop, NewLoop);
668193323Sed  }
669193323Sed
670193323Sed  /// addTopLevelLoop - This adds the specified loop to the collection of
671193323Sed  /// top-level loops.
672193323Sed  inline void addTopLevelLoop(Loop *New) {
673195340Sed    LI.addTopLevelLoop(New);
674193323Sed  }
675193323Sed
676193323Sed  /// removeBlock - This method completely removes BB from all data structures,
677193323Sed  /// including all of the Loop objects it is nested in and our mapping from
678193323Sed  /// BasicBlocks to loops.
679193323Sed  void removeBlock(BasicBlock *BB) {
680195340Sed    LI.removeBlock(BB);
681193323Sed  }
682218893Sdim
683226890Sdim  /// updateUnloop - Update LoopInfo after removing the last backedge from a
684226890Sdim  /// loop--now the "unloop". This updates the loop forest and parent loops for
685226890Sdim  /// each block so that Unloop is no longer referenced, but the caller must
686226890Sdim  /// actually delete the Unloop object.
687226890Sdim  void updateUnloop(Loop *Unloop);
688226890Sdim
689218893Sdim  /// replacementPreservesLCSSAForm - Returns true if replacing From with To
690218893Sdim  /// everywhere is guaranteed to preserve LCSSA form.
691218893Sdim  bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
692218893Sdim    // Preserving LCSSA form is only problematic if the replacing value is an
693218893Sdim    // instruction.
694218893Sdim    Instruction *I = dyn_cast<Instruction>(To);
695218893Sdim    if (!I) return true;
696218893Sdim    // If both instructions are defined in the same basic block then replacement
697218893Sdim    // cannot break LCSSA form.
698218893Sdim    if (I->getParent() == From->getParent())
699218893Sdim      return true;
700218893Sdim    // If the instruction is not defined in a loop then it can safely replace
701218893Sdim    // anything.
702218893Sdim    Loop *ToLoop = getLoopFor(I->getParent());
703218893Sdim    if (!ToLoop) return true;
704218893Sdim    // If the replacing instruction is defined in the same loop as the original
705218893Sdim    // instruction, or in a loop that contains it as an inner loop, then using
706218893Sdim    // it as a replacement will not break LCSSA form.
707218893Sdim    return ToLoop->contains(getLoopFor(From->getParent()));
708218893Sdim  }
709193323Sed};
710193323Sed
711193323Sed
712193323Sed// Allow clients to walk the list of nested loops...
713193323Sedtemplate <> struct GraphTraits<const Loop*> {
714193323Sed  typedef const Loop NodeType;
715195340Sed  typedef LoopInfo::iterator ChildIteratorType;
716193323Sed
717193323Sed  static NodeType *getEntryNode(const Loop *L) { return L; }
718193323Sed  static inline ChildIteratorType child_begin(NodeType *N) {
719193323Sed    return N->begin();
720193323Sed  }
721193323Sed  static inline ChildIteratorType child_end(NodeType *N) {
722193323Sed    return N->end();
723193323Sed  }
724193323Sed};
725193323Sed
726193323Sedtemplate <> struct GraphTraits<Loop*> {
727193323Sed  typedef Loop NodeType;
728195340Sed  typedef LoopInfo::iterator ChildIteratorType;
729193323Sed
730193323Sed  static NodeType *getEntryNode(Loop *L) { return L; }
731193323Sed  static inline ChildIteratorType child_begin(NodeType *N) {
732193323Sed    return N->begin();
733193323Sed  }
734193323Sed  static inline ChildIteratorType child_end(NodeType *N) {
735193323Sed    return N->end();
736193323Sed  }
737193323Sed};
738193323Sed
739193323Sed} // End llvm namespace
740193323Sed
741193323Sed#endif
742