blob: c7833bf7bb6376c58b9514afee4936d389b85aa3 [file] [log] [blame]
Chris Lattnercf3056d2003-10-13 03:32:08 +00001//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner0bbe58f2001-11-26 18:41:20 +00009//
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
Misha Brukman10d208d2004-01-30 17:26:24 +000017#include "llvm/Analysis/LoopInfo.h"
Chris Lattner92020fa2004-04-15 15:16:02 +000018#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
20#include "llvm/Analysis/Dominators.h"
Andrew Trick2d31ae32011-08-10 01:59:05 +000021#include "llvm/Analysis/LoopIterator.h"
Chris Lattnera59cbb22002-07-27 01:12:17 +000022#include "llvm/Assembly/Writer.h"
Misha Brukman10d208d2004-01-30 17:26:24 +000023#include "llvm/Support/CFG.h"
Dan Gohman9450b0e2009-09-28 00:27:48 +000024#include "llvm/Support/CommandLine.h"
Dan Gohmandda30cd2010-01-05 21:08:02 +000025#include "llvm/Support/Debug.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattnerb1f5d8b2007-03-04 04:06:39 +000027#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000028#include <algorithm>
Chris Lattner46758a82004-04-12 20:26:17 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Dan Gohman9450b0e2009-09-28 00:27:48 +000031// Always verify loopinfo if expensive checking is enabled.
32#ifdef XDEBUG
Dan Gohmanb3579832010-04-15 17:08:50 +000033static bool VerifyLoopInfo = true;
Dan Gohman9450b0e2009-09-28 00:27:48 +000034#else
Dan Gohmanb3579832010-04-15 17:08:50 +000035static bool VerifyLoopInfo = false;
Dan Gohman9450b0e2009-09-28 00:27:48 +000036#endif
37static cl::opt<bool,true>
38VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
39 cl::desc("Verify loop info (time consuming)"));
40
Devang Patel19974732007-05-03 01:11:54 +000041char LoopInfo::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000042INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
43INITIALIZE_PASS_DEPENDENCY(DominatorTree)
44INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
Chris Lattner93193f82002-01-31 00:42:27 +000045
46//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000047// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000048//
Misha Brukman6b290a52002-10-11 05:31:10 +000049
Dan Gohman16a2c922009-07-13 22:02:44 +000050/// isLoopInvariant - Return true if the specified value is loop invariant
51///
52bool Loop::isLoopInvariant(Value *V) const {
53 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattneradc79912010-09-06 01:05:37 +000054 return !contains(I);
Dan Gohman16a2c922009-07-13 22:02:44 +000055 return true; // All non-instructions are loop invariant
56}
57
Chris Lattneradc79912010-09-06 01:05:37 +000058/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trick882bcc62011-08-03 23:45:50 +000059/// specified instruction are loop invariant.
Chris Lattneradc79912010-09-06 01:05:37 +000060bool Loop::hasLoopInvariantOperands(Instruction *I) const {
61 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
62 if (!isLoopInvariant(I->getOperand(i)))
63 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +000064
Chris Lattneradc79912010-09-06 01:05:37 +000065 return true;
Dan Gohmana3420262009-07-14 01:06:29 +000066}
67
68/// makeLoopInvariant - If the given value is an instruciton inside of the
69/// loop and it can be hoisted, do so to make it trivially loop-invariant.
70/// Return true if the value after any hoisting is loop invariant. This
71/// function can be used as a slightly more aggressive replacement for
72/// isLoopInvariant.
73///
74/// If InsertPt is specified, it is the point to hoist instructions to.
75/// If null, the terminator of the loop preheader is used.
76///
Dan Gohmanbdc017e2009-07-15 01:25:43 +000077bool Loop::makeLoopInvariant(Value *V, bool &Changed,
78 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000079 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanbdc017e2009-07-15 01:25:43 +000080 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohmana3420262009-07-14 01:06:29 +000081 return true; // All non-instructions are loop-invariant.
82}
83
84/// makeLoopInvariant - If the given instruction is inside of the
85/// loop and it can be hoisted, do so to make it trivially loop-invariant.
86/// Return true if the instruction after any hoisting is loop invariant. This
87/// function can be used as a slightly more aggressive replacement for
88/// isLoopInvariant.
89///
90/// If InsertPt is specified, it is the point to hoist instructions to.
91/// If null, the terminator of the loop preheader is used.
92///
Dan Gohmanbdc017e2009-07-15 01:25:43 +000093bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
94 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000095 // Test if the value is already loop-invariant.
96 if (isLoopInvariant(I))
97 return true;
Eli Friedman0b79a772009-07-17 04:28:42 +000098 if (!I->isSafeToSpeculativelyExecute())
Dan Gohmana3420262009-07-14 01:06:29 +000099 return false;
Eli Friedman0b79a772009-07-17 04:28:42 +0000100 if (I->mayReadFromMemory())
Dan Gohmana3420262009-07-14 01:06:29 +0000101 return false;
Bill Wendlingc9b2a982011-08-17 20:36:44 +0000102 // The landingpad instruction is immobile.
103 if (isa<LandingPadInst>(I))
104 return false;
Dan Gohmana3420262009-07-14 01:06:29 +0000105 // Determine the insertion point, unless one was given.
106 if (!InsertPt) {
107 BasicBlock *Preheader = getLoopPreheader();
108 // Without a preheader, hoisting is not feasible.
109 if (!Preheader)
110 return false;
111 InsertPt = Preheader->getTerminator();
112 }
113 // Don't hoist instructions with loop-variant operands.
114 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000115 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohmana3420262009-07-14 01:06:29 +0000116 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +0000117
Dan Gohmana3420262009-07-14 01:06:29 +0000118 // Hoist.
119 I->moveBefore(InsertPt);
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000120 Changed = true;
Dan Gohmana3420262009-07-14 01:06:29 +0000121 return true;
122}
123
Dan Gohman16a2c922009-07-13 22:02:44 +0000124/// getCanonicalInductionVariable - Check to see if the loop has a canonical
125/// induction variable: an integer recurrence that starts at 0 and increments
126/// by one each time through the loop. If so, return the phi node that
127/// corresponds to it.
128///
129/// The IndVarSimplify pass transforms loops to have a canonical induction
130/// variable.
131///
132PHINode *Loop::getCanonicalInductionVariable() const {
133 BasicBlock *H = getHeader();
134
135 BasicBlock *Incoming = 0, *Backedge = 0;
Dan Gohman63137d52010-07-23 21:25:16 +0000136 pred_iterator PI = pred_begin(H);
137 assert(PI != pred_end(H) &&
Dan Gohman16a2c922009-07-13 22:02:44 +0000138 "Loop must have at least one backedge!");
139 Backedge = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000140 if (PI == pred_end(H)) return 0; // dead loop
Dan Gohman16a2c922009-07-13 22:02:44 +0000141 Incoming = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000142 if (PI != pred_end(H)) return 0; // multiple backedges?
Dan Gohman16a2c922009-07-13 22:02:44 +0000143
144 if (contains(Incoming)) {
145 if (contains(Backedge))
146 return 0;
147 std::swap(Incoming, Backedge);
148 } else if (!contains(Backedge))
149 return 0;
150
151 // Loop over all of the PHI nodes, looking for a canonical indvar.
152 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
153 PHINode *PN = cast<PHINode>(I);
154 if (ConstantInt *CI =
155 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
156 if (CI->isNullValue())
157 if (Instruction *Inc =
158 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
159 if (Inc->getOpcode() == Instruction::Add &&
160 Inc->getOperand(0) == PN)
161 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
162 if (CI->equalsInt(1))
163 return PN;
164 }
165 return 0;
166}
167
Dan Gohman16a2c922009-07-13 22:02:44 +0000168/// getTripCount - Return a loop-invariant LLVM value indicating the number of
169/// times the loop will be executed. Note that this means that the backedge
170/// of the loop executes N-1 times. If the trip-count cannot be determined,
171/// this returns null.
172///
173/// The IndVarSimplify pass transforms loops to have a form that this
174/// function easily understands.
175///
176Value *Loop::getTripCount() const {
177 // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
178 // canonical induction variable and V is the trip count of the loop.
Dan Gohmanf8336a72010-07-23 21:34:51 +0000179 PHINode *IV = getCanonicalInductionVariable();
180 if (IV == 0 || IV->getNumIncomingValues() != 2) return 0;
Dan Gohman16a2c922009-07-13 22:02:44 +0000181
Dan Gohmanf8336a72010-07-23 21:34:51 +0000182 bool P0InLoop = contains(IV->getIncomingBlock(0));
183 Value *Inc = IV->getIncomingValue(!P0InLoop);
184 BasicBlock *BackedgeBlock = IV->getIncomingBlock(!P0InLoop);
Dan Gohman16a2c922009-07-13 22:02:44 +0000185
186 if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
187 if (BI->isConditional()) {
188 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
189 if (ICI->getOperand(0) == Inc) {
190 if (BI->getSuccessor(0) == getHeader()) {
191 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
192 return ICI->getOperand(1);
193 } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
194 return ICI->getOperand(1);
195 }
196 }
197 }
198 }
199
200 return 0;
201}
202
203/// getSmallConstantTripCount - Returns the trip count of this loop as a
204/// normal unsigned value, if possible. Returns 0 if the trip count is unknown
Duncan Sands768b87c2010-11-13 12:16:27 +0000205/// or not constant. Will also return 0 if the trip count is very large
Dan Gohman16a2c922009-07-13 22:02:44 +0000206/// (>= 2^32)
207unsigned Loop::getSmallConstantTripCount() const {
208 Value* TripCount = this->getTripCount();
209 if (TripCount) {
210 if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCount)) {
211 // Guard against huge trip counts.
212 if (TripCountC->getValue().getActiveBits() <= 32) {
213 return (unsigned)TripCountC->getZExtValue();
214 }
215 }
216 }
217 return 0;
218}
219
220/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
221/// trip count of this loop as a normal unsigned value, if possible. This
222/// means that the actual trip count is always a multiple of the returned
223/// value (don't forget the trip count could very well be zero as well!).
224///
225/// Returns 1 if the trip count is unknown or not guaranteed to be the
226/// multiple of a constant (which is also the case if the trip count is simply
227/// constant, use getSmallConstantTripCount for that case), Will also return 1
228/// if the trip count is very large (>= 2^32).
229unsigned Loop::getSmallConstantTripMultiple() const {
230 Value* TripCount = this->getTripCount();
231 // This will hold the ConstantInt result, if any
232 ConstantInt *Result = NULL;
233 if (TripCount) {
234 // See if the trip count is constant itself
235 Result = dyn_cast<ConstantInt>(TripCount);
236 // if not, see if it is a multiplication
237 if (!Result)
238 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCount)) {
239 switch (BO->getOpcode()) {
240 case BinaryOperator::Mul:
241 Result = dyn_cast<ConstantInt>(BO->getOperand(1));
242 break;
Dan Gohmanac146652009-11-20 01:09:34 +0000243 case BinaryOperator::Shl:
244 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
245 if (CI->getValue().getActiveBits() <= 5)
246 return 1u << CI->getZExtValue();
247 break;
Dan Gohman16a2c922009-07-13 22:02:44 +0000248 default:
249 break;
250 }
251 }
252 }
253 // Guard against huge trip counts.
254 if (Result && Result->getValue().getActiveBits() <= 32) {
255 return (unsigned)Result->getZExtValue();
256 } else {
257 return 1;
258 }
259}
260
261/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000262bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman16a2c922009-07-13 22:02:44 +0000263 // Sort the blocks vector so that we can use binary search to do quick
264 // lookups.
Gabor Greif5891ac82010-07-09 14:28:41 +0000265 SmallPtrSet<BasicBlock*, 16> LoopBBs(block_begin(), block_end());
Dan Gohman16a2c922009-07-13 22:02:44 +0000266
267 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman81d893c2009-11-09 18:19:43 +0000268 BasicBlock *BB = *BI;
269 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Dan Gohman16a2c922009-07-13 22:02:44 +0000270 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
271 ++UI) {
Gabor Greif5891ac82010-07-09 14:28:41 +0000272 User *U = *UI;
273 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
274 if (PHINode *P = dyn_cast<PHINode>(U))
Dan Gohman16a2c922009-07-13 22:02:44 +0000275 UserBB = P->getIncomingBlock(UI);
Dan Gohman16a2c922009-07-13 22:02:44 +0000276
Dan Gohmancbac7f12010-03-09 01:53:33 +0000277 // Check the current block, as a fast-path, before checking whether
278 // the use is anywhere in the loop. Most values are used in the same
279 // block they are defined in. Also, blocks not reachable from the
280 // entry are special; uses in them don't need to go through PHIs.
281 if (UserBB != BB &&
282 !LoopBBs.count(UserBB) &&
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000283 DT.isReachableFromEntry(UserBB))
Dan Gohman16a2c922009-07-13 22:02:44 +0000284 return false;
285 }
286 }
287
288 return true;
289}
Dan Gohman93773862009-07-16 16:16:23 +0000290
291/// isLoopSimplifyForm - Return true if the Loop is in the form that
292/// the LoopSimplify form transforms loops to, which is sometimes called
293/// normal form.
294bool Loop::isLoopSimplifyForm() const {
Dan Gohmanf17e9512009-11-05 19:21:41 +0000295 // Normal-form loops have a preheader, a single backedge, and all of their
296 // exits have all their predecessors inside the loop.
297 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
298}
299
300/// hasDedicatedExits - Return true if no exit block for the loop
301/// has a predecessor that is outside the loop.
302bool Loop::hasDedicatedExits() const {
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000303 // Sort the blocks vector so that we can use binary search to do quick
304 // lookups.
305 SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
Dan Gohman93773862009-07-16 16:16:23 +0000306 // Each predecessor of each exit block of a normal loop is contained
307 // within the loop.
308 SmallVector<BasicBlock *, 4> ExitBlocks;
309 getExitBlocks(ExitBlocks);
310 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
311 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
312 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000313 if (!LoopBBs.count(*PI))
Dan Gohman93773862009-07-16 16:16:23 +0000314 return false;
315 // All the requirements are met.
316 return true;
317}
318
Dan Gohmanf0608d82009-09-03 16:10:48 +0000319/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
320/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman050959c2009-12-11 20:05:23 +0000321/// This assumes that loop exits are in canonical form.
Dan Gohmanf0608d82009-09-03 16:10:48 +0000322///
323void
324Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman050959c2009-12-11 20:05:23 +0000325 assert(hasDedicatedExits() &&
326 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman5c89b522009-09-08 15:45:00 +0000327
Dan Gohmanf0608d82009-09-03 16:10:48 +0000328 // Sort the blocks vector so that we can use binary search to do quick
329 // lookups.
330 SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
331 std::sort(LoopBBs.begin(), LoopBBs.end());
332
Dan Gohman058db922009-09-03 20:36:13 +0000333 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohmanf0608d82009-09-03 16:10:48 +0000334
335 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
336
337 BasicBlock *current = *BI;
338 switchExitBlocks.clear();
339
Dan Gohman63137d52010-07-23 21:25:16 +0000340 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000341 // If block is inside the loop then it is not a exit block.
342 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
343 continue;
344
Dan Gohman63137d52010-07-23 21:25:16 +0000345 pred_iterator PI = pred_begin(*I);
Dan Gohmanf0608d82009-09-03 16:10:48 +0000346 BasicBlock *firstPred = *PI;
347
348 // If current basic block is this exit block's first predecessor
349 // then only insert exit block in to the output ExitBlocks vector.
350 // This ensures that same exit block is not inserted twice into
351 // ExitBlocks vector.
352 if (current != firstPred)
353 continue;
354
355 // If a terminator has more then two successors, for example SwitchInst,
356 // then it is possible that there are multiple edges from current block
357 // to one exit block.
Dan Gohman63137d52010-07-23 21:25:16 +0000358 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000359 ExitBlocks.push_back(*I);
360 continue;
361 }
362
363 // In case of multiple edges from current block to exit block, collect
364 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
365 // duplicate edges.
366 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
367 == switchExitBlocks.end()) {
368 switchExitBlocks.push_back(*I);
369 ExitBlocks.push_back(*I);
370 }
371 }
372 }
373}
374
375/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
376/// block, return that block. Otherwise return null.
377BasicBlock *Loop::getUniqueExitBlock() const {
378 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
379 getUniqueExitBlocks(UniqueExitBlocks);
380 if (UniqueExitBlocks.size() == 1)
381 return UniqueExitBlocks[0];
382 return 0;
383}
384
Dan Gohmandda30cd2010-01-05 21:08:02 +0000385void Loop::dump() const {
386 print(dbgs());
387}
388
Chris Lattnera59cbb22002-07-27 01:12:17 +0000389//===----------------------------------------------------------------------===//
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000390// UnloopUpdater implementation
391//
392
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000393namespace {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000394/// Find the new parent loop for all blocks within the "unloop" whose last
395/// backedges has just been removed.
396class UnloopUpdater {
397 Loop *Unloop;
398 LoopInfo *LI;
399
400 LoopBlocksDFS DFS;
401
402 // Map unloop's immediate subloops to their nearest reachable parents. Nested
403 // loops within these subloops will not change parents. However, an immediate
404 // subloop's new parent will be the nearest loop reachable from either its own
405 // exits *or* any of its nested loop's exits.
406 DenseMap<Loop*, Loop*> SubloopParents;
407
408 // Flag the presence of an irreducible backedge whose destination is a block
409 // directly contained by the original unloop.
410 bool FoundIB;
411
412public:
413 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
414 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
415
416 void updateBlockParents();
417
Andrew Trickc12d9b92011-08-11 20:27:32 +0000418 void removeBlocksFromAncestors();
419
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000420 void updateSubloopParents();
421
422protected:
423 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
424};
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000425} // end anonymous namespace
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000426
427/// updateBlockParents - Update the parent loop for all blocks that are directly
428/// contained within the original "unloop".
429void UnloopUpdater::updateBlockParents() {
430 if (Unloop->getNumBlocks()) {
431 // Perform a post order CFG traversal of all blocks within this loop,
432 // propagating the nearest loop from sucessors to predecessors.
433 LoopBlocksTraversal Traversal(DFS, LI);
434 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
435 POE = Traversal.end(); POI != POE; ++POI) {
436
437 Loop *L = LI->getLoopFor(*POI);
438 Loop *NL = getNearestLoop(*POI, L);
439
440 if (NL != L) {
441 // For reducible loops, NL is now an ancestor of Unloop.
442 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
443 "uninitialized successor");
444 LI->changeLoopFor(*POI, NL);
445 }
446 else {
447 // Or the current block is part of a subloop, in which case its parent
448 // is unchanged.
449 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
450 }
451 }
452 }
453 // Each irreducible loop within the unloop induces a round of iteration using
454 // the DFS result cached by Traversal.
455 bool Changed = FoundIB;
456 for (unsigned NIters = 0; Changed; ++NIters) {
457 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
458
459 // Iterate over the postorder list of blocks, propagating the nearest loop
460 // from successors to predecessors as before.
461 Changed = false;
462 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
463 POE = DFS.endPostorder(); POI != POE; ++POI) {
464
465 Loop *L = LI->getLoopFor(*POI);
466 Loop *NL = getNearestLoop(*POI, L);
467 if (NL != L) {
468 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
469 "uninitialized successor");
470 LI->changeLoopFor(*POI, NL);
471 Changed = true;
472 }
473 }
474 }
475}
476
Andrew Trickc12d9b92011-08-11 20:27:32 +0000477/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
478/// their new parents.
479void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000480 // Remove all unloop's blocks (including those in nested subloops) from
481 // ancestors below the new parent loop.
Andrew Trickc12d9b92011-08-11 20:27:32 +0000482 for (Loop::block_iterator BI = Unloop->block_begin(),
483 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000484 Loop *OuterParent = LI->getLoopFor(*BI);
485 if (Unloop->contains(OuterParent)) {
486 while (OuterParent->getParentLoop() != Unloop)
487 OuterParent = OuterParent->getParentLoop();
488 OuterParent = SubloopParents[OuterParent];
489 }
Andrew Trickc12d9b92011-08-11 20:27:32 +0000490 // Remove blocks from former Ancestors except Unloop itself which will be
491 // deleted.
Andrew Trick5865a8d2011-11-18 03:42:41 +0000492 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12d9b92011-08-11 20:27:32 +0000493 OldParent = OldParent->getParentLoop()) {
494 assert(OldParent && "new loop is not an ancestor of the original");
495 OldParent->removeBlockFromLoop(*BI);
496 }
497 }
498}
499
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000500/// updateSubloopParents - Update the parent loop for all subloops directly
501/// nested within unloop.
502void UnloopUpdater::updateSubloopParents() {
503 while (!Unloop->empty()) {
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000504 Loop *Subloop = *llvm::prior(Unloop->end());
505 Unloop->removeChildLoop(llvm::prior(Unloop->end()));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000506
507 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
508 if (SubloopParents[Subloop])
509 SubloopParents[Subloop]->addChildLoop(Subloop);
Andrew Trick5434c1e2011-08-26 03:06:34 +0000510 else
511 LI->addTopLevelLoop(Subloop);
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000512 }
513}
514
515/// getNearestLoop - Return the nearest parent loop among this block's
516/// successors. If a successor is a subloop header, consider its parent to be
517/// the nearest parent of the subloop's exits.
518///
519/// For subloop blocks, simply update SubloopParents and return NULL.
520Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
521
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000522 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
523 // is considered uninitialized.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000524 Loop *NearLoop = BBLoop;
525
526 Loop *Subloop = 0;
527 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
528 Subloop = NearLoop;
529 // Find the subloop ancestor that is directly contained within Unloop.
530 while (Subloop->getParentLoop() != Unloop) {
531 Subloop = Subloop->getParentLoop();
532 assert(Subloop && "subloop is not an ancestor of the original loop");
533 }
534 // Get the current nearest parent of the Subloop exits, initially Unloop.
535 if (!SubloopParents.count(Subloop))
536 SubloopParents[Subloop] = Unloop;
537 NearLoop = SubloopParents[Subloop];
538 }
539
540 succ_iterator I = succ_begin(BB), E = succ_end(BB);
541 if (I == E) {
542 assert(!Subloop && "subloop blocks must have a successor");
543 NearLoop = 0; // unloop blocks may now exit the function.
544 }
545 for (; I != E; ++I) {
546 if (*I == BB)
547 continue; // self loops are uninteresting
548
549 Loop *L = LI->getLoopFor(*I);
550 if (L == Unloop) {
551 // This successor has not been processed. This path must lead to an
552 // irreducible backedge.
553 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
554 FoundIB = true;
555 }
556 if (L != Unloop && Unloop->contains(L)) {
557 // Successor is in a subloop.
558 if (Subloop)
559 continue; // Branching within subloops. Ignore it.
560
561 // BB branches from the original into a subloop header.
562 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
563
564 // Get the current nearest parent of the Subloop's exits.
565 L = SubloopParents[L];
566 // L could be Unloop if the only exit was an irreducible backedge.
567 }
568 if (L == Unloop) {
569 continue;
570 }
571 // Handle critical edges from Unloop into a sibling loop.
572 if (L && !L->contains(Unloop)) {
573 L = L->getParentLoop();
574 }
575 // Remember the nearest parent loop among successors or subloop exits.
576 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
577 NearLoop = L;
578 }
579 if (Subloop) {
580 SubloopParents[Subloop] = NearLoop;
581 return BBLoop;
582 }
583 return NearLoop;
584}
585
586//===----------------------------------------------------------------------===//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000587// LoopInfo implementation
588//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000589bool LoopInfo::runOnFunction(Function &) {
590 releaseMemory();
Dan Gohman9d59d9f2009-06-27 21:22:48 +0000591 LI.Calculate(getAnalysis<DominatorTree>().getBase()); // Update
Chris Lattnera59cbb22002-07-27 01:12:17 +0000592 return false;
593}
594
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000595/// updateUnloop - The last backedge has been removed from a loop--now the
596/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000597/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000598/// point, but LoopInfo is still valid except for the removal of this loop.
599///
600/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
601/// checking first is illegal.
602void LoopInfo::updateUnloop(Loop *Unloop) {
603
604 // First handle the special case of no parent loop to simplify the algorithm.
605 if (!Unloop->getParentLoop()) {
606 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
607 for (Loop::block_iterator I = Unloop->block_begin(),
608 E = Unloop->block_end(); I != E; ++I) {
609
610 // Don't reparent blocks in subloops.
611 if (getLoopFor(*I) != Unloop)
612 continue;
613
614 // Blocks no longer have a parent but are still referenced by Unloop until
615 // the Unloop object is deleted.
616 LI.changeLoopFor(*I, 0);
617 }
618
619 // Remove the loop from the top-level LoopInfo object.
Duncan Sands1f6a3292011-08-12 14:54:45 +0000620 for (LoopInfo::iterator I = LI.begin();; ++I) {
621 assert(I != LI.end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000622 if (*I == Unloop) {
623 LI.removeLoop(I);
624 break;
625 }
626 }
627
628 // Move all of the subloops to the top-level.
629 while (!Unloop->empty())
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000630 LI.addTopLevelLoop(Unloop->removeChildLoop(llvm::prior(Unloop->end())));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000631
632 return;
633 }
634
635 // Update the parent loop for all blocks within the loop. Blocks within
636 // subloops will not change parents.
637 UnloopUpdater Updater(Unloop, this);
638 Updater.updateBlockParents();
639
Andrew Trickc12d9b92011-08-11 20:27:32 +0000640 // Remove blocks from former ancestor loops.
641 Updater.removeBlocksFromAncestors();
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000642
643 // Add direct subloops as children in their new parent loop.
644 Updater.updateSubloopParents();
645
646 // Remove unloop from its parent loop.
647 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sands1f6a3292011-08-12 14:54:45 +0000648 for (Loop::iterator I = ParentLoop->begin();; ++I) {
649 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000650 if (*I == Unloop) {
651 ParentLoop->removeChildLoop(I);
652 break;
653 }
654 }
655}
656
Dan Gohman5c89b522009-09-08 15:45:00 +0000657void LoopInfo::verifyAnalysis() const {
Dan Gohman9450b0e2009-09-28 00:27:48 +0000658 // LoopInfo is a FunctionPass, but verifying every loop in the function
659 // each time verifyAnalysis is called is very expensive. The
660 // -verify-loop-info option can enable this. In order to perform some
661 // checking by default, LoopPass has been taught to call verifyLoop
662 // manually during loop pass sequences.
663
664 if (!VerifyLoopInfo) return;
665
Andrew Trick5434c1e2011-08-26 03:06:34 +0000666 DenseSet<const Loop*> Loops;
Dan Gohman5c89b522009-09-08 15:45:00 +0000667 for (iterator I = begin(), E = end(); I != E; ++I) {
668 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
Andrew Trick5434c1e2011-08-26 03:06:34 +0000669 (*I)->verifyLoopNest(&Loops);
Dan Gohman5c89b522009-09-08 15:45:00 +0000670 }
Dan Gohman9450b0e2009-09-28 00:27:48 +0000671
Andrew Trick5434c1e2011-08-26 03:06:34 +0000672 // Verify that blocks are mapped to valid loops.
673 //
674 // FIXME: With an up-to-date DFS (see LoopIterator.h) and DominatorTree, we
675 // could also verify that the blocks are still in the correct loops.
676 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
677 E = LI.BBMap.end(); I != E; ++I) {
678 assert(Loops.count(I->second) && "orphaned loop");
679 assert(I->second->contains(I->first) && "orphaned block");
680 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000681}
682
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000683void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000684 AU.setPreservesAll();
Devang Patel53c279b2007-06-08 00:17:13 +0000685 AU.addRequired<DominatorTree>();
Chris Lattner93193f82002-01-31 00:42:27 +0000686}
Chris Lattner791102f2009-08-23 05:17:37 +0000687
Chris Lattner45cfe542009-08-23 06:03:38 +0000688void LoopInfo::print(raw_ostream &OS, const Module*) const {
689 LI.print(OS);
Chris Lattner791102f2009-08-23 05:17:37 +0000690}
691
Andrew Trick2d31ae32011-08-10 01:59:05 +0000692//===----------------------------------------------------------------------===//
693// LoopBlocksDFS implementation
694//
695
696/// Traverse the loop blocks and store the DFS result.
697/// Useful for clients that just want the final DFS result and don't need to
698/// visit blocks during the initial traversal.
699void LoopBlocksDFS::perform(LoopInfo *LI) {
700 LoopBlocksTraversal Traversal(*this, LI);
701 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
702 POE = Traversal.end(); POI != POE; ++POI) ;
703}