db5ce2118cb5c7979d9c8038bd9c79f603c8bf31
[oota-llvm.git] / lib / Analysis / LoopInfo.cpp
1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the LoopInfo class that is used to identify natural loops
11 // and determine the loop depth of various nodes of the CFG.  Note that the
12 // loops identified may actually be several natural loops that share the same
13 // header node... not just a single natural loop.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Support/Streams.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 char LoopInfo::ID = 0;
30 static RegisterPass<LoopInfo>
31 X("loops", "Natural Loop Information", true, true);
32
33 //===----------------------------------------------------------------------===//
34 // Loop implementation
35 //
36
37 /// isLoopInvariant - Return true if the specified value is loop invariant
38 ///
39 bool Loop::isLoopInvariant(Value *V) const {
40   if (Instruction *I = dyn_cast<Instruction>(V))
41     return !contains(I->getParent());
42   return true;  // All non-instructions are loop invariant
43 }
44
45 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
46 /// induction variable: an integer recurrence that starts at 0 and increments
47 /// by one each time through the loop.  If so, return the phi node that
48 /// corresponds to it.
49 ///
50 /// The IndVarSimplify pass transforms loops to have a canonical induction
51 /// variable.
52 ///
53 PHINode *Loop::getCanonicalInductionVariable() const {
54   BasicBlock *H = getHeader();
55
56   BasicBlock *Incoming = 0, *Backedge = 0;
57   typedef GraphTraits<Inverse<BasicBlock*> > InvBlockTraits;
58   InvBlockTraits::ChildIteratorType PI = InvBlockTraits::child_begin(H);
59   assert(PI != InvBlockTraits::child_end(H) &&
60          "Loop must have at least one backedge!");
61   Backedge = *PI++;
62   if (PI == InvBlockTraits::child_end(H)) return 0;  // dead loop
63   Incoming = *PI++;
64   if (PI != InvBlockTraits::child_end(H)) return 0;  // multiple backedges?
65
66   if (contains(Incoming)) {
67     if (contains(Backedge))
68       return 0;
69     std::swap(Incoming, Backedge);
70   } else if (!contains(Backedge))
71     return 0;
72
73   // Loop over all of the PHI nodes, looking for a canonical indvar.
74   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
75     PHINode *PN = cast<PHINode>(I);
76     if (ConstantInt *CI =
77         dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
78       if (CI->isNullValue())
79         if (Instruction *Inc =
80             dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
81           if (Inc->getOpcode() == Instruction::Add &&
82                 Inc->getOperand(0) == PN)
83             if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
84               if (CI->equalsInt(1))
85                 return PN;
86   }
87   return 0;
88 }
89
90 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
91 /// the canonical induction variable value for the "next" iteration of the
92 /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
93 ///
94 Instruction *Loop::getCanonicalInductionVariableIncrement() const {
95   if (PHINode *PN = getCanonicalInductionVariable()) {
96     bool P1InLoop = contains(PN->getIncomingBlock(1));
97     return cast<Instruction>(PN->getIncomingValue(P1InLoop));
98   }
99   return 0;
100 }
101
102 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
103 /// times the loop will be executed.  Note that this means that the backedge
104 /// of the loop executes N-1 times.  If the trip-count cannot be determined,
105 /// this returns null.
106 ///
107 /// The IndVarSimplify pass transforms loops to have a form that this
108 /// function easily understands.
109 ///
110 Value *Loop::getTripCount() const {
111   // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
112   // canonical induction variable and V is the trip count of the loop.
113   Instruction *Inc = getCanonicalInductionVariableIncrement();
114   if (Inc == 0) return 0;
115   PHINode *IV = cast<PHINode>(Inc->getOperand(0));
116
117   BasicBlock *BackedgeBlock =
118     IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
119
120   if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
121     if (BI->isConditional()) {
122       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
123         if (ICI->getOperand(0) == Inc) {
124           if (BI->getSuccessor(0) == getHeader()) {
125             if (ICI->getPredicate() == ICmpInst::ICMP_NE)
126               return ICI->getOperand(1);
127           } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
128             return ICI->getOperand(1);
129           }
130         }
131       }
132     }
133
134   return 0;
135 }
136
137 /// getSmallConstantTripCount - Returns the trip count of this loop as a
138 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
139 /// of not constant. Will also return 0 if the trip count is very large
140 /// (>= 2^32)
141 unsigned Loop::getSmallConstantTripCount() const {
142   Value* TripCount = this->getTripCount();
143   if (TripCount) {
144     if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCount)) {
145       // Guard against huge trip counts.
146       if (TripCountC->getValue().getActiveBits() <= 32) {
147         return (unsigned)TripCountC->getZExtValue();
148       }
149     }
150   }
151   return 0;
152 }
153
154 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
155 /// trip count of this loop as a normal unsigned value, if possible. This
156 /// means that the actual trip count is always a multiple of the returned
157 /// value (don't forget the trip count could very well be zero as well!).
158 ///
159 /// Returns 1 if the trip count is unknown or not guaranteed to be the
160 /// multiple of a constant (which is also the case if the trip count is simply
161 /// constant, use getSmallConstantTripCount for that case), Will also return 1
162 /// if the trip count is very large (>= 2^32).
163 unsigned Loop::getSmallConstantTripMultiple() const {
164   Value* TripCount = this->getTripCount();
165   // This will hold the ConstantInt result, if any
166   ConstantInt *Result = NULL;
167   if (TripCount) {
168     // See if the trip count is constant itself
169     Result = dyn_cast<ConstantInt>(TripCount);
170     // if not, see if it is a multiplication
171     if (!Result)
172       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCount)) {
173         switch (BO->getOpcode()) {
174         case BinaryOperator::Mul:
175           Result = dyn_cast<ConstantInt>(BO->getOperand(1));
176           break;
177         default:
178           break;
179         }
180       }
181   }
182   // Guard against huge trip counts.
183   if (Result && Result->getValue().getActiveBits() <= 32) {
184     return (unsigned)Result->getZExtValue();
185   } else {
186     return 1;
187   }
188 }
189
190 /// isLCSSAForm - Return true if the Loop is in LCSSA form
191 bool Loop::isLCSSAForm() const {
192   // Sort the blocks vector so that we can use binary search to do quick
193   // lookups.
194   SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
195
196   for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
197     BasicBlock  *BB = *BI;
198     for (BasicBlock ::iterator I = BB->begin(), E = BB->end(); I != E;++I)
199       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
200            ++UI) {
201         BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
202         if (PHINode *P = dyn_cast<PHINode>(*UI)) {
203           UserBB = P->getIncomingBlock(UI);
204         }
205
206         // Check the current block, as a fast-path.  Most values are used in
207         // the same block they are defined in.
208         if (UserBB != BB && !LoopBBs.count(UserBB))
209           return false;
210       }
211   }
212
213   return true;
214 }
215 //===----------------------------------------------------------------------===//
216 // LoopInfo implementation
217 //
218 bool LoopInfo::runOnFunction(Function &) {
219   releaseMemory();
220   LI.Calculate(getAnalysis<DominatorTree>().getBase());    // Update
221   return false;
222 }
223
224 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
225   AU.setPreservesAll();
226   AU.addRequired<DominatorTree>();
227 }