LoopInfo.h revision 45cfe545ec8177262dabc70580ce05feaa1c3880
1b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//
3fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius//                     The LLVM Compiler Infrastructure
4b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//
5b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru// This file is distributed under the University of Illinois Open Source
6b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru// License. See LICENSE.TXT for details.
7b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//
8b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//===----------------------------------------------------------------------===//
9c69afcec261fc345fda8daf46f0ea6b4351dc777Jean-Baptiste Queru//
10fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius// This file defines the LoopInfo class that is used to identify natural loops
11c69afcec261fc345fda8daf46f0ea6b4351dc777Jean-Baptiste Queru// and determine the loop depth of various nodes of the CFG.  Note that natural
12c69afcec261fc345fda8daf46f0ea6b4351dc777Jean-Baptiste Queru// loops may actually be several loops that share the same header node.
13c69afcec261fc345fda8daf46f0ea6b4351dc777Jean-Baptiste Queru//
14b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru// This analysis calculates the nesting structure of loops in a function.  For
15b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru// each natural loop identified, this analysis identifies natural loops
16b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru// contained entirely within the loop and the basic blocks the make up the loop.
17b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//
18b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru// It can calculate on the fly various bits of information, for example:
19b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//
20b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//  * whether there is a preheader for the loop
21b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//  * the number of back edges to the header
22b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//  * whether or not a particular block branches out of the loop
23b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//  * the successor blocks of the loop
24b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//  * the loop depth
25b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//  * the trip count
26b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//  * etc...
27b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//
28b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//===----------------------------------------------------------------------===//
29b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
30b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#ifndef LLVM_ANALYSIS_LOOP_INFO_H
31b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#define LLVM_ANALYSIS_LOOP_INFO_H
32b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
33b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#include "llvm/Pass.h"
34b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#include "llvm/ADT/DepthFirstIterator.h"
35b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#include "llvm/ADT/GraphTraits.h"
36b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#include "llvm/ADT/SmallVector.h"
37b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#include "llvm/Analysis/Dominators.h"
38b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#include "llvm/Support/CFG.h"
39b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#include "llvm/Support/Streams.h"
40b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#include <algorithm>
41b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#include <ostream>
42b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
43b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Querunamespace llvm {
44b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
45b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Querutemplate<typename T>
46b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Querustatic void RemoveFromVector(std::vector<T*> &V, T *N) {
47b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
48b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  assert(I != V.end() && "N is not in this list!");
49b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  V.erase(I);
50b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru}
51b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
52b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queruclass DominatorTree;
53b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queruclass LoopInfo;
54b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queruclass Loop;
55b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Querutemplate<class N, class M> class LoopInfoBase;
56b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Querutemplate<class N, class M> class LoopBase;
57fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
58b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru//===----------------------------------------------------------------------===//
59b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru/// LoopBase class - Instances of this class are used to represent loops that
60b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru/// are detected in the flow graph
61b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru///
62b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Querutemplate<class BlockT, class LoopT>
63b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queruclass LoopBase {
64b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  LoopT *ParentLoop;
65b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // SubLoops - Loops contained entirely within this one.
66b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  std::vector<LoopT *> SubLoops;
67b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
68fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  // Blocks - The list of blocks in this loop.  First entry is the header node.
69fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  std::vector<BlockT*> Blocks;
70b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
71b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // DO NOT IMPLEMENT
72b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  LoopBase(const LoopBase<BlockT, LoopT> &);
73b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // DO NOT IMPLEMENT
74fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
75fceb39872958b9fa2505e63f8b8699a9e0f882f4ccorneliuspublic:
76fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// Loop ctor - This creates an empty loop.
77b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  LoopBase() : ParentLoop(0) {}
78b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ~LoopBase() {
79b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
80b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      delete SubLoops[i];
81b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
82b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
83b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getLoopDepth - Return the nesting level of this loop.  An outer-most
84b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// loop has depth 1, for consistency with loop depth values used for basic
85fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// blocks, where depth 0 is used for blocks not inside any loops.
86fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  unsigned getLoopDepth() const {
87fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    unsigned D = 1;
88fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    for (const LoopT *CurLoop = ParentLoop; CurLoop;
89fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius         CurLoop = CurLoop->ParentLoop)
90b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      ++D;
91b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return D;
92fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
93b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  BlockT *getHeader() const { return Blocks.front(); }
94b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  LoopT *getParentLoop() const { return ParentLoop; }
95b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
96b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// contains - Return true if the specified basic block is in this loop
97fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  ///
98b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  bool contains(const BlockT *BB) const {
99b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return std::find(block_begin(), block_end(), BB) != block_end();
100b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
101fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
102b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// iterator/begin/end - Return the loops contained entirely within this loop.
103b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
104fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
105fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  typedef typename std::vector<LoopT *>::const_iterator iterator;
106b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  iterator begin() const { return SubLoops.begin(); }
107b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  iterator end() const { return SubLoops.end(); }
108b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  bool empty() const { return SubLoops.empty(); }
109b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
110fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// getBlocks - Get a list of the basic blocks which make up this loop.
111b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
112b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  const std::vector<BlockT*> &getBlocks() const { return Blocks; }
113b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  typedef typename std::vector<BlockT*>::const_iterator block_iterator;
114b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  block_iterator block_begin() const { return Blocks.begin(); }
115b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  block_iterator block_end() const { return Blocks.end(); }
116b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
117b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// isLoopExit - True if terminator in the block can branch to another block
118b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// that is outside of the current loop.
119b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
120b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  bool isLoopExit(const BlockT *BB) const {
121b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    typedef GraphTraits<BlockT*> BlockTraits;
122b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (typename BlockTraits::ChildIteratorType SI =
123b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru         BlockTraits::child_begin(const_cast<BlockT*>(BB)),
124b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru         SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
125b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      if (!contains(*SI))
126b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        return true;
127dbc22bd174be483711cea006f3189d8289835830ccornelius    }
128b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return false;
129b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
130b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
131b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getNumBackEdges - Calculate the number of back edges to the loop header
132b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
133b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  unsigned getNumBackEdges() const {
134b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    unsigned NumBackEdges = 0;
135b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    BlockT *H = getHeader();
136b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
137b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
138b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (typename InvBlockTraits::ChildIteratorType I =
139b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru         InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
140b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru         E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
141b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      if (contains(*I))
142b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        ++NumBackEdges;
143b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
144b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return NumBackEdges;
145b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
146b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
147b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  //===--------------------------------------------------------------------===//
148b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // APIs for simple analysis of the loop.
149b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  //
150b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // Note that all of these methods can fail on general loops (ie, there may not
151b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // be a preheader, etc).  For best success, the loop simplification and
152b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // induction variable canonicalization pass should be used to normalize loops
153dbc22bd174be483711cea006f3189d8289835830ccornelius  // for easy analysis.  These methods assume canonical loops.
154b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
155b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getExitingBlocks - Return all blocks inside the loop that have successors
156b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// outside of the loop.  These are the blocks _inside of the current loop_
157b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// which branch out.  The returned list is always unique.
158b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
159b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
160b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // Sort the blocks vector so that we can use binary search to do quick
161b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // lookups.
162b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
163fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    std::sort(LoopBBs.begin(), LoopBBs.end());
164fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
165fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    typedef GraphTraits<BlockT*> BlockTraits;
166fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
167fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      for (typename BlockTraits::ChildIteratorType I =
168fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
169fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          I != E; ++I)
170fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
171fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          // Not in current loop? It must be an exit block.
172fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          ExitingBlocks.push_back(*BI);
173b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          break;
174b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        }
175b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
176b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
177b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getExitingBlock - If getExitingBlocks would return exactly one block,
178b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// return that block. Otherwise return null.
179b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  BlockT *getExitingBlock() const {
180b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    SmallVector<BlockT*, 8> ExitingBlocks;
181b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    getExitingBlocks(ExitingBlocks);
182b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (ExitingBlocks.size() == 1)
183b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      return ExitingBlocks[0];
184b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return 0;
185fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
186b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
187b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getExitBlocks - Return all of the successor blocks of this loop.  These
188b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// are the blocks _outside of the current loop_ which are branched to.
189b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
190fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
191b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // Sort the blocks vector so that we can use binary search to do quick
192b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // lookups.
193b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
194b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    std::sort(LoopBBs.begin(), LoopBBs.end());
195b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
196b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    typedef GraphTraits<BlockT*> BlockTraits;
197b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
198b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      for (typename BlockTraits::ChildIteratorType I =
199b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
200b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru           I != E; ++I)
201b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
202b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          // Not in current loop? It must be an exit block.
203b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          ExitBlocks.push_back(*I);
204b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
205b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
206b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getExitBlock - If getExitBlocks would return exactly one block,
207b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// return that block. Otherwise return null.
208b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  BlockT *getExitBlock() const {
209b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    SmallVector<BlockT*, 8> ExitBlocks;
210fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    getExitBlocks(ExitBlocks);
211b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (ExitBlocks.size() == 1)
212b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      return ExitBlocks[0];
213b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return 0;
214b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
215b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
216b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
217b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// (Modelled after getExitingBlocks().)
218b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  typedef std::pair<const BlockT*,const BlockT*> Edge;
219b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
220b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // Sort the blocks vector so that we can use binary search to do quick
221b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // lookups.
222b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
223b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    std::sort(LoopBBs.begin(), LoopBBs.end());
22454dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius
22554dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius    typedef GraphTraits<BlockT*> BlockTraits;
226b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
227b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      for (typename BlockTraits::ChildIteratorType I =
228b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
229b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru           I != E; ++I)
230b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
231b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          // Not in current loop? It must be an exit block.
232b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          ExitEdges.push_back(std::make_pair(*BI, *I));
233b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
234b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
235b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
236b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// These are the blocks _outside of the current loop_ which are branched to.
237b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// This assumes that loop is in canonical form.
238b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
239b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void getUniqueExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
240b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // Sort the blocks vector so that we can use binary search to do quick
241b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // lookups.
242b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
243b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    std::sort(LoopBBs.begin(), LoopBBs.end());
244b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
245b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    std::vector<BlockT*> switchExitBlocks;
246b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
247b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
248b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
249b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      BlockT *current = *BI;
250b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      switchExitBlocks.clear();
251b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
252b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      typedef GraphTraits<BlockT*> BlockTraits;
253b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
254b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      for (typename BlockTraits::ChildIteratorType I =
25554dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
25654dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius           I != E; ++I) {
257b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
258b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      // If block is inside the loop then it is not a exit block.
259b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          continue;
260b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
261b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        typename InvBlockTraits::ChildIteratorType PI =
262b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                                                InvBlockTraits::child_begin(*I);
263b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        BlockT *firstPred = *PI;
264b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
265b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // If current basic block is this exit block's first predecessor
266b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // then only insert exit block in to the output ExitBlocks vector.
267b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // This ensures that same exit block is not inserted twice into
268b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // ExitBlocks vector.
269b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        if (current != firstPred)
270b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          continue;
271fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
272fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        // If a terminator has more then two successors, for example SwitchInst,
273b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // then it is possible that there are multiple edges from current block
274b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // to one exit block.
275b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        if (std::distance(BlockTraits::child_begin(current),
276b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                          BlockTraits::child_end(current)) <= 2) {
277b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          ExitBlocks.push_back(*I);
278b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          continue;
279b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        }
280b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
281b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // In case of multiple edges from current block to exit block, collect
282b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
283b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // duplicate edges.
284b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
285b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru            == switchExitBlocks.end()) {
286b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          switchExitBlocks.push_back(*I);
287b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          ExitBlocks.push_back(*I);
288fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        }
289fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      }
290fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    }
291b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
292b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
293b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
294b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// block, return that block. Otherwise return null.
295b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  BlockT *getUniqueExitBlock() const {
296b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    SmallVector<BlockT*, 8> UniqueExitBlocks;
297b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    getUniqueExitBlocks(UniqueExitBlocks);
298b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (UniqueExitBlocks.size() == 1)
299b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      return UniqueExitBlocks[0];
300b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return 0;
301b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
302b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
303b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getLoopPreheader - If there is a preheader for this loop, return it.  A
304b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// loop has a preheader if there is only one edge to the header of the loop
305b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// from outside of the loop.  If this is the case, the block branching to the
306b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// header of the loop is the preheader node.
307b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
308b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// This method returns null if there is no preheader for the loop.
309fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  ///
310fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  BlockT *getLoopPreheader() const {
311b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // Keep track of nodes outside the loop branching to the header...
312b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    BlockT *Out = 0;
313b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
314b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Loop over the predecessors of the header node...
315b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    BlockT *Header = getHeader();
316b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    typedef GraphTraits<BlockT*> BlockTraits;
317b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
318b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    for (typename InvBlockTraits::ChildIteratorType PI =
319b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru         InvBlockTraits::child_begin(Header),
320b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru         PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
32150294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho      if (!contains(*PI)) {     // If the block is not in the loop...
322b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        if (Out && Out != *PI)
323b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          return 0;             // Multiple predecessors outside the loop
324b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        Out = *PI;
325b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      }
326b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
327b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Make sure there is only one exit out of the preheader.
328fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    assert(Out && "Header of loop has no predecessors from outside loop?");
329fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
330fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    ++SI;
331fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    if (SI != BlockTraits::child_end(Out))
332fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      return 0;  // Multiple exits from the block, must not be a preheader.
333fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
334fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    // If there is exactly one preheader, return it.  If there was zero, then
335fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    // Out is still null.
336fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    return Out;
337fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
338fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
339fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// getLoopLatch - If there is a single latch block for this loop, return it.
340fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// A latch block is a block that contains a branch back to the header.
341fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// A loop header in normal form has two edges into it: one from a preheader
342fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// and one from a latch block.
343fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  BlockT *getLoopLatch() const {
344fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    BlockT *Header = getHeader();
345b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
346b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    typename InvBlockTraits::ChildIteratorType PI =
347b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                                            InvBlockTraits::child_begin(Header);
348b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    typename InvBlockTraits::ChildIteratorType PE =
349b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                                              InvBlockTraits::child_end(Header);
350b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (PI == PE) return 0;  // no preds?
351b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
352b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    BlockT *Latch = 0;
353b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (contains(*PI))
35454dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius      Latch = *PI;
355b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    ++PI;
356b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (PI == PE) return 0;  // only one pred?
357b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
358b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (contains(*PI)) {
359b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      if (Latch) return 0;  // multiple backedges
360b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      Latch = *PI;
361b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    }
362b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    ++PI;
363b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (PI != PE) return 0;  // more than two preds
364b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
365b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return Latch;
366b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
367b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
368b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  //===--------------------------------------------------------------------===//
369b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // APIs for updating loop information after changing the CFG
370b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  //
37154dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius
372b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// addBasicBlockToLoop - This method is used by other analyses to update loop
373b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// information.  NewBB is set to be a new member of the current loop.
374b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// Because of this, it is added as a member of all parent loops, and is added
375b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// to the specified LoopInfo object as being in the current basic block.  It
376b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// is not valid to replace the loop header with this method.
377b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
378b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
379b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
380b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
381b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// the OldChild entry in our children list with NewChild, and updates the
382b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// parent pointer of OldChild to be null and the NewChild to be this loop.
383fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// This updates the loop depth of the new child.
384b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void replaceChildLoopWith(LoopT *OldChild,
385b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                            LoopT *NewChild) {
386b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    assert(OldChild->ParentLoop == this && "This loop is already broken!");
387b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
388b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    typename std::vector<LoopT *>::iterator I =
389b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                          std::find(SubLoops.begin(), SubLoops.end(), OldChild);
390b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    assert(I != SubLoops.end() && "OldChild not in loop!");
391b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    *I = NewChild;
392b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    OldChild->ParentLoop = 0;
393b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    NewChild->ParentLoop = static_cast<LoopT *>(this);
394b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
39554dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius
396b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// addChildLoop - Add the specified loop to be a child of this loop.  This
397b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// updates the loop depth of the new child.
39854dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius  ///
39954dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius  void addChildLoop(LoopT *NewChild) {
400b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
401b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    NewChild->ParentLoop = static_cast<LoopT *>(this);
402fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    SubLoops.push_back(NewChild);
403b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
404b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
405b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// removeChildLoop - This removes the specified child from being a subloop of
406b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// this loop.  The loop is not deleted, as it will presumably be inserted
407b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// into another loop.
408b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  LoopT *removeChildLoop(iterator I) {
409b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    assert(I != SubLoops.end() && "Cannot remove end iterator!");
410b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    LoopT *Child = *I;
4118393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius    assert(Child->ParentLoop == this && "Child is not a child of this loop!");
412b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    SubLoops.erase(SubLoops.begin()+(I-begin()));
4138393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius    Child->ParentLoop = 0;
414b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return Child;
4158393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius  }
4168393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius
4178393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius  /// addBlockEntry - This adds a basic block directly to the basic block list.
4188393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius  /// This should only be used by transformations that create new loops.  Other
4198393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius  /// transformations should use addBasicBlockToLoop.
4208393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius  void addBlockEntry(BlockT *BB) {
4218393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius    Blocks.push_back(BB);
422b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
4238393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius
424b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// moveToHeader - This method is used to move BB (which must be part of this
425b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// loop) to be the loop header of the loop (the block that dominates all
4268393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius  /// others).
427b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void moveToHeader(BlockT *BB) {
428b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (Blocks[0] == BB) return;
4298393335b955da7340c9f19b1b4b2d6c0c2c04be7Craig Cornelius    for (unsigned i = 0; ; ++i) {
430b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      assert(i != Blocks.size() && "Loop does not contain BB!");
431b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      if (Blocks[i] == BB) {
432b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        Blocks[i] = Blocks[0];
433b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        Blocks[0] = BB;
434b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        return;
435b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      }
436b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    }
437b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
438b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
439b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// removeBlockFromLoop - This removes the specified basic block from the
440b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// current loop, updating the Blocks as appropriate.  This does not update
441b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// the mapping in the LoopInfo class.
442b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void removeBlockFromLoop(BlockT *BB) {
443b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    RemoveFromVector(Blocks, BB);
444b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
445b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
446b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// verifyLoop - Verify loop structure
447b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void verifyLoop() const {
448b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#ifndef NDEBUG
449b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    assert (getHeader() && "Loop header is missing");
450b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    assert (getLoopPreheader() && "Loop preheader is missing");
451b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    assert (getLoopLatch() && "Loop latch is missing");
452b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (iterator I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
453b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      (*I)->verifyLoop();
454b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru#endif
455b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
45659d709d503bab6e2b61931737e662dd293b40578ccornelius
457b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void print(raw_ostream &OS, unsigned Depth = 0) const {
45859d709d503bab6e2b61931737e662dd293b40578ccornelius    OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
45959d709d503bab6e2b61931737e662dd293b40578ccornelius       << " containing: ";
46059d709d503bab6e2b61931737e662dd293b40578ccornelius
46159d709d503bab6e2b61931737e662dd293b40578ccornelius    for (unsigned i = 0; i < getBlocks().size(); ++i) {
462b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      if (i) OS << ",";
463b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      BlockT *BB = getBlocks()[i];
464b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      WriteAsOperand(OS, BB, false);
46559d709d503bab6e2b61931737e662dd293b40578ccornelius      if (BB == getHeader())    OS << "<header>";
466b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      if (BB == getLoopLatch()) OS << "<latch>";
467fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      if (isLoopExit(BB))       OS << "<exit>";
46859d709d503bab6e2b61931737e662dd293b40578ccornelius    }
469b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    OS << "\n";
470b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
471b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (iterator I = begin(), E = end(); I != E; ++I)
472b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      (*I)->print(OS, Depth+2);
473b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
474b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
475b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void dump() const {
476b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    print(errs());
477b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
478b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
479b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queruprotected:
480fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  friend class LoopInfoBase<BlockT, LoopT>;
481b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  explicit LoopBase(BlockT *BB) : ParentLoop(0) {
482b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    Blocks.push_back(BB);
483b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
484b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru};
48554dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius
48654dcd9b6a06071f647dac967e9e267abb9410720Craig Corneliusclass Loop : public LoopBase<BasicBlock, Loop> {
48754dcd9b6a06071f647dac967e9e267abb9410720Craig Corneliuspublic:
488b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  Loop() {}
489b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
490b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// isLoopInvariant - Return true if the specified value is loop invariant
49154dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius  ///
492b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  bool isLoopInvariant(Value *V) const;
493fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
494b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// isLoopInvariant - Return true if the specified instruction is
495b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// loop-invariant.
496b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
497b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  bool isLoopInvariant(Instruction *I) const;
498b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
499b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// makeLoopInvariant - If the given value is an instruction inside of the
500b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// loop and it can be hoisted, do so to make it trivially loop-invariant.
501b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// Return true if the value after any hoisting is loop invariant. This
502b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// function can be used as a slightly more aggressive replacement for
503b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// isLoopInvariant.
504b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
505b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// If InsertPt is specified, it is the point to hoist instructions to.
506b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// If null, the terminator of the loop preheader is used.
507b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
508b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  bool makeLoopInvariant(Value *V, bool &Changed,
509b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                         Instruction *InsertPt = 0) const;
510b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
511b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// makeLoopInvariant - If the given instruction is inside of the
512b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// loop and it can be hoisted, do so to make it trivially loop-invariant.
51354dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius  /// Return true if the instruction after any hoisting is loop invariant. This
514b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// function can be used as a slightly more aggressive replacement for
515b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// isLoopInvariant.
516fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  ///
517fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// If InsertPt is specified, it is the point to hoist instructions to.
518fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// If null, the terminator of the loop preheader is used.
519fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  ///
520fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  bool makeLoopInvariant(Instruction *I, bool &Changed,
521fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius                         Instruction *InsertPt = 0) const;
522fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
523fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// getCanonicalInductionVariable - Check to see if the loop has a canonical
524fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// induction variable: an integer recurrence that starts at 0 and increments
525fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// by one each time through the loop.  If so, return the phi node that
526fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// corresponds to it.
527fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  ///
528fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// The IndVarSimplify pass transforms loops to have a canonical induction
529fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// variable.
530fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  ///
531fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  PHINode *getCanonicalInductionVariable() const;
532fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
533fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
534fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// the canonical induction variable value for the "next" iteration of the
535fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
536fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  ///
537fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  Instruction *getCanonicalInductionVariableIncrement() const;
538fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
539fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// getTripCount - Return a loop-invariant LLVM value indicating the number of
540fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// times the loop will be executed.  Note that this means that the backedge
541fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// of the loop executes N-1 times.  If the trip-count cannot be determined,
542fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// this returns null.
543fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  ///
544fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// The IndVarSimplify pass transforms loops to have a form that this
545fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// function easily understands.
546fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  ///
547fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  Value *getTripCount() const;
548b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
549b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getSmallConstantTripCount - Returns the trip count of this loop as a
550b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
551fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// of not constant. Will also return 0 if the trip count is very large
552fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// (>= 2^32)
553fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  unsigned getSmallConstantTripCount() const;
554fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
555fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
556b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// trip count of this loop as a normal unsigned value, if possible. This
557b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// means that the actual trip count is always a multiple of the returned
558b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// value (don't forget the trip count could very well be zero as well!).
559b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
560fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// Returns 1 if the trip count is unknown or not guaranteed to be the
561fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// multiple of a constant (which is also the case if the trip count is simply
562fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// constant, use getSmallConstantTripCount for that case), Will also return 1
563fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// if the trip count is very large (>= 2^32).
564fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  unsigned getSmallConstantTripMultiple() const;
565fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
566fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// isLCSSAForm - Return true if the Loop is in LCSSA form
567b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  bool isLCSSAForm() const;
568fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
569fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// isLoopSimplifyForm - Return true if the Loop is in the form that
570fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// the LoopSimplify form transforms loops to, which is sometimes called
571fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// normal form.
572fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  bool isLoopSimplifyForm() const;
573b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
57454dcd9b6a06071f647dac967e9e267abb9410720Craig Corneliusprivate:
575b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  friend class LoopInfoBase<BasicBlock, Loop>;
576b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
577fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius};
578fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
579fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius//===----------------------------------------------------------------------===//
580fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius/// LoopInfo - This class builds and contains all of the top level loop
581fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius/// structures in the specified function.
582fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius///
583fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
584fceb39872958b9fa2505e63f8b8699a9e0f882f4ccorneliustemplate<class BlockT, class LoopT>
585fceb39872958b9fa2505e63f8b8699a9e0f882f4ccorneliusclass LoopInfoBase {
586b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // BBMap - Mapping of basic blocks to the inner most loop they occur in
58754dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius  std::map<BlockT *, LoopT *> BBMap;
588b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  std::vector<LoopT *> TopLevelLoops;
589b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  friend class LoopBase<BlockT, LoopT>;
590b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
591b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void operator=(const LoopInfoBase &); // do not implement
592fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  LoopInfoBase(const LoopInfo &);       // do not implement
593fceb39872958b9fa2505e63f8b8699a9e0f882f4ccorneliuspublic:
594b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  LoopInfoBase() { }
595b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ~LoopInfoBase() { releaseMemory(); }
596b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
597b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void releaseMemory() {
598b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (typename std::vector<LoopT *>::iterator I =
599fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius         TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
600b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      delete *I;   // Delete all of the loops...
601b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
602b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    BBMap.clear();                           // Reset internal state of analysis
603b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    TopLevelLoops.clear();
604fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
605b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
606b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// iterator/begin/end - The interface to the top-level loops in the current
607b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// function.
608b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
609b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  typedef typename std::vector<LoopT *>::const_iterator iterator;
610fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  iterator begin() const { return TopLevelLoops.begin(); }
611b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  iterator end() const { return TopLevelLoops.end(); }
612b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  bool empty() const { return TopLevelLoops.empty(); }
613b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
614b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
615b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// block is in no loop (for example the entry node), null is returned.
616b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
617b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  LoopT *getLoopFor(const BlockT *BB) const {
618b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    typename std::map<BlockT *, LoopT *>::const_iterator I=
619b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      BBMap.find(const_cast<BlockT*>(BB));
620b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return I != BBMap.end() ? I->second : 0;
621b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
622b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
623fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// operator[] - same as getLoopFor...
624b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
625b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  const LoopT *operator[](const BlockT *BB) const {
626b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return getLoopFor(BB);
627b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
628b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
629b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// getLoopDepth - Return the loop nesting level of the specified block.  A
630b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// depth of 0 means the block is not inside any loop.
631b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  ///
632b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  unsigned getLoopDepth(const BlockT *BB) const {
633b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    const LoopT *L = getLoopFor(BB);
634b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return L ? L->getLoopDepth() : 0;
635b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  }
636b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
637b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  // isLoopHeader - True if the block is a loop header node
638b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  bool isLoopHeader(BlockT *BB) const {
63927f654740f2a26ad62a5c155af9199af9e69b889claireho    const LoopT *L = getLoopFor(BB);
640b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho    return L && L->getHeader() == BB;
641b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  }
642b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho
643b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  /// removeLoop - This removes the specified top-level loop from this loop info
644b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  /// object.  The loop is not deleted, as it will presumably be inserted into
645b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  /// another loop.
646b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  LoopT *removeLoop(iterator I) {
647b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho    assert(I != end() && "Cannot remove end iterator!");
648103e9ffba2cba345d0078eb8b8db33249f81840aCraig Cornelius    LoopT *L = *I;
64927f654740f2a26ad62a5c155af9199af9e69b889claireho    assert(L->getParentLoop() == 0 && "Not a top-level loop!");
65054dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius    TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
65154dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius    return L;
65254dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius  }
65327f654740f2a26ad62a5c155af9199af9e69b889claireho
65427f654740f2a26ad62a5c155af9199af9e69b889claireho  /// changeLoopFor - Change the top-level loop that contains BB to the
655b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  /// specified loop.  This should be used by transformations that restructure
656b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  /// the loop hierarchy tree.
657b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  void changeLoopFor(BlockT *BB, LoopT *L) {
65827f654740f2a26ad62a5c155af9199af9e69b889claireho    LoopT *&OldLoop = BBMap[BB];
659b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho    assert(OldLoop && "Block not in a loop yet!");
660b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho    OldLoop = L;
661b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  }
662103e9ffba2cba345d0078eb8b8db33249f81840aCraig Cornelius
663b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
66454dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius  /// list with the indicated loop.
66554dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius  void changeTopLevelLoop(LoopT *OldLoop,
66654dcd9b6a06071f647dac967e9e267abb9410720Craig Cornelius                          LoopT *NewLoop) {
667b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho    typename std::vector<LoopT *>::iterator I =
668b26ce3a7367e4ed2ee7ddddcdc3f3d3377a455c2claireho                 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
669fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    assert(I != TopLevelLoops.end() && "Old loop not at top level!");
670fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    *I = NewLoop;
67127f654740f2a26ad62a5c155af9199af9e69b889claireho    assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
672fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius           "Loops already embedded into a subloop!");
673fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
674fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
675fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// addTopLevelLoop - This adds the specified loop to the collection of
676b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  /// top-level loops.
677fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  void addTopLevelLoop(LoopT *New) {
678fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    assert(New->getParentLoop() == 0 && "Loop already in subloop!");
679fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    TopLevelLoops.push_back(New);
680fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
681fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
682fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// removeBlock - This method completely removes BB from all data structures,
683fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// including all of the Loop objects it is nested in and our mapping from
684fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// BasicBlocks to loops.
685fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  void removeBlock(BlockT *BB) {
686fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    typename std::map<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
687fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    if (I != BBMap.end()) {
688fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      for (LoopT *L = I->second; L; L = L->getParentLoop())
689fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        L->removeBlockFromLoop(BB);
690fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
691fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      BBMap.erase(I);
692fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    }
693fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
694fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
695fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  // Internals
696fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
697fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
698fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius                                      const LoopT *ParentLoop) {
699fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    if (SubLoop == 0) return true;
700fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    if (SubLoop == ParentLoop) return false;
701fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
702fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
703fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
704b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void Calculate(DominatorTreeBase<BlockT> &DT) {
705b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    BlockT *RootNode = DT.getRootNode()->getBlock();
706fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
707fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    for (df_iterator<BlockT*> NI = df_begin(RootNode),
708fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius           NE = df_end(RootNode); NI != NE; ++NI)
709fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      if (LoopT *L = ConsiderForLoop(*NI, DT))
710fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        TopLevelLoops.push_back(L);
711fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
712b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
713fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
714b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
715fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
716fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    std::vector<BlockT *> TodoStack;
717b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
718b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // Scan the predecessors of BB, checking to see if BB dominates any of
719b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // them.  This identifies backedges which target this node...
720b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
721fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    for (typename InvBlockTraits::ChildIteratorType I =
722fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius         InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
723fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius         I != E; ++I)
724fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      if (DT.dominates(BB, *I))   // If BB dominates it's predecessor...
725b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        TodoStack.push_back(*I);
726fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
727b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    if (TodoStack.empty()) return 0;  // No backedges to this block...
728b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
729fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    // Create a new loop to represent this basic block...
730fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    LoopT *L = new LoopT(BB);
731fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    BBMap[BB] = L;
732fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
733fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    BlockT *EntryBlock = BB->getParent()->begin();
734fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
735fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    while (!TodoStack.empty()) {  // Process all the nodes in the loop
736fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      BlockT *X = TodoStack.back();
737fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      TodoStack.pop_back();
738fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
739b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      if (!L->contains(X) &&         // As of yet unprocessed??
740fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          DT.dominates(EntryBlock, X)) {   // X is reachable from entry block?
741fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        // Check to see if this block already belongs to a loop.  If this occurs
742fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        // then we have a case where a loop that is supposed to be a child of
743b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // the current loop was processed before the current loop.  When this
744b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        // occurs, this child loop gets added to a part of the current loop,
745fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        // making it a sibling to the current loop.  We have to reparent this
746fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        // loop.
747fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        if (LoopT *SubLoop =
748fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            const_cast<LoopT *>(getLoopFor(X)))
749fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
750b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru            // Remove the subloop from it's current parent...
751b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru            assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
752fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            LoopT *SLP = SubLoop->ParentLoop;  // SubLoopParent
753fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            typename std::vector<LoopT *>::iterator I =
754fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius              std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
755fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
756fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            SLP->SubLoops.erase(I);   // Remove from parent...
757fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
758fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            // Add the subloop to THIS loop...
759fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            SubLoop->ParentLoop = L;
760fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            L->SubLoops.push_back(SubLoop);
761b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          }
762fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
763fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        // Normal case, add the block to our loop...
764fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        L->Blocks.push_back(X);
765fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
766fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
767fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
768fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        // Add all of the predecessors of X to the end of the work stack...
769fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
770b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                         InvBlockTraits::child_end(X));
771b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      }
772fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    }
773fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
774fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    // If there are any loops nested within this loop, create them now!
775fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
776fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius         E = L->Blocks.end(); I != E; ++I)
777b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
778b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        L->SubLoops.push_back(NewLoop);
779b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru        NewLoop->ParentLoop = L;
780fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      }
781fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
782b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // Add the basic blocks that comprise this loop to the BBMap so that this
783c69afcec261fc345fda8daf46f0ea6b4351dc777Jean-Baptiste Queru    // loop can be found for them.
784b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    //
785b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
786c69afcec261fc345fda8daf46f0ea6b4351dc777Jean-Baptiste Queru           E = L->Blocks.end(); I != E; ++I) {
787b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      typename std::map<BlockT*, LoopT *>::iterator BBMI = BBMap.find(*I);
788b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru      if (BBMI == BBMap.end())                       // Not in map yet...
789fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        BBMap.insert(BBMI, std::make_pair(*I, L));   // Must be at this level
790fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    }
791b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
792fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    // Now that we have a list of all of the child loops of this loop, check to
793b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    // see if any of them should actually be nested inside of each other.  We
794fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    // can accidentally pull loops our of their parents, so we must make sure to
795fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    // organize the loop nests correctly now.
796fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    {
797fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      std::map<BlockT *, LoopT *> ContainingLoops;
798103e9ffba2cba345d0078eb8b8db33249f81840aCraig Cornelius      for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
799fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        LoopT *Child = L->SubLoops[i];
800fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        assert(Child->getParentLoop() == L && "Not proper child loop?");
801fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
802fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
803fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          // If there is already a loop which contains this loop, move this loop
804fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          // into the containing loop.
805b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru          MoveSiblingLoopInto(Child, ContainingLoop);
806fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          --i;  // The loop got removed from the SubLoops list.
807fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        } else {
808fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          // This is currently considered to be a top-level loop.  Check to see
809fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          // if any of the contained blocks are loop headers for subloops we
810fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          // have already processed.
811fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
812fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
813b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru            if (BlockLoop == 0) {   // Child block not processed yet...
814fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius              BlockLoop = Child;
815fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            } else if (BlockLoop != Child) {
816b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru              LoopT *SubLoop = BlockLoop;
817fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius              // Reparent all of the blocks which used to belong to BlockLoops
818fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius              for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
819b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                ContainingLoops[SubLoop->Blocks[j]] = Child;
820fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
821b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru              // There is already a loop which contains this block, that means
822fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius              // that we should reparent the loop which the block is currently
823fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius              // considered to belong to to be a child of this loop.
824fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius              MoveSiblingLoopInto(SubLoop, Child);
825fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius              --i;  // We just shrunk the SubLoops list.
826fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius            }
827fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius          }
828fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius        }
829fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      }
830fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    }
831b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru
832b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru    return L;
833fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
834fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
835fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
836fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// of the NewParent Loop, instead of being a sibling of it.
837fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  void MoveSiblingLoopInto(LoopT *NewChild,
838fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius                           LoopT *NewParent) {
839fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    LoopT *OldParent = NewChild->getParentLoop();
840fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    assert(OldParent && OldParent == NewParent->getParentLoop() &&
841b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru           NewChild != NewParent && "Not sibling loops!");
842fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
843fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    // Remove NewChild from being a child of OldParent
844fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    typename std::vector<LoopT *>::iterator I =
845fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius      std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
846b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru                NewChild);
847fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
848fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
849fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    NewChild->ParentLoop = 0;
850fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
851fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    InsertLoopInto(NewChild, NewParent);
852fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  }
853fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius
854fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// InsertLoopInto - This inserts loop L into the specified parent loop.  If
855fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// the parent loop contains a loop which should contain L, the loop gets
856fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius  /// inserted into L instead.
857b13da9df870a61b11249bf741347908dbea0edd8Jean-Baptiste Queru  void InsertLoopInto(LoopT *L, LoopT *Parent) {
858fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    BlockT *LHeader = L->getHeader();
859fceb39872958b9fa2505e63f8b8699a9e0f882f4ccornelius    assert(Parent->contains(LHeader) &&
860           "This loop should not be inserted here!");
861
862    // Check to see if it belongs in a child loop...
863    for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
864         i != e; ++i)
865      if (Parent->SubLoops[i]->contains(LHeader)) {
866        InsertLoopInto(L, Parent->SubLoops[i]);
867        return;
868      }
869
870    // If not, insert it here!
871    Parent->SubLoops.push_back(L);
872    L->ParentLoop = Parent;
873  }
874
875  // Debugging
876
877  void print(raw_ostream &OS) const {
878    for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
879      TopLevelLoops[i]->print(OS);
880  #if 0
881    for (std::map<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
882           E = BBMap.end(); I != E; ++I)
883      OS << "BB '" << I->first->getName() << "' level = "
884         << I->second->getLoopDepth() << "\n";
885  #endif
886  }
887};
888
889class LoopInfo : public FunctionPass {
890  LoopInfoBase<BasicBlock, Loop> LI;
891  friend class LoopBase<BasicBlock, Loop>;
892
893  void operator=(const LoopInfo &); // do not implement
894  LoopInfo(const LoopInfo &);       // do not implement
895public:
896  static char ID; // Pass identification, replacement for typeid
897
898  LoopInfo() : FunctionPass(&ID) {}
899
900  LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
901
902  /// iterator/begin/end - The interface to the top-level loops in the current
903  /// function.
904  ///
905  typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
906  inline iterator begin() const { return LI.begin(); }
907  inline iterator end() const { return LI.end(); }
908  bool empty() const { return LI.empty(); }
909
910  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
911  /// block is in no loop (for example the entry node), null is returned.
912  ///
913  inline Loop *getLoopFor(const BasicBlock *BB) const {
914    return LI.getLoopFor(BB);
915  }
916
917  /// operator[] - same as getLoopFor...
918  ///
919  inline const Loop *operator[](const BasicBlock *BB) const {
920    return LI.getLoopFor(BB);
921  }
922
923  /// getLoopDepth - Return the loop nesting level of the specified block.  A
924  /// depth of 0 means the block is not inside any loop.
925  ///
926  inline unsigned getLoopDepth(const BasicBlock *BB) const {
927    return LI.getLoopDepth(BB);
928  }
929
930  // isLoopHeader - True if the block is a loop header node
931  inline bool isLoopHeader(BasicBlock *BB) const {
932    return LI.isLoopHeader(BB);
933  }
934
935  /// runOnFunction - Calculate the natural loop information.
936  ///
937  virtual bool runOnFunction(Function &F);
938
939  virtual void releaseMemory() { LI.releaseMemory(); }
940
941  virtual void print(raw_ostream &O, const Module* M = 0) const;
942
943  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
944
945  /// removeLoop - This removes the specified top-level loop from this loop info
946  /// object.  The loop is not deleted, as it will presumably be inserted into
947  /// another loop.
948  inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
949
950  /// changeLoopFor - Change the top-level loop that contains BB to the
951  /// specified loop.  This should be used by transformations that restructure
952  /// the loop hierarchy tree.
953  inline void changeLoopFor(BasicBlock *BB, Loop *L) {
954    LI.changeLoopFor(BB, L);
955  }
956
957  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
958  /// list with the indicated loop.
959  inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
960    LI.changeTopLevelLoop(OldLoop, NewLoop);
961  }
962
963  /// addTopLevelLoop - This adds the specified loop to the collection of
964  /// top-level loops.
965  inline void addTopLevelLoop(Loop *New) {
966    LI.addTopLevelLoop(New);
967  }
968
969  /// removeBlock - This method completely removes BB from all data structures,
970  /// including all of the Loop objects it is nested in and our mapping from
971  /// BasicBlocks to loops.
972  void removeBlock(BasicBlock *BB) {
973    LI.removeBlock(BB);
974  }
975
976  static bool isNotAlreadyContainedIn(const Loop *SubLoop,
977                                      const Loop *ParentLoop) {
978    return
979      LoopInfoBase<BasicBlock, Loop>::isNotAlreadyContainedIn(SubLoop,
980                                                              ParentLoop);
981  }
982};
983
984
985// Allow clients to walk the list of nested loops...
986template <> struct GraphTraits<const Loop*> {
987  typedef const Loop NodeType;
988  typedef LoopInfo::iterator ChildIteratorType;
989
990  static NodeType *getEntryNode(const Loop *L) { return L; }
991  static inline ChildIteratorType child_begin(NodeType *N) {
992    return N->begin();
993  }
994  static inline ChildIteratorType child_end(NodeType *N) {
995    return N->end();
996  }
997};
998
999template <> struct GraphTraits<Loop*> {
1000  typedef Loop NodeType;
1001  typedef LoopInfo::iterator ChildIteratorType;
1002
1003  static NodeType *getEntryNode(Loop *L) { return L; }
1004  static inline ChildIteratorType child_begin(NodeType *N) {
1005    return N->begin();
1006  }
1007  static inline ChildIteratorType child_end(NodeType *N) {
1008    return N->end();
1009  }
1010};
1011
1012template<class BlockT, class LoopT>
1013void
1014LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1015                                             LoopInfoBase<BlockT, LoopT> &LIB) {
1016  assert((Blocks.empty() || LIB[getHeader()] == this) &&
1017         "Incorrect LI specified for this loop!");
1018  assert(NewBB && "Cannot add a null basic block to the loop!");
1019  assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1020
1021  LoopT *L = static_cast<LoopT *>(this);
1022
1023  // Add the loop mapping to the LoopInfo object...
1024  LIB.BBMap[NewBB] = L;
1025
1026  // Add the basic block to this loop and all parent loops...
1027  while (L) {
1028    L->Blocks.push_back(NewBB);
1029    L = L->getParentLoop();
1030  }
1031}
1032
1033} // End llvm namespace
1034
1035#endif
1036