blob: 6b6faf8a66c3c6295b70b197b241da6bd77edbd1 [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"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000029#include "llvm/IR/PassManager.h"
Dan Gohman4dbb3012009-09-28 00:27:48 +000030#include "llvm/Support/CommandLine.h"
Dan Gohmanc3f21372010-01-05 21:08:02 +000031#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include "llvm/Support/raw_ostream.h"
Chris Lattner6de99422001-11-26 18:41:20 +000033#include <algorithm>
Chris Lattner55b7ef52004-04-12 20:26:17 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Andrew Trickcda51d42012-06-20 03:42:09 +000036// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
37template class llvm::LoopBase<BasicBlock, Loop>;
38template class llvm::LoopInfoBase<BasicBlock, Loop>;
39
Dan Gohman4dbb3012009-09-28 00:27:48 +000040// Always verify loopinfo if expensive checking is enabled.
41#ifdef XDEBUG
Dan Gohmanb29cda92010-04-15 17:08:50 +000042static bool VerifyLoopInfo = true;
Dan Gohman4dbb3012009-09-28 00:27:48 +000043#else
Dan Gohmanb29cda92010-04-15 17:08:50 +000044static bool VerifyLoopInfo = false;
Dan Gohman4dbb3012009-09-28 00:27:48 +000045#endif
46static cl::opt<bool,true>
47VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
48 cl::desc("Verify loop info (time consuming)"));
49
Paul Redmond5fdf8362013-05-28 20:00:34 +000050// Loop identifier metadata name.
Craig Topperd3a34f82013-07-16 01:17:10 +000051static const char *const LoopMDName = "llvm.loop";
Paul Redmond5fdf8362013-05-28 20:00:34 +000052
Chris Lattnerccf571a2002-01-31 00:42:27 +000053//===----------------------------------------------------------------------===//
Chris Lattner78dd56f2002-04-28 16:21:30 +000054// Loop implementation
Chris Lattnerccf571a2002-01-31 00:42:27 +000055//
Misha Brukman3845be22002-10-11 05:31:10 +000056
Dan Gohman80a99422009-07-13 22:02:44 +000057/// isLoopInvariant - Return true if the specified value is loop invariant
58///
Pete Cooper016daa62015-05-13 01:12:06 +000059bool Loop::isLoopInvariant(const Value *V) const {
60 if (const Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000061 return !contains(I);
Dan Gohman80a99422009-07-13 22:02:44 +000062 return true; // All non-instructions are loop invariant
63}
64
Chris Lattnerda24b9a2010-09-06 01:05:37 +000065/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trickf898cbd2011-08-03 23:45:50 +000066/// specified instruction are loop invariant.
Pete Cooper016daa62015-05-13 01:12:06 +000067bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
Pete Coopera264dc02015-05-13 22:19:13 +000068 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
Dan Gohman6f6d8642009-07-14 01:06:29 +000069}
70
71/// makeLoopInvariant - If the given value is an instruciton inside of the
72/// loop and it can be hoisted, do so to make it trivially loop-invariant.
73/// Return true if the value after any hoisting is loop invariant. This
74/// function can be used as a slightly more aggressive replacement for
75/// isLoopInvariant.
76///
77/// If InsertPt is specified, it is the point to hoist instructions to.
78/// If null, the terminator of the loop preheader is used.
79///
Dan Gohmanc43e4792009-07-15 01:25:43 +000080bool Loop::makeLoopInvariant(Value *V, bool &Changed,
81 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000082 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000083 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman6f6d8642009-07-14 01:06:29 +000084 return true; // All non-instructions are loop-invariant.
85}
86
87/// makeLoopInvariant - If the given instruction is inside of the
88/// loop and it can be hoisted, do so to make it trivially loop-invariant.
89/// Return true if the instruction after any hoisting is loop invariant. This
90/// function can be used as a slightly more aggressive replacement for
91/// isLoopInvariant.
92///
93/// If InsertPt is specified, it is the point to hoist instructions to.
94/// If null, the terminator of the loop preheader is used.
95///
Dan Gohmanc43e4792009-07-15 01:25:43 +000096bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
97 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000098 // Test if the value is already loop-invariant.
99 if (isLoopInvariant(I))
100 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +0000101 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000102 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000103 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +0000104 return false;
Bill Wendlinga9ee09f2011-08-17 20:36:44 +0000105 // The landingpad instruction is immobile.
106 if (isa<LandingPadInst>(I))
107 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000108 // Determine the insertion point, unless one was given.
109 if (!InsertPt) {
110 BasicBlock *Preheader = getLoopPreheader();
111 // Without a preheader, hoisting is not feasible.
112 if (!Preheader)
113 return false;
114 InsertPt = Preheader->getTerminator();
115 }
116 // Don't hoist instructions with loop-variant operands.
117 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanc43e4792009-07-15 01:25:43 +0000118 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000119 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +0000120
Dan Gohman6f6d8642009-07-14 01:06:29 +0000121 // Hoist.
122 I->moveBefore(InsertPt);
Dan Gohmanc43e4792009-07-15 01:25:43 +0000123 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000124 return true;
125}
126
Dan Gohman80a99422009-07-13 22:02:44 +0000127/// getCanonicalInductionVariable - Check to see if the loop has a canonical
128/// induction variable: an integer recurrence that starts at 0 and increments
129/// by one each time through the loop. If so, return the phi node that
130/// corresponds to it.
131///
132/// The IndVarSimplify pass transforms loops to have a canonical induction
133/// variable.
134///
135PHINode *Loop::getCanonicalInductionVariable() const {
136 BasicBlock *H = getHeader();
137
Craig Topper9f008862014-04-15 04:59:12 +0000138 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000139 pred_iterator PI = pred_begin(H);
140 assert(PI != pred_end(H) &&
Dan Gohman80a99422009-07-13 22:02:44 +0000141 "Loop must have at least one backedge!");
142 Backedge = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000143 if (PI == pred_end(H)) return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000144 Incoming = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000145 if (PI != pred_end(H)) return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000146
147 if (contains(Incoming)) {
148 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000149 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000150 std::swap(Incoming, Backedge);
151 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000152 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000153
154 // Loop over all of the PHI nodes, looking for a canonical indvar.
155 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
156 PHINode *PN = cast<PHINode>(I);
157 if (ConstantInt *CI =
158 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
159 if (CI->isNullValue())
160 if (Instruction *Inc =
161 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
162 if (Inc->getOpcode() == Instruction::Add &&
163 Inc->getOperand(0) == PN)
164 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
165 if (CI->equalsInt(1))
166 return PN;
167 }
Craig Topper9f008862014-04-15 04:59:12 +0000168 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000169}
170
Dan Gohman80a99422009-07-13 22:02:44 +0000171/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohman2734ebd2010-03-10 19:38:49 +0000172bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman80a99422009-07-13 22:02:44 +0000173 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman5196e412009-11-09 18:19:43 +0000174 BasicBlock *BB = *BI;
175 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000176 for (Use &U : I->uses()) {
177 Instruction *UI = cast<Instruction>(U.getUser());
178 BasicBlock *UserBB = UI->getParent();
179 if (PHINode *P = dyn_cast<PHINode>(UI))
180 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000181
Dan Gohman93452ce2010-03-09 01:53:33 +0000182 // Check the current block, as a fast-path, before checking whether
183 // the use is anywhere in the loop. Most values are used in the same
184 // block they are defined in. Also, blocks not reachable from the
185 // entry are special; uses in them don't need to go through PHIs.
186 if (UserBB != BB &&
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000187 !contains(UserBB) &&
Dan Gohman2734ebd2010-03-10 19:38:49 +0000188 DT.isReachableFromEntry(UserBB))
Dan Gohman80a99422009-07-13 22:02:44 +0000189 return false;
190 }
191 }
192
193 return true;
194}
Dan Gohman1511f702009-07-16 16:16:23 +0000195
196/// isLoopSimplifyForm - Return true if the Loop is in the form that
197/// the LoopSimplify form transforms loops to, which is sometimes called
198/// normal form.
199bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000200 // Normal-form loops have a preheader, a single backedge, and all of their
201 // exits have all their predecessors inside the loop.
202 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
203}
204
Andrew Trick4442bfe2012-04-10 05:14:42 +0000205/// isSafeToClone - Return true if the loop body is safe to clone in practice.
206/// Routines that reform the loop CFG and split edges often fail on indirectbr.
207bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000208 // Return false if any loop blocks contain indirectbrs, or there are any calls
209 // to noduplicate functions.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000210 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000211 if (isa<IndirectBrInst>((*I)->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000212 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000213
214 if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()))
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000215 if (II->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000216 return false;
James Molloy4f6fb952012-12-20 16:04:27 +0000217
218 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
219 if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000220 if (CI->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000221 return false;
222 }
223 }
Andrew Trick4442bfe2012-04-10 05:14:42 +0000224 }
225 return true;
226}
227
Paul Redmond5fdf8362013-05-28 20:00:34 +0000228MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000229 MDNode *LoopID = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000230 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000231 LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000232 } else {
233 // Go through each predecessor of the loop header and check the
234 // terminator for the metadata.
235 BasicBlock *H = getHeader();
236 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
237 TerminatorInst *TI = (*I)->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000238 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000239
240 // Check if this terminator branches to the loop header.
241 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
242 if (TI->getSuccessor(i) == H) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000243 MD = TI->getMetadata(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000244 break;
245 }
246 }
247 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000248 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000249
250 if (!LoopID)
251 LoopID = MD;
252 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000253 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000254 }
255 }
256 if (!LoopID || LoopID->getNumOperands() == 0 ||
257 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000258 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000259 return LoopID;
260}
261
262void Loop::setLoopID(MDNode *LoopID) const {
263 assert(LoopID && "Loop ID should not be null");
264 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
265 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
266
267 if (isLoopSimplifyForm()) {
268 getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
269 return;
270 }
271
272 BasicBlock *H = getHeader();
273 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
274 TerminatorInst *TI = (*I)->getTerminator();
275 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
276 if (TI->getSuccessor(i) == H)
277 TI->setMetadata(LoopMDName, LoopID);
278 }
279 }
280}
281
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000282bool Loop::isAnnotatedParallel() const {
Paul Redmond5fdf8362013-05-28 20:00:34 +0000283 MDNode *desiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000284
285 if (!desiredLoopIdMetadata)
286 return false;
287
288 // The loop branch contains the parallel loop metadata. In order to ensure
289 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
290 // dependencies (thus converted the loop back to a sequential loop), check
291 // that all the memory instructions in the loop contain parallelism metadata
292 // that point to the same unique "loop id metadata" the loop branch does.
293 for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
294 for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
295 II != EE; II++) {
296
297 if (!II->mayReadOrWriteMemory())
298 continue;
299
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000300 // The memory instruction can refer to the loop identifier metadata
301 // directly or indirectly through another list metadata (in case of
302 // nested parallel loops). The loop identifier metadata refers to
303 // itself so we can check both cases with the same routine.
Philip Reames5a3f5f72014-10-21 00:13:20 +0000304 MDNode *loopIdMD =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000305 II->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000306
307 if (!loopIdMD)
308 return false;
309
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000310 bool loopIdMDFound = false;
311 for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
312 if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
313 loopIdMDFound = true;
314 break;
315 }
316 }
317
318 if (!loopIdMDFound)
319 return false;
320 }
321 }
322 return true;
323}
324
325
Dan Gohmane3a17062009-11-05 19:21:41 +0000326/// hasDedicatedExits - Return true if no exit block for the loop
327/// has a predecessor that is outside the loop.
328bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000329 // Each predecessor of each exit block of a normal loop is contained
330 // within the loop.
331 SmallVector<BasicBlock *, 4> ExitBlocks;
332 getExitBlocks(ExitBlocks);
333 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000334 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
335 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
336 if (!contains(*PI))
Dan Gohman1511f702009-07-16 16:16:23 +0000337 return false;
338 // All the requirements are met.
339 return true;
340}
341
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000342/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
343/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman84ba0392009-12-11 20:05:23 +0000344/// This assumes that loop exits are in canonical form.
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000345///
346void
347Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000348 assert(hasDedicatedExits() &&
349 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000350
Dan Gohmaned8f3202009-09-03 20:36:13 +0000351 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000352
353 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
354
355 BasicBlock *current = *BI;
356 switchExitBlocks.clear();
357
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000358 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000359 // If block is inside the loop then it is not a exit block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000360 if (contains(*I))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000361 continue;
362
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000363 pred_iterator PI = pred_begin(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000364 BasicBlock *firstPred = *PI;
365
366 // If current basic block is this exit block's first predecessor
367 // then only insert exit block in to the output ExitBlocks vector.
368 // This ensures that same exit block is not inserted twice into
369 // ExitBlocks vector.
370 if (current != firstPred)
371 continue;
372
373 // If a terminator has more then two successors, for example SwitchInst,
374 // then it is possible that there are multiple edges from current block
375 // to one exit block.
Dan Gohmanacafc612010-07-23 21:25:16 +0000376 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000377 ExitBlocks.push_back(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000378 continue;
379 }
380
381 // In case of multiple edges from current block to exit block, collect
382 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
383 // duplicate edges.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000384 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000385 == switchExitBlocks.end()) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000386 switchExitBlocks.push_back(*I);
387 ExitBlocks.push_back(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000388 }
389 }
390 }
391}
392
393/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
394/// block, return that block. Otherwise return null.
395BasicBlock *Loop::getUniqueExitBlock() const {
396 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
397 getUniqueExitBlocks(UniqueExitBlocks);
398 if (UniqueExitBlocks.size() == 1)
399 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000400 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000401}
402
Manman Ren49d684e2012-09-12 05:06:18 +0000403#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohmanc3f21372010-01-05 21:08:02 +0000404void Loop::dump() const {
405 print(dbgs());
406}
Manman Renc3366cc2012-09-06 19:55:56 +0000407#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000408
Chris Lattner26750072002-07-27 01:12:17 +0000409//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000410// UnloopUpdater implementation
411//
412
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000413namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000414/// Find the new parent loop for all blocks within the "unloop" whose last
415/// backedges has just been removed.
416class UnloopUpdater {
417 Loop *Unloop;
418 LoopInfo *LI;
419
420 LoopBlocksDFS DFS;
421
422 // Map unloop's immediate subloops to their nearest reachable parents. Nested
423 // loops within these subloops will not change parents. However, an immediate
424 // subloop's new parent will be the nearest loop reachable from either its own
425 // exits *or* any of its nested loop's exits.
426 DenseMap<Loop*, Loop*> SubloopParents;
427
428 // Flag the presence of an irreducible backedge whose destination is a block
429 // directly contained by the original unloop.
430 bool FoundIB;
431
432public:
433 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
434 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
435
436 void updateBlockParents();
437
Andrew Trickc12c30a2011-08-11 20:27:32 +0000438 void removeBlocksFromAncestors();
439
Andrew Trickd3530b92011-08-10 23:22:57 +0000440 void updateSubloopParents();
441
442protected:
443 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
444};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000445} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000446
447/// updateBlockParents - Update the parent loop for all blocks that are directly
448/// contained within the original "unloop".
449void UnloopUpdater::updateBlockParents() {
450 if (Unloop->getNumBlocks()) {
451 // Perform a post order CFG traversal of all blocks within this loop,
452 // propagating the nearest loop from sucessors to predecessors.
453 LoopBlocksTraversal Traversal(DFS, LI);
454 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
455 POE = Traversal.end(); POI != POE; ++POI) {
456
457 Loop *L = LI->getLoopFor(*POI);
458 Loop *NL = getNearestLoop(*POI, L);
459
460 if (NL != L) {
461 // For reducible loops, NL is now an ancestor of Unloop.
462 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
463 "uninitialized successor");
464 LI->changeLoopFor(*POI, NL);
465 }
466 else {
467 // Or the current block is part of a subloop, in which case its parent
468 // is unchanged.
469 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
470 }
471 }
472 }
473 // Each irreducible loop within the unloop induces a round of iteration using
474 // the DFS result cached by Traversal.
475 bool Changed = FoundIB;
476 for (unsigned NIters = 0; Changed; ++NIters) {
477 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
478
479 // Iterate over the postorder list of blocks, propagating the nearest loop
480 // from successors to predecessors as before.
481 Changed = false;
482 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
483 POE = DFS.endPostorder(); POI != POE; ++POI) {
484
485 Loop *L = LI->getLoopFor(*POI);
486 Loop *NL = getNearestLoop(*POI, L);
487 if (NL != L) {
488 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
489 "uninitialized successor");
490 LI->changeLoopFor(*POI, NL);
491 Changed = true;
492 }
493 }
494 }
495}
496
Andrew Trickc12c30a2011-08-11 20:27:32 +0000497/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
498/// their new parents.
499void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000500 // Remove all unloop's blocks (including those in nested subloops) from
501 // ancestors below the new parent loop.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000502 for (Loop::block_iterator BI = Unloop->block_begin(),
503 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000504 Loop *OuterParent = LI->getLoopFor(*BI);
505 if (Unloop->contains(OuterParent)) {
506 while (OuterParent->getParentLoop() != Unloop)
507 OuterParent = OuterParent->getParentLoop();
508 OuterParent = SubloopParents[OuterParent];
509 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000510 // Remove blocks from former Ancestors except Unloop itself which will be
511 // deleted.
Andrew Trick6b4d5782011-11-18 03:42:41 +0000512 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000513 OldParent = OldParent->getParentLoop()) {
514 assert(OldParent && "new loop is not an ancestor of the original");
515 OldParent->removeBlockFromLoop(*BI);
516 }
517 }
518}
519
Andrew Trickd3530b92011-08-10 23:22:57 +0000520/// updateSubloopParents - Update the parent loop for all subloops directly
521/// nested within unloop.
522void UnloopUpdater::updateSubloopParents() {
523 while (!Unloop->empty()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000524 Loop *Subloop = *std::prev(Unloop->end());
525 Unloop->removeChildLoop(std::prev(Unloop->end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000526
527 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000528 if (Loop *Parent = SubloopParents[Subloop])
529 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000530 else
531 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000532 }
533}
534
535/// getNearestLoop - Return the nearest parent loop among this block's
536/// successors. If a successor is a subloop header, consider its parent to be
537/// the nearest parent of the subloop's exits.
538///
539/// For subloop blocks, simply update SubloopParents and return NULL.
540Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
541
Andrew Trick266ab102011-08-11 17:54:58 +0000542 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
543 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000544 Loop *NearLoop = BBLoop;
545
Craig Topper9f008862014-04-15 04:59:12 +0000546 Loop *Subloop = nullptr;
Andrew Trickd3530b92011-08-10 23:22:57 +0000547 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
548 Subloop = NearLoop;
549 // Find the subloop ancestor that is directly contained within Unloop.
550 while (Subloop->getParentLoop() != Unloop) {
551 Subloop = Subloop->getParentLoop();
552 assert(Subloop && "subloop is not an ancestor of the original loop");
553 }
554 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000555 NearLoop =
556 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000557 }
558
559 succ_iterator I = succ_begin(BB), E = succ_end(BB);
560 if (I == E) {
561 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000562 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000563 }
564 for (; I != E; ++I) {
565 if (*I == BB)
566 continue; // self loops are uninteresting
567
568 Loop *L = LI->getLoopFor(*I);
569 if (L == Unloop) {
570 // This successor has not been processed. This path must lead to an
571 // irreducible backedge.
572 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
573 FoundIB = true;
574 }
575 if (L != Unloop && Unloop->contains(L)) {
576 // Successor is in a subloop.
577 if (Subloop)
578 continue; // Branching within subloops. Ignore it.
579
580 // BB branches from the original into a subloop header.
581 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
582
583 // Get the current nearest parent of the Subloop's exits.
584 L = SubloopParents[L];
585 // L could be Unloop if the only exit was an irreducible backedge.
586 }
587 if (L == Unloop) {
588 continue;
589 }
590 // Handle critical edges from Unloop into a sibling loop.
591 if (L && !L->contains(Unloop)) {
592 L = L->getParentLoop();
593 }
594 // Remember the nearest parent loop among successors or subloop exits.
595 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
596 NearLoop = L;
597 }
598 if (Subloop) {
599 SubloopParents[Subloop] = NearLoop;
600 return BBLoop;
601 }
602 return NearLoop;
603}
604
Andrew Trickd3530b92011-08-10 23:22:57 +0000605/// updateUnloop - The last backedge has been removed from a loop--now the
606/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick266ab102011-08-11 17:54:58 +0000607/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickd3530b92011-08-10 23:22:57 +0000608/// point, but LoopInfo is still valid except for the removal of this loop.
609///
610/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
611/// checking first is illegal.
612void LoopInfo::updateUnloop(Loop *Unloop) {
613
614 // First handle the special case of no parent loop to simplify the algorithm.
615 if (!Unloop->getParentLoop()) {
616 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
617 for (Loop::block_iterator I = Unloop->block_begin(),
Chandler Carruth691addc2015-01-18 01:25:51 +0000618 E = Unloop->block_end();
619 I != E; ++I) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000620
621 // Don't reparent blocks in subloops.
622 if (getLoopFor(*I) != Unloop)
623 continue;
624
625 // Blocks no longer have a parent but are still referenced by Unloop until
626 // the Unloop object is deleted.
Chandler Carruth691addc2015-01-18 01:25:51 +0000627 changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000628 }
629
630 // Remove the loop from the top-level LoopInfo object.
Chandler Carruth691addc2015-01-18 01:25:51 +0000631 for (iterator I = begin();; ++I) {
632 assert(I != end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000633 if (*I == Unloop) {
Chandler Carruth691addc2015-01-18 01:25:51 +0000634 removeLoop(I);
Andrew Trickd3530b92011-08-10 23:22:57 +0000635 break;
636 }
637 }
638
639 // Move all of the subloops to the top-level.
640 while (!Unloop->empty())
Chandler Carruth691addc2015-01-18 01:25:51 +0000641 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000642
643 return;
644 }
645
646 // Update the parent loop for all blocks within the loop. Blocks within
647 // subloops will not change parents.
648 UnloopUpdater Updater(Unloop, this);
649 Updater.updateBlockParents();
650
Andrew Trickc12c30a2011-08-11 20:27:32 +0000651 // Remove blocks from former ancestor loops.
652 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000653
654 // Add direct subloops as children in their new parent loop.
655 Updater.updateSubloopParents();
656
657 // Remove unloop from its parent loop.
658 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000659 for (Loop::iterator I = ParentLoop->begin();; ++I) {
660 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000661 if (*I == Unloop) {
662 ParentLoop->removeChildLoop(I);
663 break;
664 }
665 }
666}
667
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000668char LoopAnalysis::PassID;
669
670LoopInfo LoopAnalysis::run(Function &F, AnalysisManager<Function> *AM) {
671 // FIXME: Currently we create a LoopInfo from scratch for every function.
672 // This may prove to be too wasteful due to deallocating and re-allocating
673 // memory each time for the underlying map and vector datastructures. At some
674 // point it may prove worthwhile to use a freelist and recycle LoopInfo
675 // objects. I don't want to add that kind of complexity until the scope of
676 // the problem is better understood.
677 LoopInfo LI;
678 LI.Analyze(AM->getResult<DominatorTreeAnalysis>(F));
Richard Trieu6ae37962015-04-30 23:07:00 +0000679 return LI;
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000680}
681
682PreservedAnalyses LoopPrinterPass::run(Function &F,
683 AnalysisManager<Function> *AM) {
684 AM->getResult<LoopAnalysis>(F).print(OS);
685 return PreservedAnalyses::all();
686}
687
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000688//===----------------------------------------------------------------------===//
689// LoopInfo implementation
690//
691
692char LoopInfoWrapperPass::ID = 0;
693INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
694 true, true)
695INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
696INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
697 true, true)
698
699bool LoopInfoWrapperPass::runOnFunction(Function &) {
700 releaseMemory();
Chandler Carruth691addc2015-01-18 01:25:51 +0000701 LI.Analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000702 return false;
703}
704
705void LoopInfoWrapperPass::verifyAnalysis() const {
706 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
707 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman4dbb3012009-09-28 00:27:48 +0000708 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000709 // checking by default, LoopPass has been taught to call verifyLoop manually
710 // during loop pass sequences.
Chandler Carruth691addc2015-01-18 01:25:51 +0000711 if (VerifyLoopInfo)
712 LI.verify();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000713}
714
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000715void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000716 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000717 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000718}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000719
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000720void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Chandler Carruth691addc2015-01-18 01:25:51 +0000721 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000722}
723
Andrew Trick78b40c32011-08-10 01:59:05 +0000724//===----------------------------------------------------------------------===//
725// LoopBlocksDFS implementation
726//
727
728/// Traverse the loop blocks and store the DFS result.
729/// Useful for clients that just want the final DFS result and don't need to
730/// visit blocks during the initial traversal.
731void LoopBlocksDFS::perform(LoopInfo *LI) {
732 LoopBlocksTraversal Traversal(*this, LI);
733 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
734 POE = Traversal.end(); POI != POE; ++POI) ;
735}