blob: d88f8a8093b9ed8ec5656be16f13172a75ebe59e [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/DepthFirstIterator.h"
19#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner92020fa2004-04-15 15:16:02 +000020#include "llvm/Analysis/Dominators.h"
Andrew Trickcbf24b42012-06-20 03:42:09 +000021#include "llvm/Analysis/LoopInfoImpl.h"
Andrew Trick2d31ae32011-08-10 01:59:05 +000022#include "llvm/Analysis/LoopIterator.h"
Dan Gohmanf0426602011-12-14 23:49:11 +000023#include "llvm/Analysis/ValueTracking.h"
Chris Lattnera59cbb22002-07-27 01:12:17 +000024#include "llvm/Assembly/Writer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000025#include "llvm/Constants.h"
26#include "llvm/Instructions.h"
Misha Brukman10d208d2004-01-30 17:26:24 +000027#include "llvm/Support/CFG.h"
Dan Gohman9450b0e2009-09-28 00:27:48 +000028#include "llvm/Support/CommandLine.h"
Dan Gohmandda30cd2010-01-05 21:08:02 +000029#include "llvm/Support/Debug.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000030#include <algorithm>
Chris Lattner46758a82004-04-12 20:26:17 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Andrew Trickcbf24b42012-06-20 03:42:09 +000033// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
34template class llvm::LoopBase<BasicBlock, Loop>;
35template class llvm::LoopInfoBase<BasicBlock, Loop>;
36
Dan Gohman9450b0e2009-09-28 00:27:48 +000037// Always verify loopinfo if expensive checking is enabled.
38#ifdef XDEBUG
Dan Gohmanb3579832010-04-15 17:08:50 +000039static bool VerifyLoopInfo = true;
Dan Gohman9450b0e2009-09-28 00:27:48 +000040#else
Dan Gohmanb3579832010-04-15 17:08:50 +000041static bool VerifyLoopInfo = false;
Dan Gohman9450b0e2009-09-28 00:27:48 +000042#endif
43static cl::opt<bool,true>
44VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
45 cl::desc("Verify loop info (time consuming)"));
46
Devang Patel19974732007-05-03 01:11:54 +000047char LoopInfo::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000048INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
49INITIALIZE_PASS_DEPENDENCY(DominatorTree)
50INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
Chris Lattner93193f82002-01-31 00:42:27 +000051
52//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000053// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000054//
Misha Brukman6b290a52002-10-11 05:31:10 +000055
Dan Gohman16a2c922009-07-13 22:02:44 +000056/// isLoopInvariant - Return true if the specified value is loop invariant
57///
58bool Loop::isLoopInvariant(Value *V) const {
59 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattneradc79912010-09-06 01:05:37 +000060 return !contains(I);
Dan Gohman16a2c922009-07-13 22:02:44 +000061 return true; // All non-instructions are loop invariant
62}
63
Chris Lattneradc79912010-09-06 01:05:37 +000064/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trick882bcc62011-08-03 23:45:50 +000065/// specified instruction are loop invariant.
Chris Lattneradc79912010-09-06 01:05:37 +000066bool Loop::hasLoopInvariantOperands(Instruction *I) const {
67 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
68 if (!isLoopInvariant(I->getOperand(i)))
69 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +000070
Chris Lattneradc79912010-09-06 01:05:37 +000071 return true;
Dan Gohmana3420262009-07-14 01:06:29 +000072}
73
74/// makeLoopInvariant - If the given value is an instruciton inside of the
75/// loop and it can be hoisted, do so to make it trivially loop-invariant.
76/// Return true if the value after any hoisting is loop invariant. This
77/// function can be used as a slightly more aggressive replacement for
78/// isLoopInvariant.
79///
80/// If InsertPt is specified, it is the point to hoist instructions to.
81/// If null, the terminator of the loop preheader is used.
82///
Dan Gohmanbdc017e2009-07-15 01:25:43 +000083bool Loop::makeLoopInvariant(Value *V, bool &Changed,
84 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000085 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanbdc017e2009-07-15 01:25:43 +000086 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohmana3420262009-07-14 01:06:29 +000087 return true; // All non-instructions are loop-invariant.
88}
89
90/// makeLoopInvariant - If the given instruction is inside of the
91/// loop and it can be hoisted, do so to make it trivially loop-invariant.
92/// Return true if the instruction after any hoisting is loop invariant. This
93/// function can be used as a slightly more aggressive replacement for
94/// isLoopInvariant.
95///
96/// If InsertPt is specified, it is the point to hoist instructions to.
97/// If null, the terminator of the loop preheader is used.
98///
Dan Gohmanbdc017e2009-07-15 01:25:43 +000099bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
100 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +0000101 // Test if the value is already loop-invariant.
102 if (isLoopInvariant(I))
103 return true;
Dan Gohmanf0426602011-12-14 23:49:11 +0000104 if (!isSafeToSpeculativelyExecute(I))
Dan Gohmana3420262009-07-14 01:06:29 +0000105 return false;
Eli Friedman0b79a772009-07-17 04:28:42 +0000106 if (I->mayReadFromMemory())
Dan Gohmana3420262009-07-14 01:06:29 +0000107 return false;
Bill Wendlingc9b2a982011-08-17 20:36:44 +0000108 // The landingpad instruction is immobile.
109 if (isa<LandingPadInst>(I))
110 return false;
Dan Gohmana3420262009-07-14 01:06:29 +0000111 // Determine the insertion point, unless one was given.
112 if (!InsertPt) {
113 BasicBlock *Preheader = getLoopPreheader();
114 // Without a preheader, hoisting is not feasible.
115 if (!Preheader)
116 return false;
117 InsertPt = Preheader->getTerminator();
118 }
119 // Don't hoist instructions with loop-variant operands.
120 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000121 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohmana3420262009-07-14 01:06:29 +0000122 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +0000123
Dan Gohmana3420262009-07-14 01:06:29 +0000124 // Hoist.
125 I->moveBefore(InsertPt);
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000126 Changed = true;
Dan Gohmana3420262009-07-14 01:06:29 +0000127 return true;
128}
129
Dan Gohman16a2c922009-07-13 22:02:44 +0000130/// getCanonicalInductionVariable - Check to see if the loop has a canonical
131/// induction variable: an integer recurrence that starts at 0 and increments
132/// by one each time through the loop. If so, return the phi node that
133/// corresponds to it.
134///
135/// The IndVarSimplify pass transforms loops to have a canonical induction
136/// variable.
137///
138PHINode *Loop::getCanonicalInductionVariable() const {
139 BasicBlock *H = getHeader();
140
141 BasicBlock *Incoming = 0, *Backedge = 0;
Dan Gohman63137d52010-07-23 21:25:16 +0000142 pred_iterator PI = pred_begin(H);
143 assert(PI != pred_end(H) &&
Dan Gohman16a2c922009-07-13 22:02:44 +0000144 "Loop must have at least one backedge!");
145 Backedge = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000146 if (PI == pred_end(H)) return 0; // dead loop
Dan Gohman16a2c922009-07-13 22:02:44 +0000147 Incoming = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000148 if (PI != pred_end(H)) return 0; // multiple backedges?
Dan Gohman16a2c922009-07-13 22:02:44 +0000149
150 if (contains(Incoming)) {
151 if (contains(Backedge))
152 return 0;
153 std::swap(Incoming, Backedge);
154 } else if (!contains(Backedge))
155 return 0;
156
157 // Loop over all of the PHI nodes, looking for a canonical indvar.
158 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
159 PHINode *PN = cast<PHINode>(I);
160 if (ConstantInt *CI =
161 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
162 if (CI->isNullValue())
163 if (Instruction *Inc =
164 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
165 if (Inc->getOpcode() == Instruction::Add &&
166 Inc->getOperand(0) == PN)
167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
168 if (CI->equalsInt(1))
169 return PN;
170 }
171 return 0;
172}
173
Dan Gohman16a2c922009-07-13 22:02:44 +0000174/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000175bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman16a2c922009-07-13 22:02:44 +0000176 // Sort the blocks vector so that we can use binary search to do quick
177 // lookups.
Gabor Greif5891ac82010-07-09 14:28:41 +0000178 SmallPtrSet<BasicBlock*, 16> LoopBBs(block_begin(), block_end());
Dan Gohman16a2c922009-07-13 22:02:44 +0000179
180 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman81d893c2009-11-09 18:19:43 +0000181 BasicBlock *BB = *BI;
182 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Dan Gohman16a2c922009-07-13 22:02:44 +0000183 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
184 ++UI) {
Gabor Greif5891ac82010-07-09 14:28:41 +0000185 User *U = *UI;
186 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
187 if (PHINode *P = dyn_cast<PHINode>(U))
Dan Gohman16a2c922009-07-13 22:02:44 +0000188 UserBB = P->getIncomingBlock(UI);
Dan Gohman16a2c922009-07-13 22:02:44 +0000189
Dan Gohmancbac7f12010-03-09 01:53:33 +0000190 // Check the current block, as a fast-path, before checking whether
191 // the use is anywhere in the loop. Most values are used in the same
192 // block they are defined in. Also, blocks not reachable from the
193 // entry are special; uses in them don't need to go through PHIs.
194 if (UserBB != BB &&
195 !LoopBBs.count(UserBB) &&
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000196 DT.isReachableFromEntry(UserBB))
Dan Gohman16a2c922009-07-13 22:02:44 +0000197 return false;
198 }
199 }
200
201 return true;
202}
Dan Gohman93773862009-07-16 16:16:23 +0000203
204/// isLoopSimplifyForm - Return true if the Loop is in the form that
205/// the LoopSimplify form transforms loops to, which is sometimes called
206/// normal form.
207bool Loop::isLoopSimplifyForm() const {
Dan Gohmanf17e9512009-11-05 19:21:41 +0000208 // Normal-form loops have a preheader, a single backedge, and all of their
209 // exits have all their predecessors inside the loop.
210 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
211}
212
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000213/// isSafeToClone - Return true if the loop body is safe to clone in practice.
214/// Routines that reform the loop CFG and split edges often fail on indirectbr.
215bool Loop::isSafeToClone() const {
James Molloy67ae1352012-12-20 16:04:27 +0000216 // Return false if any loop blocks contain indirectbrs, or there are any calls
217 // to noduplicate functions.
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000218 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
James Molloy67ae1352012-12-20 16:04:27 +0000219 if (isa<IndirectBrInst>((*I)->getTerminator())) {
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000220 return false;
James Molloy67ae1352012-12-20 16:04:27 +0000221 } else if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator())) {
222 if (II->hasFnAttr(Attribute::NoDuplicate))
223 return false;
224 }
225
226 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
227 if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
228 if (CI->hasFnAttr(Attribute::NoDuplicate))
229 return false;
230 }
231 }
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000232 }
233 return true;
234}
235
Dan Gohmanf17e9512009-11-05 19:21:41 +0000236/// hasDedicatedExits - Return true if no exit block for the loop
237/// has a predecessor that is outside the loop.
238bool Loop::hasDedicatedExits() const {
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000239 // Sort the blocks vector so that we can use binary search to do quick
240 // lookups.
241 SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
Dan Gohman93773862009-07-16 16:16:23 +0000242 // Each predecessor of each exit block of a normal loop is contained
243 // within the loop.
244 SmallVector<BasicBlock *, 4> ExitBlocks;
245 getExitBlocks(ExitBlocks);
246 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
247 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
248 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000249 if (!LoopBBs.count(*PI))
Dan Gohman93773862009-07-16 16:16:23 +0000250 return false;
251 // All the requirements are met.
252 return true;
253}
254
Dan Gohmanf0608d82009-09-03 16:10:48 +0000255/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
256/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman050959c2009-12-11 20:05:23 +0000257/// This assumes that loop exits are in canonical form.
Dan Gohmanf0608d82009-09-03 16:10:48 +0000258///
259void
260Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman050959c2009-12-11 20:05:23 +0000261 assert(hasDedicatedExits() &&
262 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman5c89b522009-09-08 15:45:00 +0000263
Dan Gohmanf0608d82009-09-03 16:10:48 +0000264 // Sort the blocks vector so that we can use binary search to do quick
265 // lookups.
266 SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
267 std::sort(LoopBBs.begin(), LoopBBs.end());
268
Dan Gohman058db922009-09-03 20:36:13 +0000269 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohmanf0608d82009-09-03 16:10:48 +0000270
271 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
272
273 BasicBlock *current = *BI;
274 switchExitBlocks.clear();
275
Dan Gohman63137d52010-07-23 21:25:16 +0000276 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000277 // If block is inside the loop then it is not a exit block.
278 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
279 continue;
280
Dan Gohman63137d52010-07-23 21:25:16 +0000281 pred_iterator PI = pred_begin(*I);
Dan Gohmanf0608d82009-09-03 16:10:48 +0000282 BasicBlock *firstPred = *PI;
283
284 // If current basic block is this exit block's first predecessor
285 // then only insert exit block in to the output ExitBlocks vector.
286 // This ensures that same exit block is not inserted twice into
287 // ExitBlocks vector.
288 if (current != firstPred)
289 continue;
290
291 // If a terminator has more then two successors, for example SwitchInst,
292 // then it is possible that there are multiple edges from current block
293 // to one exit block.
Dan Gohman63137d52010-07-23 21:25:16 +0000294 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000295 ExitBlocks.push_back(*I);
296 continue;
297 }
298
299 // In case of multiple edges from current block to exit block, collect
300 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
301 // duplicate edges.
302 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
303 == switchExitBlocks.end()) {
304 switchExitBlocks.push_back(*I);
305 ExitBlocks.push_back(*I);
306 }
307 }
308 }
309}
310
311/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
312/// block, return that block. Otherwise return null.
313BasicBlock *Loop::getUniqueExitBlock() const {
314 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
315 getUniqueExitBlocks(UniqueExitBlocks);
316 if (UniqueExitBlocks.size() == 1)
317 return UniqueExitBlocks[0];
318 return 0;
319}
320
Manman Ren286c4dc2012-09-12 05:06:18 +0000321#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohmandda30cd2010-01-05 21:08:02 +0000322void Loop::dump() const {
323 print(dbgs());
324}
Manman Rencc77eec2012-09-06 19:55:56 +0000325#endif
Dan Gohmandda30cd2010-01-05 21:08:02 +0000326
Chris Lattnera59cbb22002-07-27 01:12:17 +0000327//===----------------------------------------------------------------------===//
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000328// UnloopUpdater implementation
329//
330
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000331namespace {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000332/// Find the new parent loop for all blocks within the "unloop" whose last
333/// backedges has just been removed.
334class UnloopUpdater {
335 Loop *Unloop;
336 LoopInfo *LI;
337
338 LoopBlocksDFS DFS;
339
340 // Map unloop's immediate subloops to their nearest reachable parents. Nested
341 // loops within these subloops will not change parents. However, an immediate
342 // subloop's new parent will be the nearest loop reachable from either its own
343 // exits *or* any of its nested loop's exits.
344 DenseMap<Loop*, Loop*> SubloopParents;
345
346 // Flag the presence of an irreducible backedge whose destination is a block
347 // directly contained by the original unloop.
348 bool FoundIB;
349
350public:
351 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
352 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
353
354 void updateBlockParents();
355
Andrew Trickc12d9b92011-08-11 20:27:32 +0000356 void removeBlocksFromAncestors();
357
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000358 void updateSubloopParents();
359
360protected:
361 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
362};
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000363} // end anonymous namespace
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000364
365/// updateBlockParents - Update the parent loop for all blocks that are directly
366/// contained within the original "unloop".
367void UnloopUpdater::updateBlockParents() {
368 if (Unloop->getNumBlocks()) {
369 // Perform a post order CFG traversal of all blocks within this loop,
370 // propagating the nearest loop from sucessors to predecessors.
371 LoopBlocksTraversal Traversal(DFS, LI);
372 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
373 POE = Traversal.end(); POI != POE; ++POI) {
374
375 Loop *L = LI->getLoopFor(*POI);
376 Loop *NL = getNearestLoop(*POI, L);
377
378 if (NL != L) {
379 // For reducible loops, NL is now an ancestor of Unloop.
380 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
381 "uninitialized successor");
382 LI->changeLoopFor(*POI, NL);
383 }
384 else {
385 // Or the current block is part of a subloop, in which case its parent
386 // is unchanged.
387 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
388 }
389 }
390 }
391 // Each irreducible loop within the unloop induces a round of iteration using
392 // the DFS result cached by Traversal.
393 bool Changed = FoundIB;
394 for (unsigned NIters = 0; Changed; ++NIters) {
395 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
396
397 // Iterate over the postorder list of blocks, propagating the nearest loop
398 // from successors to predecessors as before.
399 Changed = false;
400 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
401 POE = DFS.endPostorder(); POI != POE; ++POI) {
402
403 Loop *L = LI->getLoopFor(*POI);
404 Loop *NL = getNearestLoop(*POI, L);
405 if (NL != L) {
406 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
407 "uninitialized successor");
408 LI->changeLoopFor(*POI, NL);
409 Changed = true;
410 }
411 }
412 }
413}
414
Andrew Trickc12d9b92011-08-11 20:27:32 +0000415/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
416/// their new parents.
417void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000418 // Remove all unloop's blocks (including those in nested subloops) from
419 // ancestors below the new parent loop.
Andrew Trickc12d9b92011-08-11 20:27:32 +0000420 for (Loop::block_iterator BI = Unloop->block_begin(),
421 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000422 Loop *OuterParent = LI->getLoopFor(*BI);
423 if (Unloop->contains(OuterParent)) {
424 while (OuterParent->getParentLoop() != Unloop)
425 OuterParent = OuterParent->getParentLoop();
426 OuterParent = SubloopParents[OuterParent];
427 }
Andrew Trickc12d9b92011-08-11 20:27:32 +0000428 // Remove blocks from former Ancestors except Unloop itself which will be
429 // deleted.
Andrew Trick5865a8d2011-11-18 03:42:41 +0000430 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12d9b92011-08-11 20:27:32 +0000431 OldParent = OldParent->getParentLoop()) {
432 assert(OldParent && "new loop is not an ancestor of the original");
433 OldParent->removeBlockFromLoop(*BI);
434 }
435 }
436}
437
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000438/// updateSubloopParents - Update the parent loop for all subloops directly
439/// nested within unloop.
440void UnloopUpdater::updateSubloopParents() {
441 while (!Unloop->empty()) {
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000442 Loop *Subloop = *llvm::prior(Unloop->end());
443 Unloop->removeChildLoop(llvm::prior(Unloop->end()));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000444
445 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramer05d96f92012-08-22 15:37:57 +0000446 if (Loop *Parent = SubloopParents[Subloop])
447 Parent->addChildLoop(Subloop);
Andrew Trick5434c1e2011-08-26 03:06:34 +0000448 else
449 LI->addTopLevelLoop(Subloop);
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000450 }
451}
452
453/// getNearestLoop - Return the nearest parent loop among this block's
454/// successors. If a successor is a subloop header, consider its parent to be
455/// the nearest parent of the subloop's exits.
456///
457/// For subloop blocks, simply update SubloopParents and return NULL.
458Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
459
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000460 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
461 // is considered uninitialized.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000462 Loop *NearLoop = BBLoop;
463
464 Loop *Subloop = 0;
465 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
466 Subloop = NearLoop;
467 // Find the subloop ancestor that is directly contained within Unloop.
468 while (Subloop->getParentLoop() != Unloop) {
469 Subloop = Subloop->getParentLoop();
470 assert(Subloop && "subloop is not an ancestor of the original loop");
471 }
472 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramer05d96f92012-08-22 15:37:57 +0000473 NearLoop =
474 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000475 }
476
477 succ_iterator I = succ_begin(BB), E = succ_end(BB);
478 if (I == E) {
479 assert(!Subloop && "subloop blocks must have a successor");
480 NearLoop = 0; // unloop blocks may now exit the function.
481 }
482 for (; I != E; ++I) {
483 if (*I == BB)
484 continue; // self loops are uninteresting
485
486 Loop *L = LI->getLoopFor(*I);
487 if (L == Unloop) {
488 // This successor has not been processed. This path must lead to an
489 // irreducible backedge.
490 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
491 FoundIB = true;
492 }
493 if (L != Unloop && Unloop->contains(L)) {
494 // Successor is in a subloop.
495 if (Subloop)
496 continue; // Branching within subloops. Ignore it.
497
498 // BB branches from the original into a subloop header.
499 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
500
501 // Get the current nearest parent of the Subloop's exits.
502 L = SubloopParents[L];
503 // L could be Unloop if the only exit was an irreducible backedge.
504 }
505 if (L == Unloop) {
506 continue;
507 }
508 // Handle critical edges from Unloop into a sibling loop.
509 if (L && !L->contains(Unloop)) {
510 L = L->getParentLoop();
511 }
512 // Remember the nearest parent loop among successors or subloop exits.
513 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
514 NearLoop = L;
515 }
516 if (Subloop) {
517 SubloopParents[Subloop] = NearLoop;
518 return BBLoop;
519 }
520 return NearLoop;
521}
522
523//===----------------------------------------------------------------------===//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000524// LoopInfo implementation
525//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000526bool LoopInfo::runOnFunction(Function &) {
527 releaseMemory();
Andrew Trickc9b1e252012-06-26 04:11:38 +0000528 LI.Analyze(getAnalysis<DominatorTree>().getBase());
Chris Lattnera59cbb22002-07-27 01:12:17 +0000529 return false;
530}
531
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000532/// updateUnloop - The last backedge has been removed from a loop--now the
533/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000534/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000535/// point, but LoopInfo is still valid except for the removal of this loop.
536///
537/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
538/// checking first is illegal.
539void LoopInfo::updateUnloop(Loop *Unloop) {
540
541 // First handle the special case of no parent loop to simplify the algorithm.
542 if (!Unloop->getParentLoop()) {
543 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
544 for (Loop::block_iterator I = Unloop->block_begin(),
545 E = Unloop->block_end(); I != E; ++I) {
546
547 // Don't reparent blocks in subloops.
548 if (getLoopFor(*I) != Unloop)
549 continue;
550
551 // Blocks no longer have a parent but are still referenced by Unloop until
552 // the Unloop object is deleted.
553 LI.changeLoopFor(*I, 0);
554 }
555
556 // Remove the loop from the top-level LoopInfo object.
Duncan Sands1f6a3292011-08-12 14:54:45 +0000557 for (LoopInfo::iterator I = LI.begin();; ++I) {
558 assert(I != LI.end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000559 if (*I == Unloop) {
560 LI.removeLoop(I);
561 break;
562 }
563 }
564
565 // Move all of the subloops to the top-level.
566 while (!Unloop->empty())
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000567 LI.addTopLevelLoop(Unloop->removeChildLoop(llvm::prior(Unloop->end())));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000568
569 return;
570 }
571
572 // Update the parent loop for all blocks within the loop. Blocks within
573 // subloops will not change parents.
574 UnloopUpdater Updater(Unloop, this);
575 Updater.updateBlockParents();
576
Andrew Trickc12d9b92011-08-11 20:27:32 +0000577 // Remove blocks from former ancestor loops.
578 Updater.removeBlocksFromAncestors();
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000579
580 // Add direct subloops as children in their new parent loop.
581 Updater.updateSubloopParents();
582
583 // Remove unloop from its parent loop.
584 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sands1f6a3292011-08-12 14:54:45 +0000585 for (Loop::iterator I = ParentLoop->begin();; ++I) {
586 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000587 if (*I == Unloop) {
588 ParentLoop->removeChildLoop(I);
589 break;
590 }
591 }
592}
593
Dan Gohman5c89b522009-09-08 15:45:00 +0000594void LoopInfo::verifyAnalysis() const {
Dan Gohman9450b0e2009-09-28 00:27:48 +0000595 // LoopInfo is a FunctionPass, but verifying every loop in the function
596 // each time verifyAnalysis is called is very expensive. The
597 // -verify-loop-info option can enable this. In order to perform some
598 // checking by default, LoopPass has been taught to call verifyLoop
599 // manually during loop pass sequences.
600
601 if (!VerifyLoopInfo) return;
602
Andrew Trick5434c1e2011-08-26 03:06:34 +0000603 DenseSet<const Loop*> Loops;
Dan Gohman5c89b522009-09-08 15:45:00 +0000604 for (iterator I = begin(), E = end(); I != E; ++I) {
605 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
Andrew Trick5434c1e2011-08-26 03:06:34 +0000606 (*I)->verifyLoopNest(&Loops);
Dan Gohman5c89b522009-09-08 15:45:00 +0000607 }
Dan Gohman9450b0e2009-09-28 00:27:48 +0000608
Andrew Trick5434c1e2011-08-26 03:06:34 +0000609 // Verify that blocks are mapped to valid loops.
Andrew Trick5434c1e2011-08-26 03:06:34 +0000610 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
611 E = LI.BBMap.end(); I != E; ++I) {
612 assert(Loops.count(I->second) && "orphaned loop");
613 assert(I->second->contains(I->first) && "orphaned block");
614 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000615}
616
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000617void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000618 AU.setPreservesAll();
Devang Patel53c279b2007-06-08 00:17:13 +0000619 AU.addRequired<DominatorTree>();
Chris Lattner93193f82002-01-31 00:42:27 +0000620}
Chris Lattner791102f2009-08-23 05:17:37 +0000621
Chris Lattner45cfe542009-08-23 06:03:38 +0000622void LoopInfo::print(raw_ostream &OS, const Module*) const {
623 LI.print(OS);
Chris Lattner791102f2009-08-23 05:17:37 +0000624}
625
Andrew Trick2d31ae32011-08-10 01:59:05 +0000626//===----------------------------------------------------------------------===//
627// LoopBlocksDFS implementation
628//
629
630/// Traverse the loop blocks and store the DFS result.
631/// Useful for clients that just want the final DFS result and don't need to
632/// visit blocks during the initial traversal.
633void LoopBlocksDFS::perform(LoopInfo *LI) {
634 LoopBlocksTraversal Traversal(*this, LI);
635 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
636 POE = Traversal.end(); POI != POE; ++POI) ;
637}