blob: fd4382902bf5cc97a52f43baeab6f51925ceaf3f [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
Devang Patel8c78a0b2007-05-03 01:11:54 +000048char LoopInfo::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000049INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
Chandler Carruth73523022014-01-13 13:07:17 +000050INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000051INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
Chris Lattnerccf571a2002-01-31 00:42:27 +000052
Paul Redmond5fdf8362013-05-28 20:00:34 +000053// Loop identifier metadata name.
Craig Topperd3a34f82013-07-16 01:17:10 +000054static const char *const LoopMDName = "llvm.loop";
Paul Redmond5fdf8362013-05-28 20:00:34 +000055
Chris Lattnerccf571a2002-01-31 00:42:27 +000056//===----------------------------------------------------------------------===//
Chris Lattner78dd56f2002-04-28 16:21:30 +000057// Loop implementation
Chris Lattnerccf571a2002-01-31 00:42:27 +000058//
Misha Brukman3845be22002-10-11 05:31:10 +000059
Dan Gohman80a99422009-07-13 22:02:44 +000060/// isLoopInvariant - Return true if the specified value is loop invariant
61///
62bool Loop::isLoopInvariant(Value *V) const {
63 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000064 return !contains(I);
Dan Gohman80a99422009-07-13 22:02:44 +000065 return true; // All non-instructions are loop invariant
66}
67
Chris Lattnerda24b9a2010-09-06 01:05:37 +000068/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trickf898cbd2011-08-03 23:45:50 +000069/// specified instruction are loop invariant.
Chris Lattnerda24b9a2010-09-06 01:05:37 +000070bool Loop::hasLoopInvariantOperands(Instruction *I) const {
71 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
72 if (!isLoopInvariant(I->getOperand(i)))
73 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000074
Chris Lattnerda24b9a2010-09-06 01:05:37 +000075 return true;
Dan Gohman6f6d8642009-07-14 01:06:29 +000076}
77
78/// makeLoopInvariant - If the given value is an instruciton inside of the
79/// loop and it can be hoisted, do so to make it trivially loop-invariant.
80/// Return true if the value after any hoisting is loop invariant. This
81/// function can be used as a slightly more aggressive replacement for
82/// isLoopInvariant.
83///
84/// If InsertPt is specified, it is the point to hoist instructions to.
85/// If null, the terminator of the loop preheader is used.
86///
Dan Gohmanc43e4792009-07-15 01:25:43 +000087bool Loop::makeLoopInvariant(Value *V, bool &Changed,
88 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000089 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000090 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman6f6d8642009-07-14 01:06:29 +000091 return true; // All non-instructions are loop-invariant.
92}
93
94/// makeLoopInvariant - If the given instruction is inside of the
95/// loop and it can be hoisted, do so to make it trivially loop-invariant.
96/// Return true if the instruction after any hoisting is loop invariant. This
97/// function can be used as a slightly more aggressive replacement for
98/// isLoopInvariant.
99///
100/// If InsertPt is specified, it is the point to hoist instructions to.
101/// If null, the terminator of the loop preheader is used.
102///
Dan Gohmanc43e4792009-07-15 01:25:43 +0000103bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
104 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +0000105 // Test if the value is already loop-invariant.
106 if (isLoopInvariant(I))
107 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +0000108 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000109 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000110 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +0000111 return false;
Bill Wendlinga9ee09f2011-08-17 20:36:44 +0000112 // The landingpad instruction is immobile.
113 if (isa<LandingPadInst>(I))
114 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000115 // Determine the insertion point, unless one was given.
116 if (!InsertPt) {
117 BasicBlock *Preheader = getLoopPreheader();
118 // Without a preheader, hoisting is not feasible.
119 if (!Preheader)
120 return false;
121 InsertPt = Preheader->getTerminator();
122 }
123 // Don't hoist instructions with loop-variant operands.
124 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanc43e4792009-07-15 01:25:43 +0000125 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000126 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +0000127
Dan Gohman6f6d8642009-07-14 01:06:29 +0000128 // Hoist.
129 I->moveBefore(InsertPt);
Dan Gohmanc43e4792009-07-15 01:25:43 +0000130 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000131 return true;
132}
133
Dan Gohman80a99422009-07-13 22:02:44 +0000134/// getCanonicalInductionVariable - Check to see if the loop has a canonical
135/// induction variable: an integer recurrence that starts at 0 and increments
136/// by one each time through the loop. If so, return the phi node that
137/// corresponds to it.
138///
139/// The IndVarSimplify pass transforms loops to have a canonical induction
140/// variable.
141///
142PHINode *Loop::getCanonicalInductionVariable() const {
143 BasicBlock *H = getHeader();
144
Craig Topper9f008862014-04-15 04:59:12 +0000145 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000146 pred_iterator PI = pred_begin(H);
147 assert(PI != pred_end(H) &&
Dan Gohman80a99422009-07-13 22:02:44 +0000148 "Loop must have at least one backedge!");
149 Backedge = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000150 if (PI == pred_end(H)) return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000151 Incoming = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000152 if (PI != pred_end(H)) return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000153
154 if (contains(Incoming)) {
155 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000156 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000157 std::swap(Incoming, Backedge);
158 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000159 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000160
161 // Loop over all of the PHI nodes, looking for a canonical indvar.
162 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
163 PHINode *PN = cast<PHINode>(I);
164 if (ConstantInt *CI =
165 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
166 if (CI->isNullValue())
167 if (Instruction *Inc =
168 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
169 if (Inc->getOpcode() == Instruction::Add &&
170 Inc->getOperand(0) == PN)
171 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
172 if (CI->equalsInt(1))
173 return PN;
174 }
Craig Topper9f008862014-04-15 04:59:12 +0000175 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000176}
177
Dan Gohman80a99422009-07-13 22:02:44 +0000178/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohman2734ebd2010-03-10 19:38:49 +0000179bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman80a99422009-07-13 22:02:44 +0000180 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman5196e412009-11-09 18:19:43 +0000181 BasicBlock *BB = *BI;
182 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000183 for (Use &U : I->uses()) {
184 Instruction *UI = cast<Instruction>(U.getUser());
185 BasicBlock *UserBB = UI->getParent();
186 if (PHINode *P = dyn_cast<PHINode>(UI))
187 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000188
Dan Gohman93452ce2010-03-09 01:53:33 +0000189 // Check the current block, as a fast-path, before checking whether
190 // the use is anywhere in the loop. Most values are used in the same
191 // block they are defined in. Also, blocks not reachable from the
192 // entry are special; uses in them don't need to go through PHIs.
193 if (UserBB != BB &&
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000194 !contains(UserBB) &&
Dan Gohman2734ebd2010-03-10 19:38:49 +0000195 DT.isReachableFromEntry(UserBB))
Dan Gohman80a99422009-07-13 22:02:44 +0000196 return false;
197 }
198 }
199
200 return true;
201}
Dan Gohman1511f702009-07-16 16:16:23 +0000202
203/// isLoopSimplifyForm - Return true if the Loop is in the form that
204/// the LoopSimplify form transforms loops to, which is sometimes called
205/// normal form.
206bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000207 // Normal-form loops have a preheader, a single backedge, and all of their
208 // exits have all their predecessors inside the loop.
209 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
210}
211
Andrew Trick4442bfe2012-04-10 05:14:42 +0000212/// isSafeToClone - Return true if the loop body is safe to clone in practice.
213/// Routines that reform the loop CFG and split edges often fail on indirectbr.
214bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000215 // Return false if any loop blocks contain indirectbrs, or there are any calls
216 // to noduplicate functions.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000217 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000218 if (isa<IndirectBrInst>((*I)->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000219 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000220
221 if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()))
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000222 if (II->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000223 return false;
James Molloy4f6fb952012-12-20 16:04:27 +0000224
225 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
226 if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000227 if (CI->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000228 return false;
229 }
230 }
Andrew Trick4442bfe2012-04-10 05:14:42 +0000231 }
232 return true;
233}
234
Paul Redmond5fdf8362013-05-28 20:00:34 +0000235MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000236 MDNode *LoopID = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000237 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +0000238 LoopID = getLoopLatch()->getTerminator()->getMDNode(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000239 } else {
240 // Go through each predecessor of the loop header and check the
241 // terminator for the metadata.
242 BasicBlock *H = getHeader();
243 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
244 TerminatorInst *TI = (*I)->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000245 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000246
247 // Check if this terminator branches to the loop header.
248 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
249 if (TI->getSuccessor(i) == H) {
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +0000250 MD = TI->getMDNode(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000251 break;
252 }
253 }
254 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000255 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000256
257 if (!LoopID)
258 LoopID = MD;
259 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000260 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000261 }
262 }
263 if (!LoopID || LoopID->getNumOperands() == 0 ||
264 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000265 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000266 return LoopID;
267}
268
269void Loop::setLoopID(MDNode *LoopID) const {
270 assert(LoopID && "Loop ID should not be null");
271 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
272 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
273
274 if (isLoopSimplifyForm()) {
275 getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
276 return;
277 }
278
279 BasicBlock *H = getHeader();
280 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
281 TerminatorInst *TI = (*I)->getTerminator();
282 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
283 if (TI->getSuccessor(i) == H)
284 TI->setMetadata(LoopMDName, LoopID);
285 }
286 }
287}
288
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000289bool Loop::isAnnotatedParallel() const {
Paul Redmond5fdf8362013-05-28 20:00:34 +0000290 MDNode *desiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000291
292 if (!desiredLoopIdMetadata)
293 return false;
294
295 // The loop branch contains the parallel loop metadata. In order to ensure
296 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
297 // dependencies (thus converted the loop back to a sequential loop), check
298 // that all the memory instructions in the loop contain parallelism metadata
299 // that point to the same unique "loop id metadata" the loop branch does.
300 for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
301 for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
302 II != EE; II++) {
303
304 if (!II->mayReadOrWriteMemory())
305 continue;
306
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000307 // The memory instruction can refer to the loop identifier metadata
308 // directly or indirectly through another list metadata (in case of
309 // nested parallel loops). The loop identifier metadata refers to
310 // itself so we can check both cases with the same routine.
Philip Reames5a3f5f72014-10-21 00:13:20 +0000311 MDNode *loopIdMD =
Duncan P. N. Exon Smith3872d002014-11-01 00:10:31 +0000312 II->getMDNode(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000313
314 if (!loopIdMD)
315 return false;
316
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000317 bool loopIdMDFound = false;
318 for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
319 if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
320 loopIdMDFound = true;
321 break;
322 }
323 }
324
325 if (!loopIdMDFound)
326 return false;
327 }
328 }
329 return true;
330}
331
332
Dan Gohmane3a17062009-11-05 19:21:41 +0000333/// hasDedicatedExits - Return true if no exit block for the loop
334/// has a predecessor that is outside the loop.
335bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000336 // Each predecessor of each exit block of a normal loop is contained
337 // within the loop.
338 SmallVector<BasicBlock *, 4> ExitBlocks;
339 getExitBlocks(ExitBlocks);
340 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000341 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
342 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
343 if (!contains(*PI))
Dan Gohman1511f702009-07-16 16:16:23 +0000344 return false;
345 // All the requirements are met.
346 return true;
347}
348
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000349/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
350/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman84ba0392009-12-11 20:05:23 +0000351/// This assumes that loop exits are in canonical form.
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000352///
353void
354Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000355 assert(hasDedicatedExits() &&
356 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000357
Dan Gohmaned8f3202009-09-03 20:36:13 +0000358 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000359
360 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
361
362 BasicBlock *current = *BI;
363 switchExitBlocks.clear();
364
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000365 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000366 // If block is inside the loop then it is not a exit block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000367 if (contains(*I))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000368 continue;
369
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000370 pred_iterator PI = pred_begin(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000371 BasicBlock *firstPred = *PI;
372
373 // If current basic block is this exit block's first predecessor
374 // then only insert exit block in to the output ExitBlocks vector.
375 // This ensures that same exit block is not inserted twice into
376 // ExitBlocks vector.
377 if (current != firstPred)
378 continue;
379
380 // If a terminator has more then two successors, for example SwitchInst,
381 // then it is possible that there are multiple edges from current block
382 // to one exit block.
Dan Gohmanacafc612010-07-23 21:25:16 +0000383 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000384 ExitBlocks.push_back(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000385 continue;
386 }
387
388 // In case of multiple edges from current block to exit block, collect
389 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
390 // duplicate edges.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000391 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000392 == switchExitBlocks.end()) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000393 switchExitBlocks.push_back(*I);
394 ExitBlocks.push_back(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000395 }
396 }
397 }
398}
399
400/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
401/// block, return that block. Otherwise return null.
402BasicBlock *Loop::getUniqueExitBlock() const {
403 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
404 getUniqueExitBlocks(UniqueExitBlocks);
405 if (UniqueExitBlocks.size() == 1)
406 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000407 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000408}
409
Manman Ren49d684e2012-09-12 05:06:18 +0000410#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohmanc3f21372010-01-05 21:08:02 +0000411void Loop::dump() const {
412 print(dbgs());
413}
Manman Renc3366cc2012-09-06 19:55:56 +0000414#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000415
Chris Lattner26750072002-07-27 01:12:17 +0000416//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000417// UnloopUpdater implementation
418//
419
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000420namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000421/// Find the new parent loop for all blocks within the "unloop" whose last
422/// backedges has just been removed.
423class UnloopUpdater {
424 Loop *Unloop;
425 LoopInfo *LI;
426
427 LoopBlocksDFS DFS;
428
429 // Map unloop's immediate subloops to their nearest reachable parents. Nested
430 // loops within these subloops will not change parents. However, an immediate
431 // subloop's new parent will be the nearest loop reachable from either its own
432 // exits *or* any of its nested loop's exits.
433 DenseMap<Loop*, Loop*> SubloopParents;
434
435 // Flag the presence of an irreducible backedge whose destination is a block
436 // directly contained by the original unloop.
437 bool FoundIB;
438
439public:
440 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
441 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
442
443 void updateBlockParents();
444
Andrew Trickc12c30a2011-08-11 20:27:32 +0000445 void removeBlocksFromAncestors();
446
Andrew Trickd3530b92011-08-10 23:22:57 +0000447 void updateSubloopParents();
448
449protected:
450 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
451};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000452} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000453
454/// updateBlockParents - Update the parent loop for all blocks that are directly
455/// contained within the original "unloop".
456void UnloopUpdater::updateBlockParents() {
457 if (Unloop->getNumBlocks()) {
458 // Perform a post order CFG traversal of all blocks within this loop,
459 // propagating the nearest loop from sucessors to predecessors.
460 LoopBlocksTraversal Traversal(DFS, LI);
461 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
462 POE = Traversal.end(); POI != POE; ++POI) {
463
464 Loop *L = LI->getLoopFor(*POI);
465 Loop *NL = getNearestLoop(*POI, L);
466
467 if (NL != L) {
468 // For reducible loops, NL is now an ancestor of Unloop.
469 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
470 "uninitialized successor");
471 LI->changeLoopFor(*POI, NL);
472 }
473 else {
474 // Or the current block is part of a subloop, in which case its parent
475 // is unchanged.
476 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
477 }
478 }
479 }
480 // Each irreducible loop within the unloop induces a round of iteration using
481 // the DFS result cached by Traversal.
482 bool Changed = FoundIB;
483 for (unsigned NIters = 0; Changed; ++NIters) {
484 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
485
486 // Iterate over the postorder list of blocks, propagating the nearest loop
487 // from successors to predecessors as before.
488 Changed = false;
489 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
490 POE = DFS.endPostorder(); POI != POE; ++POI) {
491
492 Loop *L = LI->getLoopFor(*POI);
493 Loop *NL = getNearestLoop(*POI, L);
494 if (NL != L) {
495 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
496 "uninitialized successor");
497 LI->changeLoopFor(*POI, NL);
498 Changed = true;
499 }
500 }
501 }
502}
503
Andrew Trickc12c30a2011-08-11 20:27:32 +0000504/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
505/// their new parents.
506void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000507 // Remove all unloop's blocks (including those in nested subloops) from
508 // ancestors below the new parent loop.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000509 for (Loop::block_iterator BI = Unloop->block_begin(),
510 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000511 Loop *OuterParent = LI->getLoopFor(*BI);
512 if (Unloop->contains(OuterParent)) {
513 while (OuterParent->getParentLoop() != Unloop)
514 OuterParent = OuterParent->getParentLoop();
515 OuterParent = SubloopParents[OuterParent];
516 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000517 // Remove blocks from former Ancestors except Unloop itself which will be
518 // deleted.
Andrew Trick6b4d5782011-11-18 03:42:41 +0000519 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000520 OldParent = OldParent->getParentLoop()) {
521 assert(OldParent && "new loop is not an ancestor of the original");
522 OldParent->removeBlockFromLoop(*BI);
523 }
524 }
525}
526
Andrew Trickd3530b92011-08-10 23:22:57 +0000527/// updateSubloopParents - Update the parent loop for all subloops directly
528/// nested within unloop.
529void UnloopUpdater::updateSubloopParents() {
530 while (!Unloop->empty()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000531 Loop *Subloop = *std::prev(Unloop->end());
532 Unloop->removeChildLoop(std::prev(Unloop->end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000533
534 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000535 if (Loop *Parent = SubloopParents[Subloop])
536 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000537 else
538 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000539 }
540}
541
542/// getNearestLoop - Return the nearest parent loop among this block's
543/// successors. If a successor is a subloop header, consider its parent to be
544/// the nearest parent of the subloop's exits.
545///
546/// For subloop blocks, simply update SubloopParents and return NULL.
547Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
548
Andrew Trick266ab102011-08-11 17:54:58 +0000549 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
550 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000551 Loop *NearLoop = BBLoop;
552
Craig Topper9f008862014-04-15 04:59:12 +0000553 Loop *Subloop = nullptr;
Andrew Trickd3530b92011-08-10 23:22:57 +0000554 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
555 Subloop = NearLoop;
556 // Find the subloop ancestor that is directly contained within Unloop.
557 while (Subloop->getParentLoop() != Unloop) {
558 Subloop = Subloop->getParentLoop();
559 assert(Subloop && "subloop is not an ancestor of the original loop");
560 }
561 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000562 NearLoop =
563 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000564 }
565
566 succ_iterator I = succ_begin(BB), E = succ_end(BB);
567 if (I == E) {
568 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000569 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000570 }
571 for (; I != E; ++I) {
572 if (*I == BB)
573 continue; // self loops are uninteresting
574
575 Loop *L = LI->getLoopFor(*I);
576 if (L == Unloop) {
577 // This successor has not been processed. This path must lead to an
578 // irreducible backedge.
579 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
580 FoundIB = true;
581 }
582 if (L != Unloop && Unloop->contains(L)) {
583 // Successor is in a subloop.
584 if (Subloop)
585 continue; // Branching within subloops. Ignore it.
586
587 // BB branches from the original into a subloop header.
588 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
589
590 // Get the current nearest parent of the Subloop's exits.
591 L = SubloopParents[L];
592 // L could be Unloop if the only exit was an irreducible backedge.
593 }
594 if (L == Unloop) {
595 continue;
596 }
597 // Handle critical edges from Unloop into a sibling loop.
598 if (L && !L->contains(Unloop)) {
599 L = L->getParentLoop();
600 }
601 // Remember the nearest parent loop among successors or subloop exits.
602 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
603 NearLoop = L;
604 }
605 if (Subloop) {
606 SubloopParents[Subloop] = NearLoop;
607 return BBLoop;
608 }
609 return NearLoop;
610}
611
612//===----------------------------------------------------------------------===//
Chris Lattner26750072002-07-27 01:12:17 +0000613// LoopInfo implementation
614//
Chris Lattner26750072002-07-27 01:12:17 +0000615bool LoopInfo::runOnFunction(Function &) {
616 releaseMemory();
Chandler Carruth73523022014-01-13 13:07:17 +0000617 LI.Analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chris Lattner26750072002-07-27 01:12:17 +0000618 return false;
619}
620
Andrew Trickd3530b92011-08-10 23:22:57 +0000621/// updateUnloop - The last backedge has been removed from a loop--now the
622/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick266ab102011-08-11 17:54:58 +0000623/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickd3530b92011-08-10 23:22:57 +0000624/// point, but LoopInfo is still valid except for the removal of this loop.
625///
626/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
627/// checking first is illegal.
628void LoopInfo::updateUnloop(Loop *Unloop) {
629
630 // First handle the special case of no parent loop to simplify the algorithm.
631 if (!Unloop->getParentLoop()) {
632 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
633 for (Loop::block_iterator I = Unloop->block_begin(),
634 E = Unloop->block_end(); I != E; ++I) {
635
636 // Don't reparent blocks in subloops.
637 if (getLoopFor(*I) != Unloop)
638 continue;
639
640 // Blocks no longer have a parent but are still referenced by Unloop until
641 // the Unloop object is deleted.
Craig Topper9f008862014-04-15 04:59:12 +0000642 LI.changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000643 }
644
645 // Remove the loop from the top-level LoopInfo object.
Duncan Sandsa41634e2011-08-12 14:54:45 +0000646 for (LoopInfo::iterator I = LI.begin();; ++I) {
647 assert(I != LI.end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000648 if (*I == Unloop) {
649 LI.removeLoop(I);
650 break;
651 }
652 }
653
654 // Move all of the subloops to the top-level.
655 while (!Unloop->empty())
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000656 LI.addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000657
658 return;
659 }
660
661 // Update the parent loop for all blocks within the loop. Blocks within
662 // subloops will not change parents.
663 UnloopUpdater Updater(Unloop, this);
664 Updater.updateBlockParents();
665
Andrew Trickc12c30a2011-08-11 20:27:32 +0000666 // Remove blocks from former ancestor loops.
667 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000668
669 // Add direct subloops as children in their new parent loop.
670 Updater.updateSubloopParents();
671
672 // Remove unloop from its parent loop.
673 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000674 for (Loop::iterator I = ParentLoop->begin();; ++I) {
675 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000676 if (*I == Unloop) {
677 ParentLoop->removeChildLoop(I);
678 break;
679 }
680 }
681}
682
Dan Gohman3ddbc242009-09-08 15:45:00 +0000683void LoopInfo::verifyAnalysis() const {
Dan Gohman4dbb3012009-09-28 00:27:48 +0000684 // LoopInfo is a FunctionPass, but verifying every loop in the function
685 // each time verifyAnalysis is called is very expensive. The
686 // -verify-loop-info option can enable this. In order to perform some
687 // checking by default, LoopPass has been taught to call verifyLoop
688 // manually during loop pass sequences.
689
690 if (!VerifyLoopInfo) return;
691
Andrew Trick147d9cd2011-08-26 03:06:34 +0000692 DenseSet<const Loop*> Loops;
Dan Gohman3ddbc242009-09-08 15:45:00 +0000693 for (iterator I = begin(), E = end(); I != E; ++I) {
694 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
Andrew Trick147d9cd2011-08-26 03:06:34 +0000695 (*I)->verifyLoopNest(&Loops);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000696 }
Dan Gohman4dbb3012009-09-28 00:27:48 +0000697
Andrew Trick147d9cd2011-08-26 03:06:34 +0000698 // Verify that blocks are mapped to valid loops.
Andrew Trick147d9cd2011-08-26 03:06:34 +0000699 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
700 E = LI.BBMap.end(); I != E; ++I) {
701 assert(Loops.count(I->second) && "orphaned loop");
702 assert(I->second->contains(I->first) && "orphaned block");
703 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000704}
705
Chris Lattner78dd56f2002-04-28 16:21:30 +0000706void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000707 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000708 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000709}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000710
Chris Lattner13626022009-08-23 06:03:38 +0000711void LoopInfo::print(raw_ostream &OS, const Module*) const {
712 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000713}
714
Andrew Trick78b40c32011-08-10 01:59:05 +0000715//===----------------------------------------------------------------------===//
716// LoopBlocksDFS implementation
717//
718
719/// Traverse the loop blocks and store the DFS result.
720/// Useful for clients that just want the final DFS result and don't need to
721/// visit blocks during the initial traversal.
722void LoopBlocksDFS::perform(LoopInfo *LI) {
723 LoopBlocksTraversal Traversal(*this, LI);
724 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
725 POE = Traversal.end(); POI != POE; ++POI) ;
726}