blob: 46219d1b6f55cc810313f7a8083c7aca35c12b92 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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"
Dan Gohman07fbbcd2009-09-28 00:27:48 +000023#include "llvm/Support/CommandLine.h"
Dan Gohmane1b383f2010-01-05 21:08:02 +000024#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/ADT/DepthFirstIterator.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028using namespace llvm;
29
Dan Gohman07fbbcd2009-09-28 00:27:48 +000030// Always verify loopinfo if expensive checking is enabled.
31#ifdef XDEBUG
Dan Gohman738422f2010-04-15 17:08:50 +000032static bool VerifyLoopInfo = true;
Dan Gohman07fbbcd2009-09-28 00:27:48 +000033#else
Dan Gohman738422f2010-04-15 17:08:50 +000034static bool VerifyLoopInfo = false;
Dan Gohman07fbbcd2009-09-28 00:27:48 +000035#endif
36static cl::opt<bool,true>
37VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
38 cl::desc("Verify loop info (time consuming)"));
39
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040char LoopInfo::ID = 0;
Owen Anderson6374c3d2010-07-21 22:09:45 +000041INITIALIZE_PASS(LoopInfo, "loops", "Natural Loop Information", true, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042
43//===----------------------------------------------------------------------===//
44// Loop implementation
45//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046
Dan Gohman62d0d312009-07-13 22:02:44 +000047/// isLoopInvariant - Return true if the specified value is loop invariant
48///
49bool Loop::isLoopInvariant(Value *V) const {
50 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman71356152009-07-14 01:06:29 +000051 return isLoopInvariant(I);
Dan Gohman62d0d312009-07-13 22:02:44 +000052 return true; // All non-instructions are loop invariant
53}
54
Dan Gohman71356152009-07-14 01:06:29 +000055/// isLoopInvariant - Return true if the specified instruction is
56/// loop-invariant.
57///
58bool Loop::isLoopInvariant(Instruction *I) const {
Dan Gohmane8df7dd2009-12-18 01:24:09 +000059 return !contains(I);
Dan Gohman71356152009-07-14 01:06:29 +000060}
61
62/// makeLoopInvariant - If the given value is an instruciton inside of the
63/// loop and it can be hoisted, do so to make it trivially loop-invariant.
64/// Return true if the value after any hoisting is loop invariant. This
65/// function can be used as a slightly more aggressive replacement for
66/// isLoopInvariant.
67///
68/// If InsertPt is specified, it is the point to hoist instructions to.
69/// If null, the terminator of the loop preheader is used.
70///
Dan Gohmanc80f5242009-07-15 01:25:43 +000071bool Loop::makeLoopInvariant(Value *V, bool &Changed,
72 Instruction *InsertPt) const {
Dan Gohman71356152009-07-14 01:06:29 +000073 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc80f5242009-07-15 01:25:43 +000074 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman71356152009-07-14 01:06:29 +000075 return true; // All non-instructions are loop-invariant.
76}
77
78/// makeLoopInvariant - If the given instruction is inside of the
79/// loop and it can be hoisted, do so to make it trivially loop-invariant.
80/// Return true if the instruction after any hoisting is loop invariant. This
81/// function can be used as a slightly more aggressive replacement for
82/// isLoopInvariant.
83///
84/// If InsertPt is specified, it is the point to hoist instructions to.
85/// If null, the terminator of the loop preheader is used.
86///
Dan Gohmanc80f5242009-07-15 01:25:43 +000087bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
88 Instruction *InsertPt) const {
Dan Gohman71356152009-07-14 01:06:29 +000089 // Test if the value is already loop-invariant.
90 if (isLoopInvariant(I))
91 return true;
Eli Friedman490e6c72009-07-17 04:28:42 +000092 if (!I->isSafeToSpeculativelyExecute())
Dan Gohman71356152009-07-14 01:06:29 +000093 return false;
Eli Friedman490e6c72009-07-17 04:28:42 +000094 if (I->mayReadFromMemory())
Dan Gohman71356152009-07-14 01:06:29 +000095 return false;
96 // Determine the insertion point, unless one was given.
97 if (!InsertPt) {
98 BasicBlock *Preheader = getLoopPreheader();
99 // Without a preheader, hoisting is not feasible.
100 if (!Preheader)
101 return false;
102 InsertPt = Preheader->getTerminator();
103 }
104 // Don't hoist instructions with loop-variant operands.
105 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanc80f5242009-07-15 01:25:43 +0000106 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohman71356152009-07-14 01:06:29 +0000107 return false;
108 // Hoist.
109 I->moveBefore(InsertPt);
Dan Gohmanc80f5242009-07-15 01:25:43 +0000110 Changed = true;
Dan Gohman71356152009-07-14 01:06:29 +0000111 return true;
112}
113
Dan Gohman62d0d312009-07-13 22:02:44 +0000114/// getCanonicalInductionVariable - Check to see if the loop has a canonical
115/// induction variable: an integer recurrence that starts at 0 and increments
116/// by one each time through the loop. If so, return the phi node that
117/// corresponds to it.
118///
119/// The IndVarSimplify pass transforms loops to have a canonical induction
120/// variable.
121///
122PHINode *Loop::getCanonicalInductionVariable() const {
123 BasicBlock *H = getHeader();
124
125 BasicBlock *Incoming = 0, *Backedge = 0;
Dan Gohman55391f52010-07-23 21:25:16 +0000126 pred_iterator PI = pred_begin(H);
127 assert(PI != pred_end(H) &&
Dan Gohman62d0d312009-07-13 22:02:44 +0000128 "Loop must have at least one backedge!");
129 Backedge = *PI++;
Dan Gohman55391f52010-07-23 21:25:16 +0000130 if (PI == pred_end(H)) return 0; // dead loop
Dan Gohman62d0d312009-07-13 22:02:44 +0000131 Incoming = *PI++;
Dan Gohman55391f52010-07-23 21:25:16 +0000132 if (PI != pred_end(H)) return 0; // multiple backedges?
Dan Gohman62d0d312009-07-13 22:02:44 +0000133
134 if (contains(Incoming)) {
135 if (contains(Backedge))
136 return 0;
137 std::swap(Incoming, Backedge);
138 } else if (!contains(Backedge))
139 return 0;
140
141 // Loop over all of the PHI nodes, looking for a canonical indvar.
142 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
143 PHINode *PN = cast<PHINode>(I);
144 if (ConstantInt *CI =
145 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
146 if (CI->isNullValue())
147 if (Instruction *Inc =
148 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
149 if (Inc->getOpcode() == Instruction::Add &&
150 Inc->getOperand(0) == PN)
151 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
152 if (CI->equalsInt(1))
153 return PN;
154 }
155 return 0;
156}
157
Dan Gohman62d0d312009-07-13 22:02:44 +0000158/// getTripCount - Return a loop-invariant LLVM value indicating the number of
159/// times the loop will be executed. Note that this means that the backedge
160/// of the loop executes N-1 times. If the trip-count cannot be determined,
161/// this returns null.
162///
163/// The IndVarSimplify pass transforms loops to have a form that this
164/// function easily understands.
165///
166Value *Loop::getTripCount() const {
167 // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
168 // canonical induction variable and V is the trip count of the loop.
Dan Gohman73f10f72010-07-23 21:34:51 +0000169 PHINode *IV = getCanonicalInductionVariable();
170 if (IV == 0 || IV->getNumIncomingValues() != 2) return 0;
Dan Gohman62d0d312009-07-13 22:02:44 +0000171
Dan Gohman73f10f72010-07-23 21:34:51 +0000172 bool P0InLoop = contains(IV->getIncomingBlock(0));
173 Value *Inc = IV->getIncomingValue(!P0InLoop);
174 BasicBlock *BackedgeBlock = IV->getIncomingBlock(!P0InLoop);
Dan Gohman62d0d312009-07-13 22:02:44 +0000175
176 if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
177 if (BI->isConditional()) {
178 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
179 if (ICI->getOperand(0) == Inc) {
180 if (BI->getSuccessor(0) == getHeader()) {
181 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
182 return ICI->getOperand(1);
183 } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
184 return ICI->getOperand(1);
185 }
186 }
187 }
188 }
189
190 return 0;
191}
192
193/// getSmallConstantTripCount - Returns the trip count of this loop as a
194/// normal unsigned value, if possible. Returns 0 if the trip count is unknown
195/// of not constant. Will also return 0 if the trip count is very large
196/// (>= 2^32)
197unsigned Loop::getSmallConstantTripCount() const {
198 Value* TripCount = this->getTripCount();
199 if (TripCount) {
200 if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCount)) {
201 // Guard against huge trip counts.
202 if (TripCountC->getValue().getActiveBits() <= 32) {
203 return (unsigned)TripCountC->getZExtValue();
204 }
205 }
206 }
207 return 0;
208}
209
210/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
211/// trip count of this loop as a normal unsigned value, if possible. This
212/// means that the actual trip count is always a multiple of the returned
213/// value (don't forget the trip count could very well be zero as well!).
214///
215/// Returns 1 if the trip count is unknown or not guaranteed to be the
216/// multiple of a constant (which is also the case if the trip count is simply
217/// constant, use getSmallConstantTripCount for that case), Will also return 1
218/// if the trip count is very large (>= 2^32).
219unsigned Loop::getSmallConstantTripMultiple() const {
220 Value* TripCount = this->getTripCount();
221 // This will hold the ConstantInt result, if any
222 ConstantInt *Result = NULL;
223 if (TripCount) {
224 // See if the trip count is constant itself
225 Result = dyn_cast<ConstantInt>(TripCount);
226 // if not, see if it is a multiplication
227 if (!Result)
228 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCount)) {
229 switch (BO->getOpcode()) {
230 case BinaryOperator::Mul:
231 Result = dyn_cast<ConstantInt>(BO->getOperand(1));
232 break;
Dan Gohmanb1b77e72009-11-20 01:09:34 +0000233 case BinaryOperator::Shl:
234 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
235 if (CI->getValue().getActiveBits() <= 5)
236 return 1u << CI->getZExtValue();
237 break;
Dan Gohman62d0d312009-07-13 22:02:44 +0000238 default:
239 break;
240 }
241 }
242 }
243 // Guard against huge trip counts.
244 if (Result && Result->getValue().getActiveBits() <= 32) {
245 return (unsigned)Result->getZExtValue();
246 } else {
247 return 1;
248 }
249}
250
251/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohmana76b5582010-03-10 19:38:49 +0000252bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman62d0d312009-07-13 22:02:44 +0000253 // Sort the blocks vector so that we can use binary search to do quick
254 // lookups.
Gabor Greif888e0a92010-07-09 14:28:41 +0000255 SmallPtrSet<BasicBlock*, 16> LoopBBs(block_begin(), block_end());
Dan Gohman62d0d312009-07-13 22:02:44 +0000256
257 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohmanfe7d6aa2009-11-09 18:19:43 +0000258 BasicBlock *BB = *BI;
259 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Dan Gohman62d0d312009-07-13 22:02:44 +0000260 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
261 ++UI) {
Gabor Greif888e0a92010-07-09 14:28:41 +0000262 User *U = *UI;
263 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
264 if (PHINode *P = dyn_cast<PHINode>(U))
Dan Gohman62d0d312009-07-13 22:02:44 +0000265 UserBB = P->getIncomingBlock(UI);
Dan Gohman62d0d312009-07-13 22:02:44 +0000266
Dan Gohman007a6b32010-03-09 01:53:33 +0000267 // Check the current block, as a fast-path, before checking whether
268 // the use is anywhere in the loop. Most values are used in the same
269 // block they are defined in. Also, blocks not reachable from the
270 // entry are special; uses in them don't need to go through PHIs.
271 if (UserBB != BB &&
272 !LoopBBs.count(UserBB) &&
Dan Gohmana76b5582010-03-10 19:38:49 +0000273 DT.isReachableFromEntry(UserBB))
Dan Gohman62d0d312009-07-13 22:02:44 +0000274 return false;
275 }
276 }
277
278 return true;
279}
Dan Gohmanafc3ae32009-07-16 16:16:23 +0000280
281/// isLoopSimplifyForm - Return true if the Loop is in the form that
282/// the LoopSimplify form transforms loops to, which is sometimes called
283/// normal form.
284bool Loop::isLoopSimplifyForm() const {
Dan Gohman47927a32009-11-05 19:21:41 +0000285 // Normal-form loops have a preheader, a single backedge, and all of their
286 // exits have all their predecessors inside the loop.
287 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
288}
289
290/// hasDedicatedExits - Return true if no exit block for the loop
291/// has a predecessor that is outside the loop.
292bool Loop::hasDedicatedExits() const {
Dan Gohman8ec50242009-10-20 20:41:13 +0000293 // Sort the blocks vector so that we can use binary search to do quick
294 // lookups.
295 SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
Dan Gohmanafc3ae32009-07-16 16:16:23 +0000296 // Each predecessor of each exit block of a normal loop is contained
297 // within the loop.
298 SmallVector<BasicBlock *, 4> ExitBlocks;
299 getExitBlocks(ExitBlocks);
300 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
301 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
302 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
Dan Gohman8ec50242009-10-20 20:41:13 +0000303 if (!LoopBBs.count(*PI))
Dan Gohmanafc3ae32009-07-16 16:16:23 +0000304 return false;
305 // All the requirements are met.
306 return true;
307}
308
Dan Gohman5c42c872009-09-03 16:10:48 +0000309/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
310/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman10ef46f2009-12-11 20:05:23 +0000311/// This assumes that loop exits are in canonical form.
Dan Gohman5c42c872009-09-03 16:10:48 +0000312///
313void
314Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman10ef46f2009-12-11 20:05:23 +0000315 assert(hasDedicatedExits() &&
316 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman9cec4122009-09-08 15:45:00 +0000317
Dan Gohman5c42c872009-09-03 16:10:48 +0000318 // Sort the blocks vector so that we can use binary search to do quick
319 // lookups.
320 SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
321 std::sort(LoopBBs.begin(), LoopBBs.end());
322
Dan Gohmanff6a63a2009-09-03 20:36:13 +0000323 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohman5c42c872009-09-03 16:10:48 +0000324
325 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
326
327 BasicBlock *current = *BI;
328 switchExitBlocks.clear();
329
Dan Gohman55391f52010-07-23 21:25:16 +0000330 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohman5c42c872009-09-03 16:10:48 +0000331 // If block is inside the loop then it is not a exit block.
332 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
333 continue;
334
Dan Gohman55391f52010-07-23 21:25:16 +0000335 pred_iterator PI = pred_begin(*I);
Dan Gohman5c42c872009-09-03 16:10:48 +0000336 BasicBlock *firstPred = *PI;
337
338 // If current basic block is this exit block's first predecessor
339 // then only insert exit block in to the output ExitBlocks vector.
340 // This ensures that same exit block is not inserted twice into
341 // ExitBlocks vector.
342 if (current != firstPred)
343 continue;
344
345 // If a terminator has more then two successors, for example SwitchInst,
346 // then it is possible that there are multiple edges from current block
347 // to one exit block.
Dan Gohman55391f52010-07-23 21:25:16 +0000348 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Dan Gohman5c42c872009-09-03 16:10:48 +0000349 ExitBlocks.push_back(*I);
350 continue;
351 }
352
353 // In case of multiple edges from current block to exit block, collect
354 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
355 // duplicate edges.
356 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
357 == switchExitBlocks.end()) {
358 switchExitBlocks.push_back(*I);
359 ExitBlocks.push_back(*I);
360 }
361 }
362 }
363}
364
365/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
366/// block, return that block. Otherwise return null.
367BasicBlock *Loop::getUniqueExitBlock() const {
368 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
369 getUniqueExitBlocks(UniqueExitBlocks);
370 if (UniqueExitBlocks.size() == 1)
371 return UniqueExitBlocks[0];
372 return 0;
373}
374
Dan Gohmane1b383f2010-01-05 21:08:02 +0000375void Loop::dump() const {
376 print(dbgs());
377}
378
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379//===----------------------------------------------------------------------===//
380// LoopInfo implementation
381//
382bool LoopInfo::runOnFunction(Function &) {
383 releaseMemory();
Dan Gohman9b0abfe2009-06-27 21:22:48 +0000384 LI.Calculate(getAnalysis<DominatorTree>().getBase()); // Update
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385 return false;
386}
387
Dan Gohman9cec4122009-09-08 15:45:00 +0000388void LoopInfo::verifyAnalysis() const {
Dan Gohman07fbbcd2009-09-28 00:27:48 +0000389 // LoopInfo is a FunctionPass, but verifying every loop in the function
390 // each time verifyAnalysis is called is very expensive. The
391 // -verify-loop-info option can enable this. In order to perform some
392 // checking by default, LoopPass has been taught to call verifyLoop
393 // manually during loop pass sequences.
394
395 if (!VerifyLoopInfo) return;
396
Dan Gohman9cec4122009-09-08 15:45:00 +0000397 for (iterator I = begin(), E = end(); I != E; ++I) {
398 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
399 (*I)->verifyLoopNest();
400 }
Dan Gohman07fbbcd2009-09-28 00:27:48 +0000401
402 // TODO: check BBMap consistency.
Dan Gohman9cec4122009-09-08 15:45:00 +0000403}
404
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
406 AU.setPreservesAll();
407 AU.addRequired<DominatorTree>();
408}
Chris Lattnera7a9daa2009-08-23 05:17:37 +0000409
Chris Lattner397f4562009-08-23 06:03:38 +0000410void LoopInfo::print(raw_ostream &OS, const Module*) const {
411 LI.print(OS);
Chris Lattnera7a9daa2009-08-23 05:17:37 +0000412}
413