blob: e3e1a281a6c8aac57dca61a88b1c67e07f69e93c [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
Chris Lattnerccf571a2002-01-31 00:42:27 +000050//===----------------------------------------------------------------------===//
Chris Lattner78dd56f2002-04-28 16:21:30 +000051// Loop implementation
Chris Lattnerccf571a2002-01-31 00:42:27 +000052//
Misha Brukman3845be22002-10-11 05:31:10 +000053
Pete Cooper016daa62015-05-13 01:12:06 +000054bool Loop::isLoopInvariant(const Value *V) const {
55 if (const Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000056 return !contains(I);
Dan Gohman80a99422009-07-13 22:02:44 +000057 return true; // All non-instructions are loop invariant
58}
59
Pete Cooper016daa62015-05-13 01:12:06 +000060bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
Pete Coopera264dc02015-05-13 22:19:13 +000061 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
Dan Gohman6f6d8642009-07-14 01:06:29 +000062}
63
Dan Gohmanc43e4792009-07-15 01:25:43 +000064bool Loop::makeLoopInvariant(Value *V, bool &Changed,
65 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000066 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000067 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman6f6d8642009-07-14 01:06:29 +000068 return true; // All non-instructions are loop-invariant.
69}
70
Dan Gohmanc43e4792009-07-15 01:25:43 +000071bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
72 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000073 // Test if the value is already loop-invariant.
74 if (isLoopInvariant(I))
75 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +000076 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +000077 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +000078 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +000079 return false;
David Majnemer654e1302015-07-31 17:58:14 +000080 // EH block instructions are immobile.
81 if (I->isEHPad())
Bill Wendlinga9ee09f2011-08-17 20:36:44 +000082 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +000083 // Determine the insertion point, unless one was given.
84 if (!InsertPt) {
85 BasicBlock *Preheader = getLoopPreheader();
86 // Without a preheader, hoisting is not feasible.
87 if (!Preheader)
88 return false;
89 InsertPt = Preheader->getTerminator();
90 }
91 // Don't hoist instructions with loop-variant operands.
Sanjay Patel960e5342016-01-15 00:08:10 +000092 for (Value *Operand : I->operands())
93 if (!makeLoopInvariant(Operand, Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +000094 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000095
Dan Gohman6f6d8642009-07-14 01:06:29 +000096 // Hoist.
97 I->moveBefore(InsertPt);
Igor Laevsky7310c682015-11-18 14:50:18 +000098
99 // There is possibility of hoisting this instruction above some arbitrary
100 // condition. Any metadata defined on it can be control dependent on this
101 // condition. Conservatively strip it here so that we don't give any wrong
102 // information to the optimizer.
103 I->dropUnknownNonDebugMetadata();
104
Dan Gohmanc43e4792009-07-15 01:25:43 +0000105 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000106 return true;
107}
108
Dan Gohman80a99422009-07-13 22:02:44 +0000109PHINode *Loop::getCanonicalInductionVariable() const {
110 BasicBlock *H = getHeader();
111
Craig Topper9f008862014-04-15 04:59:12 +0000112 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000113 pred_iterator PI = pred_begin(H);
114 assert(PI != pred_end(H) &&
Dan Gohman80a99422009-07-13 22:02:44 +0000115 "Loop must have at least one backedge!");
116 Backedge = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000117 if (PI == pred_end(H)) return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000118 Incoming = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000119 if (PI != pred_end(H)) return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000120
121 if (contains(Incoming)) {
122 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000123 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000124 std::swap(Incoming, Backedge);
125 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000126 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000127
128 // Loop over all of the PHI nodes, looking for a canonical indvar.
129 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
130 PHINode *PN = cast<PHINode>(I);
131 if (ConstantInt *CI =
132 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
133 if (CI->isNullValue())
134 if (Instruction *Inc =
135 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
136 if (Inc->getOpcode() == Instruction::Add &&
137 Inc->getOperand(0) == PN)
138 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
139 if (CI->equalsInt(1))
140 return PN;
141 }
Craig Topper9f008862014-04-15 04:59:12 +0000142 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000143}
144
Dan Gohman2734ebd2010-03-10 19:38:49 +0000145bool Loop::isLCSSAForm(DominatorTree &DT) const {
Sanjay Patel960e5342016-01-15 00:08:10 +0000146 for (BasicBlock *BB : this->blocks()) {
147 for (Instruction &I : *BB) {
Andrew Kaylor123048d2015-12-18 18:12:35 +0000148 // Tokens can't be used in PHI nodes and live-out tokens prevent loop
149 // optimizations, so for the purposes of considered LCSSA form, we
150 // can ignore them.
Sanjay Patel960e5342016-01-15 00:08:10 +0000151 if (I.getType()->isTokenTy())
Andrew Kaylor123048d2015-12-18 18:12:35 +0000152 continue;
153
Sanjay Patel960e5342016-01-15 00:08:10 +0000154 for (Use &U : I.uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000155 Instruction *UI = cast<Instruction>(U.getUser());
156 BasicBlock *UserBB = UI->getParent();
157 if (PHINode *P = dyn_cast<PHINode>(UI))
158 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000159
Dan Gohman93452ce2010-03-09 01:53:33 +0000160 // Check the current block, as a fast-path, before checking whether
161 // the use is anywhere in the loop. Most values are used in the same
162 // block they are defined in. Also, blocks not reachable from the
163 // entry are special; uses in them don't need to go through PHIs.
164 if (UserBB != BB &&
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000165 !contains(UserBB) &&
Dan Gohman2734ebd2010-03-10 19:38:49 +0000166 DT.isReachableFromEntry(UserBB))
Dan Gohman80a99422009-07-13 22:02:44 +0000167 return false;
168 }
Andrew Kaylor123048d2015-12-18 18:12:35 +0000169 }
Dan Gohman80a99422009-07-13 22:02:44 +0000170 }
171
172 return true;
173}
Dan Gohman1511f702009-07-16 16:16:23 +0000174
Sanjoy Das683bf072015-12-08 00:13:21 +0000175bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT) const {
176 if (!isLCSSAForm(DT))
177 return false;
178
179 return std::all_of(begin(), end(), [&](const Loop *L) {
180 return L->isRecursivelyLCSSAForm(DT);
181 });
182}
183
Dan Gohman1511f702009-07-16 16:16:23 +0000184bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000185 // Normal-form loops have a preheader, a single backedge, and all of their
186 // exits have all their predecessors inside the loop.
187 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
188}
189
Sanjay Patel784b5e32016-01-14 23:23:04 +0000190// Routines that reform the loop CFG and split edges often fail on indirectbr.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000191bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000192 // Return false if any loop blocks contain indirectbrs, or there are any calls
193 // to noduplicate functions.
Sanjay Patel960e5342016-01-15 00:08:10 +0000194 for (BasicBlock *BB : this->blocks()) {
195 if (isa<IndirectBrInst>(BB->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000196 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000197
Sanjay Patel960e5342016-01-15 00:08:10 +0000198 if (const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000199 if (II->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000200 return false;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000201 // Return false if any loop blocks contain invokes to EH-pads other than
202 // landingpads; we don't know how to split those edges yet.
203 auto *FirstNonPHI = II->getUnwindDest()->getFirstNonPHI();
204 if (FirstNonPHI->isEHPad() && !isa<LandingPadInst>(FirstNonPHI))
205 return false;
206 }
Sanjay Patel960e5342016-01-15 00:08:10 +0000207 for (Instruction &I : *BB) {
208 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000209 if (CI->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000210 return false;
211 }
Sanjay Patel960e5342016-01-15 00:08:10 +0000212 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
David Majnemerb611e3f2015-08-14 05:09:07 +0000213 return false;
James Molloy4f6fb952012-12-20 16:04:27 +0000214 }
Andrew Trick4442bfe2012-04-10 05:14:42 +0000215 }
216 return true;
217}
218
Paul Redmond5fdf8362013-05-28 20:00:34 +0000219MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000220 MDNode *LoopID = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000221 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000222 LoopID = getLoopLatch()->getTerminator()->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000223 } else {
224 // Go through each predecessor of the loop header and check the
225 // terminator for the metadata.
226 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000227 for (BasicBlock *BB : this->blocks()) {
228 TerminatorInst *TI = BB->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000229 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000230
231 // Check if this terminator branches to the loop header.
Sanjay Patel960e5342016-01-15 00:08:10 +0000232 for (BasicBlock *Successor : TI->successors()) {
233 if (Successor == H) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000234 MD = TI->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000235 break;
236 }
237 }
238 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000239 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000240
241 if (!LoopID)
242 LoopID = MD;
243 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000244 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000245 }
246 }
247 if (!LoopID || LoopID->getNumOperands() == 0 ||
248 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000249 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000250 return LoopID;
251}
252
253void Loop::setLoopID(MDNode *LoopID) const {
254 assert(LoopID && "Loop ID should not be null");
255 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
256 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
257
258 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000259 getLoopLatch()->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000260 return;
261 }
262
263 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000264 for (BasicBlock *BB : this->blocks()) {
265 TerminatorInst *TI = BB->getTerminator();
266 for (BasicBlock *Successor : TI->successors()) {
267 if (Successor == H)
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000268 TI->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000269 }
270 }
271}
272
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000273bool Loop::isAnnotatedParallel() const {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000274 MDNode *DesiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000275
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000276 if (!DesiredLoopIdMetadata)
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000277 return false;
278
279 // The loop branch contains the parallel loop metadata. In order to ensure
280 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
281 // dependencies (thus converted the loop back to a sequential loop), check
282 // that all the memory instructions in the loop contain parallelism metadata
283 // that point to the same unique "loop id metadata" the loop branch does.
Sanjay Patel960e5342016-01-15 00:08:10 +0000284 for (BasicBlock *BB : this->blocks()) {
285 for (Instruction &I : *BB) {
286 if (!I.mayReadOrWriteMemory())
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000287 continue;
288
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000289 // The memory instruction can refer to the loop identifier metadata
290 // directly or indirectly through another list metadata (in case of
291 // nested parallel loops). The loop identifier metadata refers to
292 // itself so we can check both cases with the same routine.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000293 MDNode *LoopIdMD =
Sanjay Patel960e5342016-01-15 00:08:10 +0000294 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000295
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000296 if (!LoopIdMD)
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000297 return false;
298
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000299 bool LoopIdMDFound = false;
300 for (const MDOperand &MDOp : LoopIdMD->operands()) {
301 if (MDOp == DesiredLoopIdMetadata) {
302 LoopIdMDFound = true;
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000303 break;
304 }
305 }
306
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000307 if (!LoopIdMDFound)
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000308 return false;
309 }
310 }
311 return true;
312}
313
Dan Gohmane3a17062009-11-05 19:21:41 +0000314bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000315 // Each predecessor of each exit block of a normal loop is contained
316 // within the loop.
317 SmallVector<BasicBlock *, 4> ExitBlocks;
318 getExitBlocks(ExitBlocks);
Sanjay Patel960e5342016-01-15 00:08:10 +0000319 for (BasicBlock *BB : ExitBlocks)
320 for (BasicBlock *Predecessor : predecessors(BB))
321 if (!contains(Predecessor))
Dan Gohman1511f702009-07-16 16:16:23 +0000322 return false;
323 // All the requirements are met.
324 return true;
325}
326
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000327void
328Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000329 assert(hasDedicatedExits() &&
330 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000331
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000332 SmallVector<BasicBlock *, 32> SwitchExitBlocks;
Sanjay Patel960e5342016-01-15 00:08:10 +0000333 for (BasicBlock *BB : this->blocks()) {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000334 SwitchExitBlocks.clear();
Sanjay Patel960e5342016-01-15 00:08:10 +0000335 for (BasicBlock *Successor : successors(BB)) {
336 // If block is inside the loop then it is not an exit block.
337 if (contains(Successor))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000338 continue;
339
Sanjay Patel960e5342016-01-15 00:08:10 +0000340 pred_iterator PI = pred_begin(Successor);
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000341 BasicBlock *FirstPred = *PI;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000342
343 // If current basic block is this exit block's first predecessor
344 // then only insert exit block in to the output ExitBlocks vector.
345 // This ensures that same exit block is not inserted twice into
346 // ExitBlocks vector.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000347 if (BB != FirstPred)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000348 continue;
349
350 // If a terminator has more then two successors, for example SwitchInst,
351 // then it is possible that there are multiple edges from current block
352 // to one exit block.
Sanjay Patel960e5342016-01-15 00:08:10 +0000353 if (std::distance(succ_begin(BB), succ_end(BB)) <= 2) {
354 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000355 continue;
356 }
357
358 // In case of multiple edges from current block to exit block, collect
359 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
360 // duplicate edges.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000361 if (std::find(SwitchExitBlocks.begin(), SwitchExitBlocks.end(), Successor)
362 == SwitchExitBlocks.end()) {
363 SwitchExitBlocks.push_back(Successor);
Sanjay Patel960e5342016-01-15 00:08:10 +0000364 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000365 }
366 }
367 }
368}
369
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000370BasicBlock *Loop::getUniqueExitBlock() const {
371 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
372 getUniqueExitBlocks(UniqueExitBlocks);
373 if (UniqueExitBlocks.size() == 1)
374 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000375 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000376}
377
Manman Ren49d684e2012-09-12 05:06:18 +0000378#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +0000379LLVM_DUMP_METHOD void Loop::dump() const {
Dan Gohmanc3f21372010-01-05 21:08:02 +0000380 print(dbgs());
381}
Manman Renc3366cc2012-09-06 19:55:56 +0000382#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000383
Chris Lattner26750072002-07-27 01:12:17 +0000384//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000385// UnloopUpdater implementation
386//
387
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000388namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000389/// Find the new parent loop for all blocks within the "unloop" whose last
390/// backedges has just been removed.
391class UnloopUpdater {
392 Loop *Unloop;
393 LoopInfo *LI;
394
395 LoopBlocksDFS DFS;
396
397 // Map unloop's immediate subloops to their nearest reachable parents. Nested
398 // loops within these subloops will not change parents. However, an immediate
399 // subloop's new parent will be the nearest loop reachable from either its own
400 // exits *or* any of its nested loop's exits.
401 DenseMap<Loop*, Loop*> SubloopParents;
402
403 // Flag the presence of an irreducible backedge whose destination is a block
404 // directly contained by the original unloop.
405 bool FoundIB;
406
407public:
408 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
409 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
410
411 void updateBlockParents();
412
Andrew Trickc12c30a2011-08-11 20:27:32 +0000413 void removeBlocksFromAncestors();
414
Andrew Trickd3530b92011-08-10 23:22:57 +0000415 void updateSubloopParents();
416
417protected:
418 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
419};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000420} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000421
Sanjay Patel784b5e32016-01-14 23:23:04 +0000422/// Update the parent loop for all blocks that are directly contained within the
423/// original "unloop".
Andrew Trickd3530b92011-08-10 23:22:57 +0000424void UnloopUpdater::updateBlockParents() {
425 if (Unloop->getNumBlocks()) {
426 // Perform a post order CFG traversal of all blocks within this loop,
427 // propagating the nearest loop from sucessors to predecessors.
428 LoopBlocksTraversal Traversal(DFS, LI);
429 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
430 POE = Traversal.end(); POI != POE; ++POI) {
431
432 Loop *L = LI->getLoopFor(*POI);
433 Loop *NL = getNearestLoop(*POI, L);
434
435 if (NL != L) {
436 // For reducible loops, NL is now an ancestor of Unloop.
437 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
438 "uninitialized successor");
439 LI->changeLoopFor(*POI, NL);
440 }
441 else {
442 // Or the current block is part of a subloop, in which case its parent
443 // is unchanged.
444 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
445 }
446 }
447 }
448 // Each irreducible loop within the unloop induces a round of iteration using
449 // the DFS result cached by Traversal.
450 bool Changed = FoundIB;
451 for (unsigned NIters = 0; Changed; ++NIters) {
452 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
453
454 // Iterate over the postorder list of blocks, propagating the nearest loop
455 // from successors to predecessors as before.
456 Changed = false;
457 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
458 POE = DFS.endPostorder(); POI != POE; ++POI) {
459
460 Loop *L = LI->getLoopFor(*POI);
461 Loop *NL = getNearestLoop(*POI, L);
462 if (NL != L) {
463 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
464 "uninitialized successor");
465 LI->changeLoopFor(*POI, NL);
466 Changed = true;
467 }
468 }
469 }
470}
471
Sanjay Patel784b5e32016-01-14 23:23:04 +0000472/// Remove unloop's blocks from all ancestors below their new parents.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000473void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000474 // Remove all unloop's blocks (including those in nested subloops) from
475 // ancestors below the new parent loop.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000476 for (Loop::block_iterator BI = Unloop->block_begin(),
477 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000478 Loop *OuterParent = LI->getLoopFor(*BI);
479 if (Unloop->contains(OuterParent)) {
480 while (OuterParent->getParentLoop() != Unloop)
481 OuterParent = OuterParent->getParentLoop();
482 OuterParent = SubloopParents[OuterParent];
483 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000484 // Remove blocks from former Ancestors except Unloop itself which will be
485 // deleted.
Andrew Trick6b4d5782011-11-18 03:42:41 +0000486 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000487 OldParent = OldParent->getParentLoop()) {
488 assert(OldParent && "new loop is not an ancestor of the original");
489 OldParent->removeBlockFromLoop(*BI);
490 }
491 }
492}
493
Sanjay Patel784b5e32016-01-14 23:23:04 +0000494/// Update the parent loop for all subloops directly nested within unloop.
Andrew Trickd3530b92011-08-10 23:22:57 +0000495void UnloopUpdater::updateSubloopParents() {
496 while (!Unloop->empty()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000497 Loop *Subloop = *std::prev(Unloop->end());
498 Unloop->removeChildLoop(std::prev(Unloop->end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000499
500 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000501 if (Loop *Parent = SubloopParents[Subloop])
502 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000503 else
504 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000505 }
506}
507
Sanjay Patel784b5e32016-01-14 23:23:04 +0000508/// Return the nearest parent loop among this block's successors. If a successor
509/// is a subloop header, consider its parent to be the nearest parent of the
510/// subloop's exits.
Andrew Trickd3530b92011-08-10 23:22:57 +0000511///
512/// For subloop blocks, simply update SubloopParents and return NULL.
513Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
514
Andrew Trick266ab102011-08-11 17:54:58 +0000515 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
516 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000517 Loop *NearLoop = BBLoop;
518
Craig Topper9f008862014-04-15 04:59:12 +0000519 Loop *Subloop = nullptr;
Andrew Trickd3530b92011-08-10 23:22:57 +0000520 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
521 Subloop = NearLoop;
522 // Find the subloop ancestor that is directly contained within Unloop.
523 while (Subloop->getParentLoop() != Unloop) {
524 Subloop = Subloop->getParentLoop();
525 assert(Subloop && "subloop is not an ancestor of the original loop");
526 }
527 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000528 NearLoop =
529 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000530 }
531
532 succ_iterator I = succ_begin(BB), E = succ_end(BB);
533 if (I == E) {
534 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000535 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000536 }
537 for (; I != E; ++I) {
538 if (*I == BB)
539 continue; // self loops are uninteresting
540
541 Loop *L = LI->getLoopFor(*I);
542 if (L == Unloop) {
543 // This successor has not been processed. This path must lead to an
544 // irreducible backedge.
545 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
546 FoundIB = true;
547 }
548 if (L != Unloop && Unloop->contains(L)) {
549 // Successor is in a subloop.
550 if (Subloop)
551 continue; // Branching within subloops. Ignore it.
552
553 // BB branches from the original into a subloop header.
554 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
555
556 // Get the current nearest parent of the Subloop's exits.
557 L = SubloopParents[L];
558 // L could be Unloop if the only exit was an irreducible backedge.
559 }
560 if (L == Unloop) {
561 continue;
562 }
563 // Handle critical edges from Unloop into a sibling loop.
564 if (L && !L->contains(Unloop)) {
565 L = L->getParentLoop();
566 }
567 // Remember the nearest parent loop among successors or subloop exits.
568 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
569 NearLoop = L;
570 }
571 if (Subloop) {
572 SubloopParents[Subloop] = NearLoop;
573 return BBLoop;
574 }
575 return NearLoop;
576}
577
Cong Hou9b4f6b22015-07-16 23:23:35 +0000578LoopInfo::LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree) {
579 analyze(DomTree);
580}
581
Justin Bognere9fb228d2016-01-08 19:08:53 +0000582void LoopInfo::markAsRemoved(Loop *Unloop) {
583 assert(!Unloop->isInvalid() && "Loop has already been removed");
584 Unloop->invalidate();
585 RemovedLoops.push_back(Unloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000586
587 // First handle the special case of no parent loop to simplify the algorithm.
588 if (!Unloop->getParentLoop()) {
589 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
590 for (Loop::block_iterator I = Unloop->block_begin(),
Chandler Carruth691addc2015-01-18 01:25:51 +0000591 E = Unloop->block_end();
592 I != E; ++I) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000593
594 // Don't reparent blocks in subloops.
595 if (getLoopFor(*I) != Unloop)
596 continue;
597
598 // Blocks no longer have a parent but are still referenced by Unloop until
599 // the Unloop object is deleted.
Chandler Carruth691addc2015-01-18 01:25:51 +0000600 changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000601 }
602
603 // Remove the loop from the top-level LoopInfo object.
Chandler Carruth691addc2015-01-18 01:25:51 +0000604 for (iterator I = begin();; ++I) {
605 assert(I != end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000606 if (*I == Unloop) {
Chandler Carruth691addc2015-01-18 01:25:51 +0000607 removeLoop(I);
Andrew Trickd3530b92011-08-10 23:22:57 +0000608 break;
609 }
610 }
611
612 // Move all of the subloops to the top-level.
613 while (!Unloop->empty())
Chandler Carruth691addc2015-01-18 01:25:51 +0000614 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000615
616 return;
617 }
618
619 // Update the parent loop for all blocks within the loop. Blocks within
620 // subloops will not change parents.
621 UnloopUpdater Updater(Unloop, this);
622 Updater.updateBlockParents();
623
Andrew Trickc12c30a2011-08-11 20:27:32 +0000624 // Remove blocks from former ancestor loops.
625 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000626
627 // Add direct subloops as children in their new parent loop.
628 Updater.updateSubloopParents();
629
630 // Remove unloop from its parent loop.
631 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000632 for (Loop::iterator I = ParentLoop->begin();; ++I) {
633 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000634 if (*I == Unloop) {
635 ParentLoop->removeChildLoop(I);
636 break;
637 }
638 }
639}
640
Chandler Carruthb4faf132016-03-11 10:22:49 +0000641char LoopAnalysis::PassID;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +0000642
Chandler Carruthb47f8012016-03-11 11:05:24 +0000643LoopInfo LoopAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000644 // FIXME: Currently we create a LoopInfo from scratch for every function.
645 // This may prove to be too wasteful due to deallocating and re-allocating
646 // memory each time for the underlying map and vector datastructures. At some
647 // point it may prove worthwhile to use a freelist and recycle LoopInfo
648 // objects. I don't want to add that kind of complexity until the scope of
649 // the problem is better understood.
650 LoopInfo LI;
Chandler Carruthb47f8012016-03-11 11:05:24 +0000651 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
Richard Trieu6ae37962015-04-30 23:07:00 +0000652 return LI;
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000653}
654
655PreservedAnalyses LoopPrinterPass::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +0000656 AnalysisManager<Function> &AM) {
657 AM.getResult<LoopAnalysis>(F).print(OS);
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000658 return PreservedAnalyses::all();
659}
660
Justin Bognerc2b98f02015-11-04 22:24:08 +0000661PrintLoopPass::PrintLoopPass() : OS(dbgs()) {}
662PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
663 : OS(OS), Banner(Banner) {}
664
665PreservedAnalyses PrintLoopPass::run(Loop &L) {
666 OS << Banner;
667 for (auto *Block : L.blocks())
668 if (Block)
669 Block->print(OS);
670 else
671 OS << "Printing <null> block";
672 return PreservedAnalyses::all();
673}
674
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000675//===----------------------------------------------------------------------===//
676// LoopInfo implementation
677//
678
679char LoopInfoWrapperPass::ID = 0;
680INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
681 true, true)
682INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
683INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
684 true, true)
685
686bool LoopInfoWrapperPass::runOnFunction(Function &) {
687 releaseMemory();
Cong Houd2c1d912015-07-16 18:23:57 +0000688 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000689 return false;
690}
691
692void LoopInfoWrapperPass::verifyAnalysis() const {
693 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
694 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman4dbb3012009-09-28 00:27:48 +0000695 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000696 // checking by default, LoopPass has been taught to call verifyLoop manually
697 // during loop pass sequences.
Chandler Carruth691addc2015-01-18 01:25:51 +0000698 if (VerifyLoopInfo)
699 LI.verify();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000700}
701
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000702void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000703 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000704 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000705}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000706
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000707void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Chandler Carruth691addc2015-01-18 01:25:51 +0000708 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000709}
710
Andrew Trick78b40c32011-08-10 01:59:05 +0000711//===----------------------------------------------------------------------===//
712// LoopBlocksDFS implementation
713//
714
715/// Traverse the loop blocks and store the DFS result.
716/// Useful for clients that just want the final DFS result and don't need to
717/// visit blocks during the initial traversal.
718void LoopBlocksDFS::perform(LoopInfo *LI) {
719 LoopBlocksTraversal Traversal(*this, LI);
720 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
721 POE = Traversal.end(); POI != POE; ++POI) ;
722}