LoopInfo.h revision 92583187306cec18d73db362681ea4f8e2b41909
1ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//
3ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//                     The LLVM Compiler Infrastructure
4ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//
5ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// This file is distributed under the University of Illinois Open Source
6ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// License. See LICENSE.TXT for details.
7ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//
88a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com//===----------------------------------------------------------------------===//
98a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com//
108a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com// This file defines the LoopInfo class that is used to identify natural loops
118a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com// and determine the loop depth of various nodes of the CFG.  A natural loop
128a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com// has exactly one entry-point, which is called the header. Note that natural
138a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com// loops may actually be several loops that share the same header node.
148a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com//
158a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com// This analysis calculates the nesting structure of loops in a function.  For
168a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com// each natural loop identified, this analysis identifies natural loops
178a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com// contained entirely within the loop and the basic blocks the make up the loop.
184b5894c82df1777ef86353521d789e094070156breed@google.com//
194b5894c82df1777ef86353521d789e094070156breed@google.com// It can calculate on the fly various bits of information, for example:
204b5894c82df1777ef86353521d789e094070156breed@google.com//
214b5894c82df1777ef86353521d789e094070156breed@google.com//  * whether there is a preheader for the loop
224b5894c82df1777ef86353521d789e094070156breed@google.com//  * the number of back edges to the header
23a8c183125f2861067daf432cada06d431a795cd0commit-bot@chromium.org//  * whether or not a particular block branches out of the loop
24dbfac8a72393eaf01670aeb3244de0e18d8faf98junov@google.com//  * the successor blocks of the loop
254b5894c82df1777ef86353521d789e094070156breed@google.com//  * the loop depth
264b5894c82df1777ef86353521d789e094070156breed@google.com//  * the trip count
274b5894c82df1777ef86353521d789e094070156breed@google.com//  * etc...
28ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com//
294b5894c82df1777ef86353521d789e094070156breed@google.com//===----------------------------------------------------------------------===//
30ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com
31ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com#ifndef LLVM_ANALYSIS_LOOP_INFO_H
324debcac8c38cae17a01e697578719c60a068052frobertphillips@google.com#define LLVM_ANALYSIS_LOOP_INFO_H
334debcac8c38cae17a01e697578719c60a068052frobertphillips@google.com
34ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com#include "llvm/Pass.h"
354b5894c82df1777ef86353521d789e094070156breed@google.com#include "llvm/ADT/DepthFirstIterator.h"
364b5894c82df1777ef86353521d789e094070156breed@google.com#include "llvm/ADT/GraphTraits.h"
374b5894c82df1777ef86353521d789e094070156breed@google.com#include "llvm/ADT/SmallVector.h"
384b5894c82df1777ef86353521d789e094070156breed@google.com#include "llvm/ADT/STLExtras.h"
394b5894c82df1777ef86353521d789e094070156breed@google.com#include "llvm/Analysis/Dominators.h"
404b5894c82df1777ef86353521d789e094070156breed@google.com#include "llvm/Support/CFG.h"
414b5894c82df1777ef86353521d789e094070156breed@google.com#include "llvm/Support/raw_ostream.h"
424b5894c82df1777ef86353521d789e094070156breed@google.com#include <algorithm>
43dbfac8a72393eaf01670aeb3244de0e18d8faf98junov@google.com
444b5894c82df1777ef86353521d789e094070156breed@google.comnamespace llvm {
454b5894c82df1777ef86353521d789e094070156breed@google.com
464b5894c82df1777ef86353521d789e094070156breed@google.comtemplate<typename T>
474b5894c82df1777ef86353521d789e094070156breed@google.comstatic void RemoveFromVector(std::vector<T*> &V, T *N) {
48dbfac8a72393eaf01670aeb3244de0e18d8faf98junov@google.com  typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
494b5894c82df1777ef86353521d789e094070156breed@google.com  assert(I != V.end() && "N is not in this list!");
504debcac8c38cae17a01e697578719c60a068052frobertphillips@google.com  V.erase(I);
514b5894c82df1777ef86353521d789e094070156breed@google.com}
524b5894c82df1777ef86353521d789e094070156breed@google.com
534b5894c82df1777ef86353521d789e094070156breed@google.comclass DominatorTree;
544b5894c82df1777ef86353521d789e094070156breed@google.comclass LoopInfo;
554b5894c82df1777ef86353521d789e094070156breed@google.comclass Loop;
564b5894c82df1777ef86353521d789e094070156breed@google.comtemplate<class N, class M> class LoopInfoBase;
574b5894c82df1777ef86353521d789e094070156breed@google.comtemplate<class N, class M> class LoopBase;
584b5894c82df1777ef86353521d789e094070156breed@google.com
59ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com//===----------------------------------------------------------------------===//
604b5894c82df1777ef86353521d789e094070156breed@google.com/// LoopBase class - Instances of this class are used to represent loops that
614b5894c82df1777ef86353521d789e094070156breed@google.com/// are detected in the flow graph
624b5894c82df1777ef86353521d789e094070156breed@google.com///
634b5894c82df1777ef86353521d789e094070156breed@google.comtemplate<class BlockT, class LoopT>
644b5894c82df1777ef86353521d789e094070156breed@google.comclass LoopBase {
654b5894c82df1777ef86353521d789e094070156breed@google.com  LoopT *ParentLoop;
664b5894c82df1777ef86353521d789e094070156breed@google.com  // SubLoops - Loops contained entirely within this one.
674b5894c82df1777ef86353521d789e094070156breed@google.com  std::vector<LoopT *> SubLoops;
684b5894c82df1777ef86353521d789e094070156breed@google.com
694b5894c82df1777ef86353521d789e094070156breed@google.com  // Blocks - The list of blocks in this loop.  First entry is the header node.
704b5894c82df1777ef86353521d789e094070156breed@google.com  std::vector<BlockT*> Blocks;
714b5894c82df1777ef86353521d789e094070156breed@google.com
724b5894c82df1777ef86353521d789e094070156breed@google.com  // DO NOT IMPLEMENT
734b5894c82df1777ef86353521d789e094070156breed@google.com  LoopBase(const LoopBase<BlockT, LoopT> &);
744b5894c82df1777ef86353521d789e094070156breed@google.com  // DO NOT IMPLEMENT
754b5894c82df1777ef86353521d789e094070156breed@google.com  const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
764b5894c82df1777ef86353521d789e094070156breed@google.compublic:
774b5894c82df1777ef86353521d789e094070156breed@google.com  /// Loop ctor - This creates an empty loop.
784b413c8bb123e42ca4b9c7bfa6bc2167283cb84ccommit-bot@chromium.org  LoopBase() : ParentLoop(0) {}
794b5894c82df1777ef86353521d789e094070156breed@google.com  ~LoopBase() {
804b5894c82df1777ef86353521d789e094070156breed@google.com    for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
814b5894c82df1777ef86353521d789e094070156breed@google.com      delete SubLoops[i];
824b5894c82df1777ef86353521d789e094070156breed@google.com  }
834b5894c82df1777ef86353521d789e094070156breed@google.com
844b5894c82df1777ef86353521d789e094070156breed@google.com  /// getLoopDepth - Return the nesting level of this loop.  An outer-most
854b5894c82df1777ef86353521d789e094070156breed@google.com  /// loop has depth 1, for consistency with loop depth values used for basic
864b5894c82df1777ef86353521d789e094070156breed@google.com  /// blocks, where depth 0 is used for blocks not inside any loops.
874b5894c82df1777ef86353521d789e094070156breed@google.com  unsigned getLoopDepth() const {
884b5894c82df1777ef86353521d789e094070156breed@google.com    unsigned D = 1;
894b5894c82df1777ef86353521d789e094070156breed@google.com    for (const LoopT *CurLoop = ParentLoop; CurLoop;
904b5894c82df1777ef86353521d789e094070156breed@google.com         CurLoop = CurLoop->ParentLoop)
914b5894c82df1777ef86353521d789e094070156breed@google.com      ++D;
924b5894c82df1777ef86353521d789e094070156breed@google.com    return D;
934b5894c82df1777ef86353521d789e094070156breed@google.com  }
94ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com  BlockT *getHeader() const { return Blocks.front(); }
954b5894c82df1777ef86353521d789e094070156breed@google.com  LoopT *getParentLoop() const { return ParentLoop; }
964b5894c82df1777ef86353521d789e094070156breed@google.com
974b5894c82df1777ef86353521d789e094070156breed@google.com  /// contains - Return true if the specified loop is contained within in
984b5894c82df1777ef86353521d789e094070156breed@google.com  /// this loop.
994b5894c82df1777ef86353521d789e094070156breed@google.com  ///
1004b5894c82df1777ef86353521d789e094070156breed@google.com  bool contains(const LoopT *L) const {
1014b5894c82df1777ef86353521d789e094070156breed@google.com    if (L == this) return true;
1024b5894c82df1777ef86353521d789e094070156breed@google.com    if (L == 0)    return false;
1034b5894c82df1777ef86353521d789e094070156breed@google.com    return contains(L->getParentLoop());
1044b5894c82df1777ef86353521d789e094070156breed@google.com  }
1054b5894c82df1777ef86353521d789e094070156breed@google.com
1064b5894c82df1777ef86353521d789e094070156breed@google.com  /// contains - Return true if the specified basic block is in this loop.
1074b5894c82df1777ef86353521d789e094070156breed@google.com  ///
1084b5894c82df1777ef86353521d789e094070156breed@google.com  bool contains(const BlockT *BB) const {
1094b5894c82df1777ef86353521d789e094070156breed@google.com    return std::find(block_begin(), block_end(), BB) != block_end();
1104b5894c82df1777ef86353521d789e094070156breed@google.com  }
1114b5894c82df1777ef86353521d789e094070156breed@google.com
1124b5894c82df1777ef86353521d789e094070156breed@google.com  /// contains - Return true if the specified instruction is in this loop.
1134b5894c82df1777ef86353521d789e094070156breed@google.com  ///
1144b5894c82df1777ef86353521d789e094070156breed@google.com  template<class InstT>
1154b5894c82df1777ef86353521d789e094070156breed@google.com  bool contains(const InstT *Inst) const {
1164b5894c82df1777ef86353521d789e094070156breed@google.com    return contains(Inst->getParent());
1174b5894c82df1777ef86353521d789e094070156breed@google.com  }
118f2b98d67dcb6fcb3120feede9c72016fc7b3ead8reed@android.com
119f2b98d67dcb6fcb3120feede9c72016fc7b3ead8reed@android.com  /// iterator/begin/end - Return the loops contained entirely within this loop.
120f2b98d67dcb6fcb3120feede9c72016fc7b3ead8reed@android.com  ///
121f2b98d67dcb6fcb3120feede9c72016fc7b3ead8reed@android.com  const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
122f2b98d67dcb6fcb3120feede9c72016fc7b3ead8reed@android.com  typedef typename std::vector<LoopT *>::const_iterator iterator;
1238a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  iterator begin() const { return SubLoops.begin(); }
1248a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  iterator end() const { return SubLoops.end(); }
1257fa2a65c0cfc714364490cb715171461143024e0reed@google.com  bool empty() const { return SubLoops.empty(); }
1268a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1278a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// getBlocks - Get a list of the basic blocks which make up this loop.
128ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com  ///
1298a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  const std::vector<BlockT*> &getBlocks() const { return Blocks; }
1308a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  typedef typename std::vector<BlockT*>::const_iterator block_iterator;
1318a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  block_iterator block_begin() const { return Blocks.begin(); }
1328a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  block_iterator block_end() const { return Blocks.end(); }
1338a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1348a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// isLoopExiting - True if terminator in the block can branch to another
1354b5894c82df1777ef86353521d789e094070156breed@google.com  /// block that is outside of the current loop.
1364b5894c82df1777ef86353521d789e094070156breed@google.com  ///
1374b5894c82df1777ef86353521d789e094070156breed@google.com  bool isLoopExiting(const BlockT *BB) const {
1384b5894c82df1777ef86353521d789e094070156breed@google.com    typedef GraphTraits<BlockT*> BlockTraits;
1394b5894c82df1777ef86353521d789e094070156breed@google.com    for (typename BlockTraits::ChildIteratorType SI =
1404b5894c82df1777ef86353521d789e094070156breed@google.com         BlockTraits::child_begin(const_cast<BlockT*>(BB)),
1414b5894c82df1777ef86353521d789e094070156breed@google.com         SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
1424b5894c82df1777ef86353521d789e094070156breed@google.com      if (!contains(*SI))
1438a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        return true;
1448a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    }
1458a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return false;
1468a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
1474b5894c82df1777ef86353521d789e094070156breed@google.com
1484b5894c82df1777ef86353521d789e094070156breed@google.com  /// getNumBackEdges - Calculate the number of back edges to the loop header
1494b5894c82df1777ef86353521d789e094070156breed@google.com  ///
1504b5894c82df1777ef86353521d789e094070156breed@google.com  unsigned getNumBackEdges() const {
1514b5894c82df1777ef86353521d789e094070156breed@google.com    unsigned NumBackEdges = 0;
1524b5894c82df1777ef86353521d789e094070156breed@google.com    BlockT *H = getHeader();
1534b5894c82df1777ef86353521d789e094070156breed@google.com
1544b5894c82df1777ef86353521d789e094070156breed@google.com    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
1554b5894c82df1777ef86353521d789e094070156breed@google.com    for (typename InvBlockTraits::ChildIteratorType I =
1568a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com         InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
1578a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com         E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
158ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com      if (contains(*I))
1598a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        ++NumBackEdges;
1608a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1618a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return NumBackEdges;
1628a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
163f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com
164f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  //===--------------------------------------------------------------------===//
165f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  // APIs for simple analysis of the loop.
166f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  //
167f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  // Note that all of these methods can fail on general loops (ie, there may not
168f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  // be a preheader, etc).  For best success, the loop simplification and
169f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  // induction variable canonicalization pass should be used to normalize loops
170f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  // for easy analysis.  These methods assume canonical loops.
171f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com
172f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  /// getExitingBlocks - Return all blocks inside the loop that have successors
173f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  /// outside of the loop.  These are the blocks _inside of the current loop_
174f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  /// which branch out.  The returned list is always unique.
175f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  ///
176f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com  void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
177f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com    // Sort the blocks vector so that we can use binary search to do quick
178f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com    // lookups.
179f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
180f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com    std::sort(LoopBBs.begin(), LoopBBs.end());
181f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com
182f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com    typedef GraphTraits<BlockT*> BlockTraits;
183f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com    for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
184f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com      for (typename BlockTraits::ChildIteratorType I =
185f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com          BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
186ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com          I != E; ++I)
187f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com        if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
188f76bacff7f66724072c67edb185abf9e3add11a0reed@android.com          // Not in current loop? It must be an exit block.
1898a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com          ExitingBlocks.push_back(*BI);
1908a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com          break;
1918a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        }
1928a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
1938a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
1948a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// getExitingBlock - If getExitingBlocks would return exactly one block,
1958a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// return that block. Otherwise return null.
1968a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  BlockT *getExitingBlock() const {
1975fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org    SmallVector<BlockT*, 8> ExitingBlocks;
1988a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    getExitingBlocks(ExitingBlocks);
199ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    if (ExitingBlocks.size() == 1)
2008a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return ExitingBlocks[0];
2018a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return 0;
2028a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
2038a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
2045fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org  /// getExitBlocks - Return all of the successor blocks of this loop.  These
2058a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// are the blocks _outside of the current loop_ which are branched to.
2068a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  ///
2074b5894c82df1777ef86353521d789e094070156breed@google.com  void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
2088a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Sort the blocks vector so that we can use binary search to do quick
2098a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // lookups.
2108a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
2118a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    std::sort(LoopBBs.begin(), LoopBBs.end());
2124b5894c82df1777ef86353521d789e094070156breed@google.com
2134b5894c82df1777ef86353521d789e094070156breed@google.com    typedef GraphTraits<BlockT*> BlockTraits;
2144b5894c82df1777ef86353521d789e094070156breed@google.com    for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
2154b5894c82df1777ef86353521d789e094070156breed@google.com      for (typename BlockTraits::ChildIteratorType I =
2168a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
2178a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com           I != E; ++I)
2188a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
2198a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com          // Not in current loop? It must be an exit block.
2208a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com          ExitBlocks.push_back(*I);
2218a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
2225fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org
2235fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org  /// getExitBlock - If getExitBlocks would return exactly one block,
2248a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// return that block. Otherwise return null.
2258a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  BlockT *getExitBlock() const {
2268a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    SmallVector<BlockT*, 8> ExitBlocks;
2278a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    getExitBlocks(ExitBlocks);
2288a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (ExitBlocks.size() == 1)
229ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com      return ExitBlocks[0];
2304b5894c82df1777ef86353521d789e094070156breed@google.com    return 0;
2314b5894c82df1777ef86353521d789e094070156breed@google.com  }
2324b5894c82df1777ef86353521d789e094070156breed@google.com
2334b5894c82df1777ef86353521d789e094070156breed@google.com  /// Edge type.
2344b5894c82df1777ef86353521d789e094070156breed@google.com  typedef std::pair<BlockT*, BlockT*> Edge;
2354b5894c82df1777ef86353521d789e094070156breed@google.com
2364b5894c82df1777ef86353521d789e094070156breed@google.com  /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
2374b5894c82df1777ef86353521d789e094070156breed@google.com  template <typename EdgeT>
2384b5894c82df1777ef86353521d789e094070156breed@google.com  void getExitEdges(SmallVectorImpl<EdgeT> &ExitEdges) const {
2394b5894c82df1777ef86353521d789e094070156breed@google.com    // Sort the blocks vector so that we can use binary search to do quick
2404b5894c82df1777ef86353521d789e094070156breed@google.com    // lookups.
2414b5894c82df1777ef86353521d789e094070156breed@google.com    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
242ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    array_pod_sort(LoopBBs.begin(), LoopBBs.end());
2434b5894c82df1777ef86353521d789e094070156breed@google.com
2444b5894c82df1777ef86353521d789e094070156breed@google.com    typedef GraphTraits<BlockT*> BlockTraits;
2454b5894c82df1777ef86353521d789e094070156breed@google.com    for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
2464b5894c82df1777ef86353521d789e094070156breed@google.com      for (typename BlockTraits::ChildIteratorType I =
2475fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
2488a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com           I != E; ++I)
2498a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
250ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com          // Not in current loop? It must be an exit block.
2518a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com          ExitEdges.push_back(EdgeT(*BI, *I));
2528a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
2538a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
254ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com  /// getLoopPreheader - If there is a preheader for this loop, return it.  A
2554b5894c82df1777ef86353521d789e094070156breed@google.com  /// loop has a preheader if there is only one edge to the header of the loop
2564b5894c82df1777ef86353521d789e094070156breed@google.com  /// from outside of the loop.  If this is the case, the block branching to the
2574b5894c82df1777ef86353521d789e094070156breed@google.com  /// header of the loop is the preheader node.
2584b5894c82df1777ef86353521d789e094070156breed@google.com  ///
2598a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// This method returns null if there is no preheader for the loop.
2608a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  ///
2618a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  BlockT *getLoopPreheader() const {
262ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    // Keep track of nodes outside the loop branching to the header...
2635fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org    BlockT *Out = getLoopPredecessor();
2648a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    if (!Out) return 0;
2658a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
2668a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Make sure there is only one exit out of the preheader.
267ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    typedef GraphTraits<BlockT*> BlockTraits;
2688a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
2698a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    ++SI;
270ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    if (SI != BlockTraits::child_end(Out))
2718a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      return 0;  // Multiple exits from the block, must not be a preheader.
2728a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
273ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    // The predecessor has exactly one successor, so it is a preheader.
2748a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return Out;
2758a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
2760e51577a14f903ffeafa117a75954baeb173ffb9humper@google.com
2778a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// getLoopPredecessor - If the given loop's header has exactly one unique
2780e51577a14f903ffeafa117a75954baeb173ffb9humper@google.com  /// predecessor outside the loop, return it. Otherwise return null.
2798a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// This is less strict that the loop "preheader" concept, which requires
280ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com  /// the predecessor to have exactly one successor.
2818a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  ///
2824faa869cdabbdcf4867118b4a1272296baaeeb52commit-bot@chromium.org  BlockT *getLoopPredecessor() const {
2838a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Keep track of nodes outside the loop branching to the header...
284ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    BlockT *Out = 0;
2858a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
2868a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Loop over the predecessors of the header node...
2878a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    BlockT *Header = getHeader();
2888a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    typedef GraphTraits<BlockT*> BlockTraits;
2898a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
2908a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    for (typename InvBlockTraits::ChildIteratorType PI =
2918a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com         InvBlockTraits::child_begin(Header),
2928a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com         PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
2938a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      typename InvBlockTraits::NodeType *N = *PI;
2948a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      if (!contains(N)) {     // If the block is not in the loop...
2958a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        if (Out && Out != N)
2968a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com          return 0;             // Multiple predecessors outside the loop
2978a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        Out = N;
2988a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      }
2998a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    }
3008a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
3018a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Make sure there is only one exit out of the preheader.
3028a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    assert(Out && "Header of loop has no predecessors from outside loop?");
3038a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return Out;
304ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com  }
3055fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org
3068a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// getLoopLatch - If there is a single latch block for this loop, return it.
3078a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// A latch block is a block that contains a branch back to the header.
3088a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  BlockT *getLoopLatch() const {
3098a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    BlockT *Header = getHeader();
3108a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
3118a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    typename InvBlockTraits::ChildIteratorType PI =
3128a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com                                            InvBlockTraits::child_begin(Header);
3138a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    typename InvBlockTraits::ChildIteratorType PE =
3148a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com                                              InvBlockTraits::child_end(Header);
3158a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    BlockT *Latch = 0;
3168a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    for (; PI != PE; ++PI) {
3178a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      typename InvBlockTraits::NodeType *N = *PI;
3188a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      if (contains(N)) {
3198a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        if (Latch) return 0;
3208a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        Latch = N;
3218a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      }
3228a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    }
323ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com
3245fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org    return Latch;
32502939ce4bddd3223d9e8cc98d4abd02939b7f70acaryclark@google.com  }
32602939ce4bddd3223d9e8cc98d4abd02939b7f70acaryclark@google.com
32702939ce4bddd3223d9e8cc98d4abd02939b7f70acaryclark@google.com  //===--------------------------------------------------------------------===//
32802939ce4bddd3223d9e8cc98d4abd02939b7f70acaryclark@google.com  // APIs for updating loop information after changing the CFG
32902939ce4bddd3223d9e8cc98d4abd02939b7f70acaryclark@google.com  //
33002939ce4bddd3223d9e8cc98d4abd02939b7f70acaryclark@google.com
33102939ce4bddd3223d9e8cc98d4abd02939b7f70acaryclark@google.com  /// addBasicBlockToLoop - This method is used by other analyses to update loop
33202939ce4bddd3223d9e8cc98d4abd02939b7f70acaryclark@google.com  /// information.  NewBB is set to be a new member of the current loop.
3338a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// Because of this, it is added as a member of all parent loops, and is added
3348a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// to the specified LoopInfo object as being in the current basic block.  It
3358a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// is not valid to replace the loop header with this method.
3368a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  ///
337ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com  void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
3388a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
3398a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
340ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com  /// the OldChild entry in our children list with NewChild, and updates the
3418a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// parent pointer of OldChild to be null and the NewChild to be this loop.
3428a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// This updates the loop depth of the new child.
3438a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  void replaceChildLoopWith(LoopT *OldChild,
3448a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com                            LoopT *NewChild) {
3458a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    assert(OldChild->ParentLoop == this && "This loop is already broken!");
3468a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
3478a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    typename std::vector<LoopT *>::iterator I =
3488a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com                          std::find(SubLoops.begin(), SubLoops.end(), OldChild);
3498a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    assert(I != SubLoops.end() && "OldChild not in loop!");
3508a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    *I = NewChild;
3518a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    OldChild->ParentLoop = 0;
3528a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    NewChild->ParentLoop = static_cast<LoopT *>(this);
3534b5894c82df1777ef86353521d789e094070156breed@google.com  }
3544b5894c82df1777ef86353521d789e094070156breed@google.com
3554b5894c82df1777ef86353521d789e094070156breed@google.com  /// addChildLoop - Add the specified loop to be a child of this loop.  This
3564b5894c82df1777ef86353521d789e094070156breed@google.com  /// updates the loop depth of the new child.
3574b5894c82df1777ef86353521d789e094070156breed@google.com  ///
3588a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  void addChildLoop(LoopT *NewChild) {
3598a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
3608a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    NewChild->ParentLoop = static_cast<LoopT *>(this);
3618a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    SubLoops.push_back(NewChild);
3628a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
3638a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
3648a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// removeChildLoop - This removes the specified child from being a subloop of
3658a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// this loop.  The loop is not deleted, as it will presumably be inserted
3668a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// into another loop.
3678a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  LoopT *removeChildLoop(iterator I) {
3688a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    assert(I != SubLoops.end() && "Cannot remove end iterator!");
3698a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    LoopT *Child = *I;
3708a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    assert(Child->ParentLoop == this && "Child is not a child of this loop!");
3718a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    SubLoops.erase(SubLoops.begin()+(I-begin()));
3728a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    Child->ParentLoop = 0;
3738a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    return Child;
3748a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
3758a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
3768a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// addBlockEntry - This adds a basic block directly to the basic block list.
3778a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// This should only be used by transformations that create new loops.  Other
3788a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// transformations should use addBasicBlockToLoop.
379ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com  void addBlockEntry(BlockT *BB) {
3808a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    Blocks.push_back(BB);
3818a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
38264cc579efa7e416c7298ed159d76b074b283c0f9senorblanco@chromium.org
3838a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// moveToHeader - This method is used to move BB (which must be part of this
3848a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// loop) to be the loop header of the loop (the block that dominates all
3858a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// others).
3868a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  void moveToHeader(BlockT *BB) {
3875fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org    if (Blocks[0] == BB) return;
3885fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org    for (unsigned i = 0; ; ++i) {
3895fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org      assert(i != Blocks.size() && "Loop does not contain BB!");
3905fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org      if (Blocks[i] == BB) {
391ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com        Blocks[i] = Blocks[0];
3928a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        Blocks[0] = BB;
3938a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com        return;
3948a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      }
395ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    }
396dd0c3a55ecc096a2d9d46b15b8a485e86dbe9238mike@reedtribe.org  }
397dd0c3a55ecc096a2d9d46b15b8a485e86dbe9238mike@reedtribe.org
398e1ca705cac4b946993f6cbf798e2a0ba27e739f3reed@google.com  /// removeBlockFromLoop - This removes the specified basic block from the
399e1ca705cac4b946993f6cbf798e2a0ba27e739f3reed@google.com  /// current loop, updating the Blocks as appropriate.  This does not update
4008a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  /// the mapping in the LoopInfo class.
401ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com  void removeBlockFromLoop(BlockT *BB) {
4025fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org    RemoveFromVector(Blocks, BB);
4038a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  }
4048a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
405671cd656785de5e84564b6ffe4831625d7016dedreed@android.com  /// verifyLoop - Verify loop structure
4068a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com  void verifyLoop() const {
4078a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com#ifndef NDEBUG
408ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    assert(!Blocks.empty() && "Loop header is missing");
4098a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
4108a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Sort the blocks vector so that we can use binary search to do quick
411ae933ce0ea5fd9d21cb6ef2cee7e729d32690aacrmistry@google.com    // lookups.
4125fd9243fd6b82aa3f2a2fae7c62310e77ab7b6d3mike@reedtribe.org    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
4138a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    std::sort(LoopBBs.begin(), LoopBBs.end());
4148a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com
4158a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    // Check the individual blocks.
4168a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com    for (block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
4178a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      BlockT *BB = *I;
4188a1c16ff38322f0210116fa7293eb8817c7e477ereed@android.com      bool HasInsideLoopSuccs = false;
419      bool HasInsideLoopPreds = false;
420      SmallVector<BlockT *, 2> OutsideLoopPreds;
421
422      typedef GraphTraits<BlockT*> BlockTraits;
423      for (typename BlockTraits::ChildIteratorType SI =
424           BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
425           SI != SE; ++SI)
426        if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
427          HasInsideLoopSuccs = true;
428          break;
429        }
430      typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
431      for (typename InvBlockTraits::ChildIteratorType PI =
432           InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
433           PI != PE; ++PI) {
434        typename InvBlockTraits::NodeType *N = *PI;
435        if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), N))
436          HasInsideLoopPreds = true;
437        else
438          OutsideLoopPreds.push_back(N);
439      }
440
441      if (BB == getHeader()) {
442        assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
443      } else if (!OutsideLoopPreds.empty()) {
444        // A non-header loop shouldn't be reachable from outside the loop,
445        // though it is permitted if the predecessor is not itself actually
446        // reachable.
447        BlockT *EntryBB = BB->getParent()->begin();
448        for (df_iterator<BlockT *> NI = df_begin(EntryBB),
449             NE = df_end(EntryBB); NI != NE; ++NI)
450          for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
451            assert(*NI != OutsideLoopPreds[i] &&
452                   "Loop has multiple entry points!");
453      }
454      assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
455      assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
456      assert(BB != getHeader()->getParent()->begin() &&
457             "Loop contains function entry block!");
458    }
459
460    // Check the subloops.
461    for (iterator I = begin(), E = end(); I != E; ++I)
462      // Each block in each subloop should be contained within this loop.
463      for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
464           BI != BE; ++BI) {
465        assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
466               "Loop does not contain all the blocks of a subloop!");
467      }
468
469    // Check the parent loop pointer.
470    if (ParentLoop) {
471      assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
472               ParentLoop->end() &&
473             "Loop is not a subloop of its parent!");
474    }
475#endif
476  }
477
478  /// verifyLoop - Verify loop structure of this loop and all nested loops.
479  void verifyLoopNest() const {
480    // Verify this loop.
481    verifyLoop();
482    // Verify the subloops.
483    for (iterator I = begin(), E = end(); I != E; ++I)
484      (*I)->verifyLoopNest();
485  }
486
487  void print(raw_ostream &OS, unsigned Depth = 0) const {
488    OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
489       << " containing: ";
490
491    for (unsigned i = 0; i < getBlocks().size(); ++i) {
492      if (i) OS << ",";
493      BlockT *BB = getBlocks()[i];
494      WriteAsOperand(OS, BB, false);
495      if (BB == getHeader())    OS << "<header>";
496      if (BB == getLoopLatch()) OS << "<latch>";
497      if (isLoopExiting(BB))    OS << "<exiting>";
498    }
499    OS << "\n";
500
501    for (iterator I = begin(), E = end(); I != E; ++I)
502      (*I)->print(OS, Depth+2);
503  }
504
505protected:
506  friend class LoopInfoBase<BlockT, LoopT>;
507  explicit LoopBase(BlockT *BB) : ParentLoop(0) {
508    Blocks.push_back(BB);
509  }
510};
511
512class Loop : public LoopBase<BasicBlock, Loop> {
513public:
514  Loop() {}
515
516  /// isLoopInvariant - Return true if the specified value is loop invariant
517  ///
518  bool isLoopInvariant(Value *V) const;
519
520  /// isLoopInvariant - Return true if the specified instruction is
521  /// loop-invariant.
522  ///
523  bool isLoopInvariant(Instruction *I) const;
524
525  /// makeLoopInvariant - If the given value is an instruction inside of the
526  /// loop and it can be hoisted, do so to make it trivially loop-invariant.
527  /// Return true if the value after any hoisting is loop invariant. This
528  /// function can be used as a slightly more aggressive replacement for
529  /// isLoopInvariant.
530  ///
531  /// If InsertPt is specified, it is the point to hoist instructions to.
532  /// If null, the terminator of the loop preheader is used.
533  ///
534  bool makeLoopInvariant(Value *V, bool &Changed,
535                         Instruction *InsertPt = 0) const;
536
537  /// makeLoopInvariant - If the given instruction is inside of the
538  /// loop and it can be hoisted, do so to make it trivially loop-invariant.
539  /// Return true if the instruction after any hoisting is loop invariant. This
540  /// function can be used as a slightly more aggressive replacement for
541  /// isLoopInvariant.
542  ///
543  /// If InsertPt is specified, it is the point to hoist instructions to.
544  /// If null, the terminator of the loop preheader is used.
545  ///
546  bool makeLoopInvariant(Instruction *I, bool &Changed,
547                         Instruction *InsertPt = 0) const;
548
549  /// getCanonicalInductionVariable - Check to see if the loop has a canonical
550  /// induction variable: an integer recurrence that starts at 0 and increments
551  /// by one each time through the loop.  If so, return the phi node that
552  /// corresponds to it.
553  ///
554  /// The IndVarSimplify pass transforms loops to have a canonical induction
555  /// variable.
556  ///
557  PHINode *getCanonicalInductionVariable() const;
558
559  /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
560  /// the canonical induction variable value for the "next" iteration of the
561  /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
562  ///
563  Instruction *getCanonicalInductionVariableIncrement() const;
564
565  /// getTripCount - Return a loop-invariant LLVM value indicating the number of
566  /// times the loop will be executed.  Note that this means that the backedge
567  /// of the loop executes N-1 times.  If the trip-count cannot be determined,
568  /// this returns null.
569  ///
570  /// The IndVarSimplify pass transforms loops to have a form that this
571  /// function easily understands.
572  ///
573  Value *getTripCount() const;
574
575  /// getSmallConstantTripCount - Returns the trip count of this loop as a
576  /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
577  /// of not constant. Will also return 0 if the trip count is very large
578  /// (>= 2^32)
579  ///
580  /// The IndVarSimplify pass transforms loops to have a form that this
581  /// function easily understands.
582  ///
583  unsigned getSmallConstantTripCount() const;
584
585  /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
586  /// trip count of this loop as a normal unsigned value, if possible. This
587  /// means that the actual trip count is always a multiple of the returned
588  /// value (don't forget the trip count could very well be zero as well!).
589  ///
590  /// Returns 1 if the trip count is unknown or not guaranteed to be the
591  /// multiple of a constant (which is also the case if the trip count is simply
592  /// constant, use getSmallConstantTripCount for that case), Will also return 1
593  /// if the trip count is very large (>= 2^32).
594  unsigned getSmallConstantTripMultiple() const;
595
596  /// isLCSSAForm - Return true if the Loop is in LCSSA form
597  bool isLCSSAForm(DominatorTree &DT) const;
598
599  /// isLoopSimplifyForm - Return true if the Loop is in the form that
600  /// the LoopSimplify form transforms loops to, which is sometimes called
601  /// normal form.
602  bool isLoopSimplifyForm() const;
603
604  /// hasDedicatedExits - Return true if no exit block for the loop
605  /// has a predecessor that is outside the loop.
606  bool hasDedicatedExits() const;
607
608  /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
609  /// These are the blocks _outside of the current loop_ which are branched to.
610  /// This assumes that loop exits are in canonical form.
611  ///
612  void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
613
614  /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
615  /// block, return that block. Otherwise return null.
616  BasicBlock *getUniqueExitBlock() const;
617
618  void dump() const;
619
620private:
621  friend class LoopInfoBase<BasicBlock, Loop>;
622  explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
623};
624
625//===----------------------------------------------------------------------===//
626/// LoopInfo - This class builds and contains all of the top level loop
627/// structures in the specified function.
628///
629
630template<class BlockT, class LoopT>
631class LoopInfoBase {
632  // BBMap - Mapping of basic blocks to the inner most loop they occur in
633  std::map<BlockT *, LoopT *> BBMap;
634  std::vector<LoopT *> TopLevelLoops;
635  friend class LoopBase<BlockT, LoopT>;
636
637  void operator=(const LoopInfoBase &); // do not implement
638  LoopInfoBase(const LoopInfo &);       // do not implement
639public:
640  LoopInfoBase() { }
641  ~LoopInfoBase() { releaseMemory(); }
642
643  void releaseMemory() {
644    for (typename std::vector<LoopT *>::iterator I =
645         TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
646      delete *I;   // Delete all of the loops...
647
648    BBMap.clear();                           // Reset internal state of analysis
649    TopLevelLoops.clear();
650  }
651
652  /// iterator/begin/end - The interface to the top-level loops in the current
653  /// function.
654  ///
655  typedef typename std::vector<LoopT *>::const_iterator iterator;
656  iterator begin() const { return TopLevelLoops.begin(); }
657  iterator end() const { return TopLevelLoops.end(); }
658  bool empty() const { return TopLevelLoops.empty(); }
659
660  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
661  /// block is in no loop (for example the entry node), null is returned.
662  ///
663  LoopT *getLoopFor(const BlockT *BB) const {
664    typename std::map<BlockT *, LoopT *>::const_iterator I=
665      BBMap.find(const_cast<BlockT*>(BB));
666    return I != BBMap.end() ? I->second : 0;
667  }
668
669  /// operator[] - same as getLoopFor...
670  ///
671  const LoopT *operator[](const BlockT *BB) const {
672    return getLoopFor(BB);
673  }
674
675  /// getLoopDepth - Return the loop nesting level of the specified block.  A
676  /// depth of 0 means the block is not inside any loop.
677  ///
678  unsigned getLoopDepth(const BlockT *BB) const {
679    const LoopT *L = getLoopFor(BB);
680    return L ? L->getLoopDepth() : 0;
681  }
682
683  // isLoopHeader - True if the block is a loop header node
684  bool isLoopHeader(BlockT *BB) const {
685    const LoopT *L = getLoopFor(BB);
686    return L && L->getHeader() == BB;
687  }
688
689  /// removeLoop - This removes the specified top-level loop from this loop info
690  /// object.  The loop is not deleted, as it will presumably be inserted into
691  /// another loop.
692  LoopT *removeLoop(iterator I) {
693    assert(I != end() && "Cannot remove end iterator!");
694    LoopT *L = *I;
695    assert(L->getParentLoop() == 0 && "Not a top-level loop!");
696    TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
697    return L;
698  }
699
700  /// changeLoopFor - Change the top-level loop that contains BB to the
701  /// specified loop.  This should be used by transformations that restructure
702  /// the loop hierarchy tree.
703  void changeLoopFor(BlockT *BB, LoopT *L) {
704    LoopT *&OldLoop = BBMap[BB];
705    assert(OldLoop && "Block not in a loop yet!");
706    OldLoop = L;
707  }
708
709  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
710  /// list with the indicated loop.
711  void changeTopLevelLoop(LoopT *OldLoop,
712                          LoopT *NewLoop) {
713    typename std::vector<LoopT *>::iterator I =
714                 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
715    assert(I != TopLevelLoops.end() && "Old loop not at top level!");
716    *I = NewLoop;
717    assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
718           "Loops already embedded into a subloop!");
719  }
720
721  /// addTopLevelLoop - This adds the specified loop to the collection of
722  /// top-level loops.
723  void addTopLevelLoop(LoopT *New) {
724    assert(New->getParentLoop() == 0 && "Loop already in subloop!");
725    TopLevelLoops.push_back(New);
726  }
727
728  /// removeBlock - This method completely removes BB from all data structures,
729  /// including all of the Loop objects it is nested in and our mapping from
730  /// BasicBlocks to loops.
731  void removeBlock(BlockT *BB) {
732    typename std::map<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
733    if (I != BBMap.end()) {
734      for (LoopT *L = I->second; L; L = L->getParentLoop())
735        L->removeBlockFromLoop(BB);
736
737      BBMap.erase(I);
738    }
739  }
740
741  // Internals
742
743  static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
744                                      const LoopT *ParentLoop) {
745    if (SubLoop == 0) return true;
746    if (SubLoop == ParentLoop) return false;
747    return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
748  }
749
750  void Calculate(DominatorTreeBase<BlockT> &DT) {
751    BlockT *RootNode = DT.getRootNode()->getBlock();
752
753    for (df_iterator<BlockT*> NI = df_begin(RootNode),
754           NE = df_end(RootNode); NI != NE; ++NI)
755      if (LoopT *L = ConsiderForLoop(*NI, DT))
756        TopLevelLoops.push_back(L);
757  }
758
759  LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
760    if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
761
762    std::vector<BlockT *> TodoStack;
763
764    // Scan the predecessors of BB, checking to see if BB dominates any of
765    // them.  This identifies backedges which target this node...
766    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
767    for (typename InvBlockTraits::ChildIteratorType I =
768         InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
769         I != E; ++I) {
770      typename InvBlockTraits::NodeType *N = *I;
771      if (DT.dominates(BB, N))   // If BB dominates its predecessor...
772          TodoStack.push_back(N);
773    }
774
775    if (TodoStack.empty()) return 0;  // No backedges to this block...
776
777    // Create a new loop to represent this basic block...
778    LoopT *L = new LoopT(BB);
779    BBMap[BB] = L;
780
781    BlockT *EntryBlock = BB->getParent()->begin();
782
783    while (!TodoStack.empty()) {  // Process all the nodes in the loop
784      BlockT *X = TodoStack.back();
785      TodoStack.pop_back();
786
787      if (!L->contains(X) &&         // As of yet unprocessed??
788          DT.dominates(EntryBlock, X)) {   // X is reachable from entry block?
789        // Check to see if this block already belongs to a loop.  If this occurs
790        // then we have a case where a loop that is supposed to be a child of
791        // the current loop was processed before the current loop.  When this
792        // occurs, this child loop gets added to a part of the current loop,
793        // making it a sibling to the current loop.  We have to reparent this
794        // loop.
795        if (LoopT *SubLoop =
796            const_cast<LoopT *>(getLoopFor(X)))
797          if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
798            // Remove the subloop from its current parent...
799            assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
800            LoopT *SLP = SubLoop->ParentLoop;  // SubLoopParent
801            typename std::vector<LoopT *>::iterator I =
802              std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
803            assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
804            SLP->SubLoops.erase(I);   // Remove from parent...
805
806            // Add the subloop to THIS loop...
807            SubLoop->ParentLoop = L;
808            L->SubLoops.push_back(SubLoop);
809          }
810
811        // Normal case, add the block to our loop...
812        L->Blocks.push_back(X);
813
814        typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
815
816        // Add all of the predecessors of X to the end of the work stack...
817        TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
818                         InvBlockTraits::child_end(X));
819      }
820    }
821
822    // If there are any loops nested within this loop, create them now!
823    for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
824         E = L->Blocks.end(); I != E; ++I)
825      if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
826        L->SubLoops.push_back(NewLoop);
827        NewLoop->ParentLoop = L;
828      }
829
830    // Add the basic blocks that comprise this loop to the BBMap so that this
831    // loop can be found for them.
832    //
833    for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
834           E = L->Blocks.end(); I != E; ++I)
835      BBMap.insert(std::make_pair(*I, L));
836
837    // Now that we have a list of all of the child loops of this loop, check to
838    // see if any of them should actually be nested inside of each other.  We
839    // can accidentally pull loops our of their parents, so we must make sure to
840    // organize the loop nests correctly now.
841    {
842      std::map<BlockT *, LoopT *> ContainingLoops;
843      for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
844        LoopT *Child = L->SubLoops[i];
845        assert(Child->getParentLoop() == L && "Not proper child loop?");
846
847        if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
848          // If there is already a loop which contains this loop, move this loop
849          // into the containing loop.
850          MoveSiblingLoopInto(Child, ContainingLoop);
851          --i;  // The loop got removed from the SubLoops list.
852        } else {
853          // This is currently considered to be a top-level loop.  Check to see
854          // if any of the contained blocks are loop headers for subloops we
855          // have already processed.
856          for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
857            LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
858            if (BlockLoop == 0) {   // Child block not processed yet...
859              BlockLoop = Child;
860            } else if (BlockLoop != Child) {
861              LoopT *SubLoop = BlockLoop;
862              // Reparent all of the blocks which used to belong to BlockLoops
863              for (unsigned j = 0, f = SubLoop->Blocks.size(); j != f; ++j)
864                ContainingLoops[SubLoop->Blocks[j]] = Child;
865
866              // There is already a loop which contains this block, that means
867              // that we should reparent the loop which the block is currently
868              // considered to belong to to be a child of this loop.
869              MoveSiblingLoopInto(SubLoop, Child);
870              --i;  // We just shrunk the SubLoops list.
871            }
872          }
873        }
874      }
875    }
876
877    return L;
878  }
879
880  /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
881  /// of the NewParent Loop, instead of being a sibling of it.
882  void MoveSiblingLoopInto(LoopT *NewChild,
883                           LoopT *NewParent) {
884    LoopT *OldParent = NewChild->getParentLoop();
885    assert(OldParent && OldParent == NewParent->getParentLoop() &&
886           NewChild != NewParent && "Not sibling loops!");
887
888    // Remove NewChild from being a child of OldParent
889    typename std::vector<LoopT *>::iterator I =
890      std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
891                NewChild);
892    assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
893    OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
894    NewChild->ParentLoop = 0;
895
896    InsertLoopInto(NewChild, NewParent);
897  }
898
899  /// InsertLoopInto - This inserts loop L into the specified parent loop.  If
900  /// the parent loop contains a loop which should contain L, the loop gets
901  /// inserted into L instead.
902  void InsertLoopInto(LoopT *L, LoopT *Parent) {
903    BlockT *LHeader = L->getHeader();
904    assert(Parent->contains(LHeader) &&
905           "This loop should not be inserted here!");
906
907    // Check to see if it belongs in a child loop...
908    for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
909         i != e; ++i)
910      if (Parent->SubLoops[i]->contains(LHeader)) {
911        InsertLoopInto(L, Parent->SubLoops[i]);
912        return;
913      }
914
915    // If not, insert it here!
916    Parent->SubLoops.push_back(L);
917    L->ParentLoop = Parent;
918  }
919
920  // Debugging
921
922  void print(raw_ostream &OS) const {
923    for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
924      TopLevelLoops[i]->print(OS);
925  #if 0
926    for (std::map<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
927           E = BBMap.end(); I != E; ++I)
928      OS << "BB '" << I->first->getName() << "' level = "
929         << I->second->getLoopDepth() << "\n";
930  #endif
931  }
932};
933
934class LoopInfo : public FunctionPass {
935  LoopInfoBase<BasicBlock, Loop> LI;
936  friend class LoopBase<BasicBlock, Loop>;
937
938  void operator=(const LoopInfo &); // do not implement
939  LoopInfo(const LoopInfo &);       // do not implement
940public:
941  static char ID; // Pass identification, replacement for typeid
942
943  LoopInfo() : FunctionPass(&ID) {}
944
945  LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
946
947  /// iterator/begin/end - The interface to the top-level loops in the current
948  /// function.
949  ///
950  typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
951  inline iterator begin() const { return LI.begin(); }
952  inline iterator end() const { return LI.end(); }
953  bool empty() const { return LI.empty(); }
954
955  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
956  /// block is in no loop (for example the entry node), null is returned.
957  ///
958  inline Loop *getLoopFor(const BasicBlock *BB) const {
959    return LI.getLoopFor(BB);
960  }
961
962  /// operator[] - same as getLoopFor...
963  ///
964  inline const Loop *operator[](const BasicBlock *BB) const {
965    return LI.getLoopFor(BB);
966  }
967
968  /// getLoopDepth - Return the loop nesting level of the specified block.  A
969  /// depth of 0 means the block is not inside any loop.
970  ///
971  inline unsigned getLoopDepth(const BasicBlock *BB) const {
972    return LI.getLoopDepth(BB);
973  }
974
975  // isLoopHeader - True if the block is a loop header node
976  inline bool isLoopHeader(BasicBlock *BB) const {
977    return LI.isLoopHeader(BB);
978  }
979
980  /// runOnFunction - Calculate the natural loop information.
981  ///
982  virtual bool runOnFunction(Function &F);
983
984  virtual void verifyAnalysis() const;
985
986  virtual void releaseMemory() { LI.releaseMemory(); }
987
988  virtual void print(raw_ostream &O, const Module* M = 0) const;
989
990  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
991
992  /// removeLoop - This removes the specified top-level loop from this loop info
993  /// object.  The loop is not deleted, as it will presumably be inserted into
994  /// another loop.
995  inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
996
997  /// changeLoopFor - Change the top-level loop that contains BB to the
998  /// specified loop.  This should be used by transformations that restructure
999  /// the loop hierarchy tree.
1000  inline void changeLoopFor(BasicBlock *BB, Loop *L) {
1001    LI.changeLoopFor(BB, L);
1002  }
1003
1004  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
1005  /// list with the indicated loop.
1006  inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
1007    LI.changeTopLevelLoop(OldLoop, NewLoop);
1008  }
1009
1010  /// addTopLevelLoop - This adds the specified loop to the collection of
1011  /// top-level loops.
1012  inline void addTopLevelLoop(Loop *New) {
1013    LI.addTopLevelLoop(New);
1014  }
1015
1016  /// removeBlock - This method completely removes BB from all data structures,
1017  /// including all of the Loop objects it is nested in and our mapping from
1018  /// BasicBlocks to loops.
1019  void removeBlock(BasicBlock *BB) {
1020    LI.removeBlock(BB);
1021  }
1022};
1023
1024
1025// Allow clients to walk the list of nested loops...
1026template <> struct GraphTraits<const Loop*> {
1027  typedef const Loop NodeType;
1028  typedef LoopInfo::iterator ChildIteratorType;
1029
1030  static NodeType *getEntryNode(const Loop *L) { return L; }
1031  static inline ChildIteratorType child_begin(NodeType *N) {
1032    return N->begin();
1033  }
1034  static inline ChildIteratorType child_end(NodeType *N) {
1035    return N->end();
1036  }
1037};
1038
1039template <> struct GraphTraits<Loop*> {
1040  typedef Loop NodeType;
1041  typedef LoopInfo::iterator ChildIteratorType;
1042
1043  static NodeType *getEntryNode(Loop *L) { return L; }
1044  static inline ChildIteratorType child_begin(NodeType *N) {
1045    return N->begin();
1046  }
1047  static inline ChildIteratorType child_end(NodeType *N) {
1048    return N->end();
1049  }
1050};
1051
1052template<class BlockT, class LoopT>
1053void
1054LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1055                                             LoopInfoBase<BlockT, LoopT> &LIB) {
1056  assert((Blocks.empty() || LIB[getHeader()] == this) &&
1057         "Incorrect LI specified for this loop!");
1058  assert(NewBB && "Cannot add a null basic block to the loop!");
1059  assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1060
1061  LoopT *L = static_cast<LoopT *>(this);
1062
1063  // Add the loop mapping to the LoopInfo object...
1064  LIB.BBMap[NewBB] = L;
1065
1066  // Add the basic block to this loop and all parent loops...
1067  while (L) {
1068    L->Blocks.push_back(NewBB);
1069    L = L->getParentLoop();
1070  }
1071}
1072
1073} // End llvm namespace
1074
1075#endif
1076