blob: c200f9f36841030102218eefe0466535035fd15c [file] [log] [blame]
Chris Lattner44d2c352003-10-13 03:32:08 +00001//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman01808ca2005-04-21 21:13:18 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6de99422001-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 Brukman81804b42004-01-30 17:26:24 +000017#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DepthFirstIterator.h"
19#include "llvm/ADT/SmallPtrSet.h"
Andrew Trickcda51d42012-06-20 03:42:09 +000020#include "llvm/Analysis/LoopInfoImpl.h"
Andrew Trick78b40c32011-08-10 01:59:05 +000021#include "llvm/Analysis/LoopIterator.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000023#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
Philip Reames5a3f5f72014-10-21 00:13:20 +000027#include "llvm/IR/LLVMContext.h"
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +000028#include "llvm/IR/Metadata.h"
Dan Gohman4dbb3012009-09-28 00:27:48 +000029#include "llvm/Support/CommandLine.h"
Dan Gohmanc3f21372010-01-05 21:08:02 +000030#include "llvm/Support/Debug.h"
Chris Lattner6de99422001-11-26 18:41:20 +000031#include <algorithm>
Chris Lattner55b7ef52004-04-12 20:26:17 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Andrew Trickcda51d42012-06-20 03:42:09 +000034// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
35template class llvm::LoopBase<BasicBlock, Loop>;
36template class llvm::LoopInfoBase<BasicBlock, Loop>;
37
Dan Gohman4dbb3012009-09-28 00:27:48 +000038// Always verify loopinfo if expensive checking is enabled.
39#ifdef XDEBUG
Dan Gohmanb29cda92010-04-15 17:08:50 +000040static bool VerifyLoopInfo = true;
Dan Gohman4dbb3012009-09-28 00:27:48 +000041#else
Dan Gohmanb29cda92010-04-15 17:08:50 +000042static bool VerifyLoopInfo = false;
Dan Gohman4dbb3012009-09-28 00:27:48 +000043#endif
44static cl::opt<bool,true>
45VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
46 cl::desc("Verify loop info (time consuming)"));
47
Paul Redmond5fdf8362013-05-28 20:00:34 +000048// Loop identifier metadata name.
Craig Topperd3a34f82013-07-16 01:17:10 +000049static const char *const LoopMDName = "llvm.loop";
Paul Redmond5fdf8362013-05-28 20:00:34 +000050
Chris Lattnerccf571a2002-01-31 00:42:27 +000051//===----------------------------------------------------------------------===//
Chris Lattner78dd56f2002-04-28 16:21:30 +000052// Loop implementation
Chris Lattnerccf571a2002-01-31 00:42:27 +000053//
Misha Brukman3845be22002-10-11 05:31:10 +000054
Dan Gohman80a99422009-07-13 22:02:44 +000055/// isLoopInvariant - Return true if the specified value is loop invariant
56///
57bool Loop::isLoopInvariant(Value *V) const {
58 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000059 return !contains(I);
Dan Gohman80a99422009-07-13 22:02:44 +000060 return true; // All non-instructions are loop invariant
61}
62
Chris Lattnerda24b9a2010-09-06 01:05:37 +000063/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trickf898cbd2011-08-03 23:45:50 +000064/// specified instruction are loop invariant.
Chris Lattnerda24b9a2010-09-06 01:05:37 +000065bool Loop::hasLoopInvariantOperands(Instruction *I) const {
66 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
67 if (!isLoopInvariant(I->getOperand(i)))
68 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000069
Chris Lattnerda24b9a2010-09-06 01:05:37 +000070 return true;
Dan Gohman6f6d8642009-07-14 01:06:29 +000071}
72
73/// makeLoopInvariant - If the given value is an instruciton inside of the
74/// loop and it can be hoisted, do so to make it trivially loop-invariant.
75/// Return true if the value after any hoisting is loop invariant. This
76/// function can be used as a slightly more aggressive replacement for
77/// isLoopInvariant.
78///
79/// If InsertPt is specified, it is the point to hoist instructions to.
80/// If null, the terminator of the loop preheader is used.
81///
Dan Gohmanc43e4792009-07-15 01:25:43 +000082bool Loop::makeLoopInvariant(Value *V, bool &Changed,
83 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000084 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000085 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman6f6d8642009-07-14 01:06:29 +000086 return true; // All non-instructions are loop-invariant.
87}
88
89/// makeLoopInvariant - If the given instruction is inside of the
90/// loop and it can be hoisted, do so to make it trivially loop-invariant.
91/// Return true if the instruction after any hoisting is loop invariant. This
92/// function can be used as a slightly more aggressive replacement for
93/// isLoopInvariant.
94///
95/// If InsertPt is specified, it is the point to hoist instructions to.
96/// If null, the terminator of the loop preheader is used.
97///
Dan Gohmanc43e4792009-07-15 01:25:43 +000098bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
99 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +0000100 // Test if the value is already loop-invariant.
101 if (isLoopInvariant(I))
102 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +0000103 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000104 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000105 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +0000106 return false;
Bill Wendlinga9ee09f2011-08-17 20:36:44 +0000107 // The landingpad instruction is immobile.
108 if (isa<LandingPadInst>(I))
109 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000110 // Determine the insertion point, unless one was given.
111 if (!InsertPt) {
112 BasicBlock *Preheader = getLoopPreheader();
113 // Without a preheader, hoisting is not feasible.
114 if (!Preheader)
115 return false;
116 InsertPt = Preheader->getTerminator();
117 }
118 // Don't hoist instructions with loop-variant operands.
119 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanc43e4792009-07-15 01:25:43 +0000120 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000121 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +0000122
Dan Gohman6f6d8642009-07-14 01:06:29 +0000123 // Hoist.
124 I->moveBefore(InsertPt);
Dan Gohmanc43e4792009-07-15 01:25:43 +0000125 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000126 return true;
127}
128
Dan Gohman80a99422009-07-13 22:02:44 +0000129/// getCanonicalInductionVariable - Check to see if the loop has a canonical
130/// induction variable: an integer recurrence that starts at 0 and increments
131/// by one each time through the loop. If so, return the phi node that
132/// corresponds to it.
133///
134/// The IndVarSimplify pass transforms loops to have a canonical induction
135/// variable.
136///
137PHINode *Loop::getCanonicalInductionVariable() const {
138 BasicBlock *H = getHeader();
139
Craig Topper9f008862014-04-15 04:59:12 +0000140 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000141 pred_iterator PI = pred_begin(H);
142 assert(PI != pred_end(H) &&
Dan Gohman80a99422009-07-13 22:02:44 +0000143 "Loop must have at least one backedge!");
144 Backedge = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000145 if (PI == pred_end(H)) return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000146 Incoming = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000147 if (PI != pred_end(H)) return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000148
149 if (contains(Incoming)) {
150 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000151 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000152 std::swap(Incoming, Backedge);
153 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000154 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000155
156 // Loop over all of the PHI nodes, looking for a canonical indvar.
157 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
158 PHINode *PN = cast<PHINode>(I);
159 if (ConstantInt *CI =
160 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
161 if (CI->isNullValue())
162 if (Instruction *Inc =
163 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
164 if (Inc->getOpcode() == Instruction::Add &&
165 Inc->getOperand(0) == PN)
166 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
167 if (CI->equalsInt(1))
168 return PN;
169 }
Craig Topper9f008862014-04-15 04:59:12 +0000170 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000171}
172
Dan Gohman80a99422009-07-13 22:02:44 +0000173/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohman2734ebd2010-03-10 19:38:49 +0000174bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman80a99422009-07-13 22:02:44 +0000175 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman5196e412009-11-09 18:19:43 +0000176 BasicBlock *BB = *BI;
177 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000178 for (Use &U : I->uses()) {
179 Instruction *UI = cast<Instruction>(U.getUser());
180 BasicBlock *UserBB = UI->getParent();
181 if (PHINode *P = dyn_cast<PHINode>(UI))
182 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000183
Dan Gohman93452ce2010-03-09 01:53:33 +0000184 // Check the current block, as a fast-path, before checking whether
185 // the use is anywhere in the loop. Most values are used in the same
186 // block they are defined in. Also, blocks not reachable from the
187 // entry are special; uses in them don't need to go through PHIs.
188 if (UserBB != BB &&
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000189 !contains(UserBB) &&
Dan Gohman2734ebd2010-03-10 19:38:49 +0000190 DT.isReachableFromEntry(UserBB))
Dan Gohman80a99422009-07-13 22:02:44 +0000191 return false;
192 }
193 }
194
195 return true;
196}
Dan Gohman1511f702009-07-16 16:16:23 +0000197
198/// isLoopSimplifyForm - Return true if the Loop is in the form that
199/// the LoopSimplify form transforms loops to, which is sometimes called
200/// normal form.
201bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000202 // Normal-form loops have a preheader, a single backedge, and all of their
203 // exits have all their predecessors inside the loop.
204 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
205}
206
Andrew Trick4442bfe2012-04-10 05:14:42 +0000207/// isSafeToClone - Return true if the loop body is safe to clone in practice.
208/// Routines that reform the loop CFG and split edges often fail on indirectbr.
209bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000210 // Return false if any loop blocks contain indirectbrs, or there are any calls
211 // to noduplicate functions.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000212 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000213 if (isa<IndirectBrInst>((*I)->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000214 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000215
216 if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()))
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000217 if (II->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000218 return false;
James Molloy4f6fb952012-12-20 16:04:27 +0000219
220 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
221 if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000222 if (CI->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000223 return false;
224 }
225 }
Andrew Trick4442bfe2012-04-10 05:14:42 +0000226 }
227 return true;
228}
229
Paul Redmond5fdf8362013-05-28 20:00:34 +0000230MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000231 MDNode *LoopID = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000232 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000233 LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000234 } else {
235 // Go through each predecessor of the loop header and check the
236 // terminator for the metadata.
237 BasicBlock *H = getHeader();
238 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
239 TerminatorInst *TI = (*I)->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000240 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000241
242 // Check if this terminator branches to the loop header.
243 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
244 if (TI->getSuccessor(i) == H) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000245 MD = TI->getMetadata(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000246 break;
247 }
248 }
249 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000250 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000251
252 if (!LoopID)
253 LoopID = MD;
254 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000255 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000256 }
257 }
258 if (!LoopID || LoopID->getNumOperands() == 0 ||
259 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000260 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000261 return LoopID;
262}
263
264void Loop::setLoopID(MDNode *LoopID) const {
265 assert(LoopID && "Loop ID should not be null");
266 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
267 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
268
269 if (isLoopSimplifyForm()) {
270 getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
271 return;
272 }
273
274 BasicBlock *H = getHeader();
275 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
276 TerminatorInst *TI = (*I)->getTerminator();
277 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
278 if (TI->getSuccessor(i) == H)
279 TI->setMetadata(LoopMDName, LoopID);
280 }
281 }
282}
283
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000284bool Loop::isAnnotatedParallel() const {
Paul Redmond5fdf8362013-05-28 20:00:34 +0000285 MDNode *desiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000286
287 if (!desiredLoopIdMetadata)
288 return false;
289
290 // The loop branch contains the parallel loop metadata. In order to ensure
291 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
292 // dependencies (thus converted the loop back to a sequential loop), check
293 // that all the memory instructions in the loop contain parallelism metadata
294 // that point to the same unique "loop id metadata" the loop branch does.
295 for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
296 for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
297 II != EE; II++) {
298
299 if (!II->mayReadOrWriteMemory())
300 continue;
301
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000302 // The memory instruction can refer to the loop identifier metadata
303 // directly or indirectly through another list metadata (in case of
304 // nested parallel loops). The loop identifier metadata refers to
305 // itself so we can check both cases with the same routine.
Philip Reames5a3f5f72014-10-21 00:13:20 +0000306 MDNode *loopIdMD =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000307 II->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000308
309 if (!loopIdMD)
310 return false;
311
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000312 bool loopIdMDFound = false;
313 for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
314 if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
315 loopIdMDFound = true;
316 break;
317 }
318 }
319
320 if (!loopIdMDFound)
321 return false;
322 }
323 }
324 return true;
325}
326
327
Dan Gohmane3a17062009-11-05 19:21:41 +0000328/// hasDedicatedExits - Return true if no exit block for the loop
329/// has a predecessor that is outside the loop.
330bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000331 // Each predecessor of each exit block of a normal loop is contained
332 // within the loop.
333 SmallVector<BasicBlock *, 4> ExitBlocks;
334 getExitBlocks(ExitBlocks);
335 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000336 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
337 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
338 if (!contains(*PI))
Dan Gohman1511f702009-07-16 16:16:23 +0000339 return false;
340 // All the requirements are met.
341 return true;
342}
343
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000344/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
345/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman84ba0392009-12-11 20:05:23 +0000346/// This assumes that loop exits are in canonical form.
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000347///
348void
349Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000350 assert(hasDedicatedExits() &&
351 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000352
Dan Gohmaned8f3202009-09-03 20:36:13 +0000353 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000354
355 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
356
357 BasicBlock *current = *BI;
358 switchExitBlocks.clear();
359
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000360 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000361 // If block is inside the loop then it is not a exit block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000362 if (contains(*I))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000363 continue;
364
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000365 pred_iterator PI = pred_begin(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000366 BasicBlock *firstPred = *PI;
367
368 // If current basic block is this exit block's first predecessor
369 // then only insert exit block in to the output ExitBlocks vector.
370 // This ensures that same exit block is not inserted twice into
371 // ExitBlocks vector.
372 if (current != firstPred)
373 continue;
374
375 // If a terminator has more then two successors, for example SwitchInst,
376 // then it is possible that there are multiple edges from current block
377 // to one exit block.
Dan Gohmanacafc612010-07-23 21:25:16 +0000378 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000379 ExitBlocks.push_back(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000380 continue;
381 }
382
383 // In case of multiple edges from current block to exit block, collect
384 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
385 // duplicate edges.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000386 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000387 == switchExitBlocks.end()) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000388 switchExitBlocks.push_back(*I);
389 ExitBlocks.push_back(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000390 }
391 }
392 }
393}
394
395/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
396/// block, return that block. Otherwise return null.
397BasicBlock *Loop::getUniqueExitBlock() const {
398 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
399 getUniqueExitBlocks(UniqueExitBlocks);
400 if (UniqueExitBlocks.size() == 1)
401 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000402 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000403}
404
Manman Ren49d684e2012-09-12 05:06:18 +0000405#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohmanc3f21372010-01-05 21:08:02 +0000406void Loop::dump() const {
407 print(dbgs());
408}
Manman Renc3366cc2012-09-06 19:55:56 +0000409#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000410
Chris Lattner26750072002-07-27 01:12:17 +0000411//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000412// UnloopUpdater implementation
413//
414
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000415namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000416/// Find the new parent loop for all blocks within the "unloop" whose last
417/// backedges has just been removed.
418class UnloopUpdater {
419 Loop *Unloop;
420 LoopInfo *LI;
421
422 LoopBlocksDFS DFS;
423
424 // Map unloop's immediate subloops to their nearest reachable parents. Nested
425 // loops within these subloops will not change parents. However, an immediate
426 // subloop's new parent will be the nearest loop reachable from either its own
427 // exits *or* any of its nested loop's exits.
428 DenseMap<Loop*, Loop*> SubloopParents;
429
430 // Flag the presence of an irreducible backedge whose destination is a block
431 // directly contained by the original unloop.
432 bool FoundIB;
433
434public:
435 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
436 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
437
438 void updateBlockParents();
439
Andrew Trickc12c30a2011-08-11 20:27:32 +0000440 void removeBlocksFromAncestors();
441
Andrew Trickd3530b92011-08-10 23:22:57 +0000442 void updateSubloopParents();
443
444protected:
445 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
446};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000447} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000448
449/// updateBlockParents - Update the parent loop for all blocks that are directly
450/// contained within the original "unloop".
451void UnloopUpdater::updateBlockParents() {
452 if (Unloop->getNumBlocks()) {
453 // Perform a post order CFG traversal of all blocks within this loop,
454 // propagating the nearest loop from sucessors to predecessors.
455 LoopBlocksTraversal Traversal(DFS, LI);
456 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
457 POE = Traversal.end(); POI != POE; ++POI) {
458
459 Loop *L = LI->getLoopFor(*POI);
460 Loop *NL = getNearestLoop(*POI, L);
461
462 if (NL != L) {
463 // For reducible loops, NL is now an ancestor of Unloop.
464 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
465 "uninitialized successor");
466 LI->changeLoopFor(*POI, NL);
467 }
468 else {
469 // Or the current block is part of a subloop, in which case its parent
470 // is unchanged.
471 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
472 }
473 }
474 }
475 // Each irreducible loop within the unloop induces a round of iteration using
476 // the DFS result cached by Traversal.
477 bool Changed = FoundIB;
478 for (unsigned NIters = 0; Changed; ++NIters) {
479 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
480
481 // Iterate over the postorder list of blocks, propagating the nearest loop
482 // from successors to predecessors as before.
483 Changed = false;
484 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
485 POE = DFS.endPostorder(); POI != POE; ++POI) {
486
487 Loop *L = LI->getLoopFor(*POI);
488 Loop *NL = getNearestLoop(*POI, L);
489 if (NL != L) {
490 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
491 "uninitialized successor");
492 LI->changeLoopFor(*POI, NL);
493 Changed = true;
494 }
495 }
496 }
497}
498
Andrew Trickc12c30a2011-08-11 20:27:32 +0000499/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
500/// their new parents.
501void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000502 // Remove all unloop's blocks (including those in nested subloops) from
503 // ancestors below the new parent loop.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000504 for (Loop::block_iterator BI = Unloop->block_begin(),
505 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000506 Loop *OuterParent = LI->getLoopFor(*BI);
507 if (Unloop->contains(OuterParent)) {
508 while (OuterParent->getParentLoop() != Unloop)
509 OuterParent = OuterParent->getParentLoop();
510 OuterParent = SubloopParents[OuterParent];
511 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000512 // Remove blocks from former Ancestors except Unloop itself which will be
513 // deleted.
Andrew Trick6b4d5782011-11-18 03:42:41 +0000514 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000515 OldParent = OldParent->getParentLoop()) {
516 assert(OldParent && "new loop is not an ancestor of the original");
517 OldParent->removeBlockFromLoop(*BI);
518 }
519 }
520}
521
Andrew Trickd3530b92011-08-10 23:22:57 +0000522/// updateSubloopParents - Update the parent loop for all subloops directly
523/// nested within unloop.
524void UnloopUpdater::updateSubloopParents() {
525 while (!Unloop->empty()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000526 Loop *Subloop = *std::prev(Unloop->end());
527 Unloop->removeChildLoop(std::prev(Unloop->end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000528
529 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000530 if (Loop *Parent = SubloopParents[Subloop])
531 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000532 else
533 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000534 }
535}
536
537/// getNearestLoop - Return the nearest parent loop among this block's
538/// successors. If a successor is a subloop header, consider its parent to be
539/// the nearest parent of the subloop's exits.
540///
541/// For subloop blocks, simply update SubloopParents and return NULL.
542Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
543
Andrew Trick266ab102011-08-11 17:54:58 +0000544 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
545 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000546 Loop *NearLoop = BBLoop;
547
Craig Topper9f008862014-04-15 04:59:12 +0000548 Loop *Subloop = nullptr;
Andrew Trickd3530b92011-08-10 23:22:57 +0000549 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
550 Subloop = NearLoop;
551 // Find the subloop ancestor that is directly contained within Unloop.
552 while (Subloop->getParentLoop() != Unloop) {
553 Subloop = Subloop->getParentLoop();
554 assert(Subloop && "subloop is not an ancestor of the original loop");
555 }
556 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000557 NearLoop =
558 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000559 }
560
561 succ_iterator I = succ_begin(BB), E = succ_end(BB);
562 if (I == E) {
563 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000564 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000565 }
566 for (; I != E; ++I) {
567 if (*I == BB)
568 continue; // self loops are uninteresting
569
570 Loop *L = LI->getLoopFor(*I);
571 if (L == Unloop) {
572 // This successor has not been processed. This path must lead to an
573 // irreducible backedge.
574 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
575 FoundIB = true;
576 }
577 if (L != Unloop && Unloop->contains(L)) {
578 // Successor is in a subloop.
579 if (Subloop)
580 continue; // Branching within subloops. Ignore it.
581
582 // BB branches from the original into a subloop header.
583 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
584
585 // Get the current nearest parent of the Subloop's exits.
586 L = SubloopParents[L];
587 // L could be Unloop if the only exit was an irreducible backedge.
588 }
589 if (L == Unloop) {
590 continue;
591 }
592 // Handle critical edges from Unloop into a sibling loop.
593 if (L && !L->contains(Unloop)) {
594 L = L->getParentLoop();
595 }
596 // Remember the nearest parent loop among successors or subloop exits.
597 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
598 NearLoop = L;
599 }
600 if (Subloop) {
601 SubloopParents[Subloop] = NearLoop;
602 return BBLoop;
603 }
604 return NearLoop;
605}
606
Andrew Trickd3530b92011-08-10 23:22:57 +0000607/// updateUnloop - The last backedge has been removed from a loop--now the
608/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick266ab102011-08-11 17:54:58 +0000609/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickd3530b92011-08-10 23:22:57 +0000610/// point, but LoopInfo is still valid except for the removal of this loop.
611///
612/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
613/// checking first is illegal.
614void LoopInfo::updateUnloop(Loop *Unloop) {
615
616 // First handle the special case of no parent loop to simplify the algorithm.
617 if (!Unloop->getParentLoop()) {
618 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
619 for (Loop::block_iterator I = Unloop->block_begin(),
620 E = Unloop->block_end(); I != E; ++I) {
621
622 // Don't reparent blocks in subloops.
623 if (getLoopFor(*I) != Unloop)
624 continue;
625
626 // Blocks no longer have a parent but are still referenced by Unloop until
627 // the Unloop object is deleted.
Craig Topper9f008862014-04-15 04:59:12 +0000628 LI.changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000629 }
630
631 // Remove the loop from the top-level LoopInfo object.
Duncan Sandsa41634e2011-08-12 14:54:45 +0000632 for (LoopInfo::iterator I = LI.begin();; ++I) {
633 assert(I != LI.end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000634 if (*I == Unloop) {
635 LI.removeLoop(I);
636 break;
637 }
638 }
639
640 // Move all of the subloops to the top-level.
641 while (!Unloop->empty())
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000642 LI.addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000643
644 return;
645 }
646
647 // Update the parent loop for all blocks within the loop. Blocks within
648 // subloops will not change parents.
649 UnloopUpdater Updater(Unloop, this);
650 Updater.updateBlockParents();
651
Andrew Trickc12c30a2011-08-11 20:27:32 +0000652 // Remove blocks from former ancestor loops.
653 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000654
655 // Add direct subloops as children in their new parent loop.
656 Updater.updateSubloopParents();
657
658 // Remove unloop from its parent loop.
659 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000660 for (Loop::iterator I = ParentLoop->begin();; ++I) {
661 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000662 if (*I == Unloop) {
663 ParentLoop->removeChildLoop(I);
664 break;
665 }
666 }
667}
668
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000669//===----------------------------------------------------------------------===//
670// LoopInfo implementation
671//
672
673char LoopInfoWrapperPass::ID = 0;
674INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
675 true, true)
676INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
677INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
678 true, true)
679
680bool LoopInfoWrapperPass::runOnFunction(Function &) {
681 releaseMemory();
682 LI.getBase().Analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
683 return false;
684}
685
686void LoopInfoWrapperPass::verifyAnalysis() const {
687 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
688 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman4dbb3012009-09-28 00:27:48 +0000689 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000690 // checking by default, LoopPass has been taught to call verifyLoop manually
691 // during loop pass sequences.
Dan Gohman4dbb3012009-09-28 00:27:48 +0000692
693 if (!VerifyLoopInfo) return;
694
Andrew Trick147d9cd2011-08-26 03:06:34 +0000695 DenseSet<const Loop*> Loops;
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000696 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) {
Dan Gohman3ddbc242009-09-08 15:45:00 +0000697 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
Andrew Trick147d9cd2011-08-26 03:06:34 +0000698 (*I)->verifyLoopNest(&Loops);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000699 }
Dan Gohman4dbb3012009-09-28 00:27:48 +0000700
Andrew Trick147d9cd2011-08-26 03:06:34 +0000701 // Verify that blocks are mapped to valid loops.
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000702 for (auto &Entry : LI.LI.BBMap) {
703 BasicBlock *BB = Entry.first;
704 Loop *L = Entry.second;
705 assert(Loops.count(L) && "orphaned loop");
706 assert(L->contains(BB) && "orphaned block");
Andrew Trick147d9cd2011-08-26 03:06:34 +0000707 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000708}
709
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000710void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000711 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000712 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000713}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000714
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000715void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
716 LI.LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000717}
718
Andrew Trick78b40c32011-08-10 01:59:05 +0000719//===----------------------------------------------------------------------===//
720// LoopBlocksDFS implementation
721//
722
723/// Traverse the loop blocks and store the DFS result.
724/// Useful for clients that just want the final DFS result and don't need to
725/// visit blocks during the initial traversal.
726void LoopBlocksDFS::perform(LoopInfo *LI) {
727 LoopBlocksTraversal Traversal(*this, LI);
728 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
729 POE = Traversal.end(); POI != POE; ++POI) ;
730}