blob: 1ada07c5f7013dbc7d2369544a8852fbe035b65c [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
Pete Cooper016daa62015-05-13 01:12:06 +000057bool Loop::isLoopInvariant(const Value *V) const {
58 if (const Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000059 return !contains(I);
Dan Gohman80a99422009-07-13 22:02:44 +000060 return true; // All non-instructions are loop invariant
61}
62
Pete Cooper016daa62015-05-13 01:12:06 +000063bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
Pete Coopera264dc02015-05-13 22:19:13 +000064 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
Dan Gohman6f6d8642009-07-14 01:06:29 +000065}
66
Dan Gohmanc43e4792009-07-15 01:25:43 +000067bool Loop::makeLoopInvariant(Value *V, bool &Changed,
68 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000069 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000070 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman6f6d8642009-07-14 01:06:29 +000071 return true; // All non-instructions are loop-invariant.
72}
73
Dan Gohmanc43e4792009-07-15 01:25:43 +000074bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
75 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000076 // Test if the value is already loop-invariant.
77 if (isLoopInvariant(I))
78 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +000079 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +000080 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +000081 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +000082 return false;
David Majnemer654e1302015-07-31 17:58:14 +000083 // EH block instructions are immobile.
84 if (I->isEHPad())
Bill Wendlinga9ee09f2011-08-17 20:36:44 +000085 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +000086 // Determine the insertion point, unless one was given.
87 if (!InsertPt) {
88 BasicBlock *Preheader = getLoopPreheader();
89 // Without a preheader, hoisting is not feasible.
90 if (!Preheader)
91 return false;
92 InsertPt = Preheader->getTerminator();
93 }
94 // Don't hoist instructions with loop-variant operands.
Sanjay Patel960e5342016-01-15 00:08:10 +000095 for (Value *Operand : I->operands())
96 if (!makeLoopInvariant(Operand, Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +000097 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000098
Dan Gohman6f6d8642009-07-14 01:06:29 +000099 // Hoist.
100 I->moveBefore(InsertPt);
Igor Laevsky7310c682015-11-18 14:50:18 +0000101
102 // There is possibility of hoisting this instruction above some arbitrary
103 // condition. Any metadata defined on it can be control dependent on this
104 // condition. Conservatively strip it here so that we don't give any wrong
105 // information to the optimizer.
106 I->dropUnknownNonDebugMetadata();
107
Dan Gohmanc43e4792009-07-15 01:25:43 +0000108 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000109 return true;
110}
111
Dan Gohman80a99422009-07-13 22:02:44 +0000112PHINode *Loop::getCanonicalInductionVariable() const {
113 BasicBlock *H = getHeader();
114
Craig Topper9f008862014-04-15 04:59:12 +0000115 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000116 pred_iterator PI = pred_begin(H);
117 assert(PI != pred_end(H) &&
Dan Gohman80a99422009-07-13 22:02:44 +0000118 "Loop must have at least one backedge!");
119 Backedge = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000120 if (PI == pred_end(H)) return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000121 Incoming = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000122 if (PI != pred_end(H)) return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000123
124 if (contains(Incoming)) {
125 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000126 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000127 std::swap(Incoming, Backedge);
128 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000129 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000130
131 // Loop over all of the PHI nodes, looking for a canonical indvar.
132 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
133 PHINode *PN = cast<PHINode>(I);
134 if (ConstantInt *CI =
135 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
136 if (CI->isNullValue())
137 if (Instruction *Inc =
138 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
139 if (Inc->getOpcode() == Instruction::Add &&
140 Inc->getOperand(0) == PN)
141 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
142 if (CI->equalsInt(1))
143 return PN;
144 }
Craig Topper9f008862014-04-15 04:59:12 +0000145 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000146}
147
Dan Gohman2734ebd2010-03-10 19:38:49 +0000148bool Loop::isLCSSAForm(DominatorTree &DT) const {
Sanjay Patel960e5342016-01-15 00:08:10 +0000149 for (BasicBlock *BB : this->blocks()) {
150 for (Instruction &I : *BB) {
Andrew Kaylor123048d2015-12-18 18:12:35 +0000151 // Tokens can't be used in PHI nodes and live-out tokens prevent loop
152 // optimizations, so for the purposes of considered LCSSA form, we
153 // can ignore them.
Sanjay Patel960e5342016-01-15 00:08:10 +0000154 if (I.getType()->isTokenTy())
Andrew Kaylor123048d2015-12-18 18:12:35 +0000155 continue;
156
Sanjay Patel960e5342016-01-15 00:08:10 +0000157 for (Use &U : I.uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000158 Instruction *UI = cast<Instruction>(U.getUser());
159 BasicBlock *UserBB = UI->getParent();
160 if (PHINode *P = dyn_cast<PHINode>(UI))
161 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000162
Dan Gohman93452ce2010-03-09 01:53:33 +0000163 // Check the current block, as a fast-path, before checking whether
164 // the use is anywhere in the loop. Most values are used in the same
165 // block they are defined in. Also, blocks not reachable from the
166 // entry are special; uses in them don't need to go through PHIs.
167 if (UserBB != BB &&
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000168 !contains(UserBB) &&
Dan Gohman2734ebd2010-03-10 19:38:49 +0000169 DT.isReachableFromEntry(UserBB))
Dan Gohman80a99422009-07-13 22:02:44 +0000170 return false;
171 }
Andrew Kaylor123048d2015-12-18 18:12:35 +0000172 }
Dan Gohman80a99422009-07-13 22:02:44 +0000173 }
174
175 return true;
176}
Dan Gohman1511f702009-07-16 16:16:23 +0000177
Sanjoy Das683bf072015-12-08 00:13:21 +0000178bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT) const {
179 if (!isLCSSAForm(DT))
180 return false;
181
182 return std::all_of(begin(), end(), [&](const Loop *L) {
183 return L->isRecursivelyLCSSAForm(DT);
184 });
185}
186
Dan Gohman1511f702009-07-16 16:16:23 +0000187bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000188 // Normal-form loops have a preheader, a single backedge, and all of their
189 // exits have all their predecessors inside the loop.
190 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
191}
192
Sanjay Patel784b5e32016-01-14 23:23:04 +0000193// Routines that reform the loop CFG and split edges often fail on indirectbr.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000194bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000195 // Return false if any loop blocks contain indirectbrs, or there are any calls
196 // to noduplicate functions.
Sanjay Patel960e5342016-01-15 00:08:10 +0000197 for (BasicBlock *BB : this->blocks()) {
198 if (isa<IndirectBrInst>(BB->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000199 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000200
Sanjay Patel960e5342016-01-15 00:08:10 +0000201 if (const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000202 if (II->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000203 return false;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000204 // Return false if any loop blocks contain invokes to EH-pads other than
205 // landingpads; we don't know how to split those edges yet.
206 auto *FirstNonPHI = II->getUnwindDest()->getFirstNonPHI();
207 if (FirstNonPHI->isEHPad() && !isa<LandingPadInst>(FirstNonPHI))
208 return false;
209 }
Sanjay Patel960e5342016-01-15 00:08:10 +0000210 for (Instruction &I : *BB) {
211 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000212 if (CI->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000213 return false;
214 }
Sanjay Patel960e5342016-01-15 00:08:10 +0000215 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
David Majnemerb611e3f2015-08-14 05:09:07 +0000216 return false;
James Molloy4f6fb952012-12-20 16:04:27 +0000217 }
Andrew Trick4442bfe2012-04-10 05:14:42 +0000218 }
219 return true;
220}
221
Paul Redmond5fdf8362013-05-28 20:00:34 +0000222MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000223 MDNode *LoopID = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000224 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000225 LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000226 } else {
227 // Go through each predecessor of the loop header and check the
228 // terminator for the metadata.
229 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000230 for (BasicBlock *BB : this->blocks()) {
231 TerminatorInst *TI = BB->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000232 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000233
234 // Check if this terminator branches to the loop header.
Sanjay Patel960e5342016-01-15 00:08:10 +0000235 for (BasicBlock *Successor : TI->successors()) {
236 if (Successor == H) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000237 MD = TI->getMetadata(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000238 break;
239 }
240 }
241 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000242 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000243
244 if (!LoopID)
245 LoopID = MD;
246 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000247 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000248 }
249 }
250 if (!LoopID || LoopID->getNumOperands() == 0 ||
251 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000252 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000253 return LoopID;
254}
255
256void Loop::setLoopID(MDNode *LoopID) const {
257 assert(LoopID && "Loop ID should not be null");
258 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
259 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
260
261 if (isLoopSimplifyForm()) {
262 getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
263 return;
264 }
265
266 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000267 for (BasicBlock *BB : this->blocks()) {
268 TerminatorInst *TI = BB->getTerminator();
269 for (BasicBlock *Successor : TI->successors()) {
270 if (Successor == H)
Paul Redmond5fdf8362013-05-28 20:00:34 +0000271 TI->setMetadata(LoopMDName, LoopID);
272 }
273 }
274}
275
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000276bool Loop::isAnnotatedParallel() const {
Paul Redmond5fdf8362013-05-28 20:00:34 +0000277 MDNode *desiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000278
279 if (!desiredLoopIdMetadata)
280 return false;
281
282 // The loop branch contains the parallel loop metadata. In order to ensure
283 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
284 // dependencies (thus converted the loop back to a sequential loop), check
285 // that all the memory instructions in the loop contain parallelism metadata
286 // that point to the same unique "loop id metadata" the loop branch does.
Sanjay Patel960e5342016-01-15 00:08:10 +0000287 for (BasicBlock *BB : this->blocks()) {
288 for (Instruction &I : *BB) {
289 if (!I.mayReadOrWriteMemory())
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000290 continue;
291
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000292 // The memory instruction can refer to the loop identifier metadata
293 // directly or indirectly through another list metadata (in case of
294 // nested parallel loops). The loop identifier metadata refers to
295 // itself so we can check both cases with the same routine.
Philip Reames5a3f5f72014-10-21 00:13:20 +0000296 MDNode *loopIdMD =
Sanjay Patel960e5342016-01-15 00:08:10 +0000297 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000298
299 if (!loopIdMD)
300 return false;
301
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000302 bool loopIdMDFound = false;
Sanjay Patel960e5342016-01-15 00:08:10 +0000303 for (const MDOperand &MDOp : loopIdMD->operands()) {
304 if (MDOp == desiredLoopIdMetadata) {
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000305 loopIdMDFound = true;
306 break;
307 }
308 }
309
310 if (!loopIdMDFound)
311 return false;
312 }
313 }
314 return true;
315}
316
Dan Gohmane3a17062009-11-05 19:21:41 +0000317bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000318 // Each predecessor of each exit block of a normal loop is contained
319 // within the loop.
320 SmallVector<BasicBlock *, 4> ExitBlocks;
321 getExitBlocks(ExitBlocks);
Sanjay Patel960e5342016-01-15 00:08:10 +0000322 for (BasicBlock *BB : ExitBlocks)
323 for (BasicBlock *Predecessor : predecessors(BB))
324 if (!contains(Predecessor))
Dan Gohman1511f702009-07-16 16:16:23 +0000325 return false;
326 // All the requirements are met.
327 return true;
328}
329
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000330void
331Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000332 assert(hasDedicatedExits() &&
333 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000334
Dan Gohmaned8f3202009-09-03 20:36:13 +0000335 SmallVector<BasicBlock *, 32> switchExitBlocks;
Sanjay Patel960e5342016-01-15 00:08:10 +0000336 for (BasicBlock *BB : this->blocks()) {
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000337 switchExitBlocks.clear();
Sanjay Patel960e5342016-01-15 00:08:10 +0000338 for (BasicBlock *Successor : successors(BB)) {
339 // If block is inside the loop then it is not an exit block.
340 if (contains(Successor))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000341 continue;
342
Sanjay Patel960e5342016-01-15 00:08:10 +0000343 pred_iterator PI = pred_begin(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000344 BasicBlock *firstPred = *PI;
345
346 // If current basic block is this exit block's first predecessor
347 // then only insert exit block in to the output ExitBlocks vector.
348 // This ensures that same exit block is not inserted twice into
349 // ExitBlocks vector.
Sanjay Patel960e5342016-01-15 00:08:10 +0000350 if (BB != firstPred)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000351 continue;
352
353 // If a terminator has more then two successors, for example SwitchInst,
354 // then it is possible that there are multiple edges from current block
355 // to one exit block.
Sanjay Patel960e5342016-01-15 00:08:10 +0000356 if (std::distance(succ_begin(BB), succ_end(BB)) <= 2) {
357 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000358 continue;
359 }
360
361 // In case of multiple edges from current block to exit block, collect
362 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
363 // duplicate edges.
Sanjay Patel960e5342016-01-15 00:08:10 +0000364 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), Successor)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000365 == switchExitBlocks.end()) {
Sanjay Patel960e5342016-01-15 00:08:10 +0000366 switchExitBlocks.push_back(Successor);
367 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000368 }
369 }
370 }
371}
372
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000373BasicBlock *Loop::getUniqueExitBlock() const {
374 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
375 getUniqueExitBlocks(UniqueExitBlocks);
376 if (UniqueExitBlocks.size() == 1)
377 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000378 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000379}
380
Manman Ren49d684e2012-09-12 05:06:18 +0000381#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohmanc3f21372010-01-05 21:08:02 +0000382void Loop::dump() const {
383 print(dbgs());
384}
Manman Renc3366cc2012-09-06 19:55:56 +0000385#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000386
Chris Lattner26750072002-07-27 01:12:17 +0000387//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000388// UnloopUpdater implementation
389//
390
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000391namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000392/// Find the new parent loop for all blocks within the "unloop" whose last
393/// backedges has just been removed.
394class UnloopUpdater {
395 Loop *Unloop;
396 LoopInfo *LI;
397
398 LoopBlocksDFS DFS;
399
400 // Map unloop's immediate subloops to their nearest reachable parents. Nested
401 // loops within these subloops will not change parents. However, an immediate
402 // subloop's new parent will be the nearest loop reachable from either its own
403 // exits *or* any of its nested loop's exits.
404 DenseMap<Loop*, Loop*> SubloopParents;
405
406 // Flag the presence of an irreducible backedge whose destination is a block
407 // directly contained by the original unloop.
408 bool FoundIB;
409
410public:
411 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
412 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
413
414 void updateBlockParents();
415
Andrew Trickc12c30a2011-08-11 20:27:32 +0000416 void removeBlocksFromAncestors();
417
Andrew Trickd3530b92011-08-10 23:22:57 +0000418 void updateSubloopParents();
419
420protected:
421 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
422};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000423} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000424
Sanjay Patel784b5e32016-01-14 23:23:04 +0000425/// Update the parent loop for all blocks that are directly contained within the
426/// original "unloop".
Andrew Trickd3530b92011-08-10 23:22:57 +0000427void UnloopUpdater::updateBlockParents() {
428 if (Unloop->getNumBlocks()) {
429 // Perform a post order CFG traversal of all blocks within this loop,
430 // propagating the nearest loop from sucessors to predecessors.
431 LoopBlocksTraversal Traversal(DFS, LI);
432 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
433 POE = Traversal.end(); POI != POE; ++POI) {
434
435 Loop *L = LI->getLoopFor(*POI);
436 Loop *NL = getNearestLoop(*POI, L);
437
438 if (NL != L) {
439 // For reducible loops, NL is now an ancestor of Unloop.
440 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
441 "uninitialized successor");
442 LI->changeLoopFor(*POI, NL);
443 }
444 else {
445 // Or the current block is part of a subloop, in which case its parent
446 // is unchanged.
447 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
448 }
449 }
450 }
451 // Each irreducible loop within the unloop induces a round of iteration using
452 // the DFS result cached by Traversal.
453 bool Changed = FoundIB;
454 for (unsigned NIters = 0; Changed; ++NIters) {
455 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
456
457 // Iterate over the postorder list of blocks, propagating the nearest loop
458 // from successors to predecessors as before.
459 Changed = false;
460 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
461 POE = DFS.endPostorder(); POI != POE; ++POI) {
462
463 Loop *L = LI->getLoopFor(*POI);
464 Loop *NL = getNearestLoop(*POI, L);
465 if (NL != L) {
466 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
467 "uninitialized successor");
468 LI->changeLoopFor(*POI, NL);
469 Changed = true;
470 }
471 }
472 }
473}
474
Sanjay Patel784b5e32016-01-14 23:23:04 +0000475/// Remove unloop's blocks from all ancestors below their new parents.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000476void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000477 // Remove all unloop's blocks (including those in nested subloops) from
478 // ancestors below the new parent loop.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000479 for (Loop::block_iterator BI = Unloop->block_begin(),
480 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000481 Loop *OuterParent = LI->getLoopFor(*BI);
482 if (Unloop->contains(OuterParent)) {
483 while (OuterParent->getParentLoop() != Unloop)
484 OuterParent = OuterParent->getParentLoop();
485 OuterParent = SubloopParents[OuterParent];
486 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000487 // Remove blocks from former Ancestors except Unloop itself which will be
488 // deleted.
Andrew Trick6b4d5782011-11-18 03:42:41 +0000489 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000490 OldParent = OldParent->getParentLoop()) {
491 assert(OldParent && "new loop is not an ancestor of the original");
492 OldParent->removeBlockFromLoop(*BI);
493 }
494 }
495}
496
Sanjay Patel784b5e32016-01-14 23:23:04 +0000497/// Update the parent loop for all subloops directly nested within unloop.
Andrew Trickd3530b92011-08-10 23:22:57 +0000498void UnloopUpdater::updateSubloopParents() {
499 while (!Unloop->empty()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000500 Loop *Subloop = *std::prev(Unloop->end());
501 Unloop->removeChildLoop(std::prev(Unloop->end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000502
503 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000504 if (Loop *Parent = SubloopParents[Subloop])
505 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000506 else
507 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000508 }
509}
510
Sanjay Patel784b5e32016-01-14 23:23:04 +0000511/// Return the nearest parent loop among this block's successors. If a successor
512/// is a subloop header, consider its parent to be the nearest parent of the
513/// subloop's exits.
Andrew Trickd3530b92011-08-10 23:22:57 +0000514///
515/// For subloop blocks, simply update SubloopParents and return NULL.
516Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
517
Andrew Trick266ab102011-08-11 17:54:58 +0000518 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
519 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000520 Loop *NearLoop = BBLoop;
521
Craig Topper9f008862014-04-15 04:59:12 +0000522 Loop *Subloop = nullptr;
Andrew Trickd3530b92011-08-10 23:22:57 +0000523 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
524 Subloop = NearLoop;
525 // Find the subloop ancestor that is directly contained within Unloop.
526 while (Subloop->getParentLoop() != Unloop) {
527 Subloop = Subloop->getParentLoop();
528 assert(Subloop && "subloop is not an ancestor of the original loop");
529 }
530 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000531 NearLoop =
532 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000533 }
534
535 succ_iterator I = succ_begin(BB), E = succ_end(BB);
536 if (I == E) {
537 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000538 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000539 }
540 for (; I != E; ++I) {
541 if (*I == BB)
542 continue; // self loops are uninteresting
543
544 Loop *L = LI->getLoopFor(*I);
545 if (L == Unloop) {
546 // This successor has not been processed. This path must lead to an
547 // irreducible backedge.
548 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
549 FoundIB = true;
550 }
551 if (L != Unloop && Unloop->contains(L)) {
552 // Successor is in a subloop.
553 if (Subloop)
554 continue; // Branching within subloops. Ignore it.
555
556 // BB branches from the original into a subloop header.
557 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
558
559 // Get the current nearest parent of the Subloop's exits.
560 L = SubloopParents[L];
561 // L could be Unloop if the only exit was an irreducible backedge.
562 }
563 if (L == Unloop) {
564 continue;
565 }
566 // Handle critical edges from Unloop into a sibling loop.
567 if (L && !L->contains(Unloop)) {
568 L = L->getParentLoop();
569 }
570 // Remember the nearest parent loop among successors or subloop exits.
571 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
572 NearLoop = L;
573 }
574 if (Subloop) {
575 SubloopParents[Subloop] = NearLoop;
576 return BBLoop;
577 }
578 return NearLoop;
579}
580
Cong Hou9b4f6b22015-07-16 23:23:35 +0000581LoopInfo::LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree) {
582 analyze(DomTree);
583}
584
Justin Bognere9fb228d2016-01-08 19:08:53 +0000585void LoopInfo::markAsRemoved(Loop *Unloop) {
586 assert(!Unloop->isInvalid() && "Loop has already been removed");
587 Unloop->invalidate();
588 RemovedLoops.push_back(Unloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000589
590 // First handle the special case of no parent loop to simplify the algorithm.
591 if (!Unloop->getParentLoop()) {
592 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
593 for (Loop::block_iterator I = Unloop->block_begin(),
Chandler Carruth691addc2015-01-18 01:25:51 +0000594 E = Unloop->block_end();
595 I != E; ++I) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000596
597 // Don't reparent blocks in subloops.
598 if (getLoopFor(*I) != Unloop)
599 continue;
600
601 // Blocks no longer have a parent but are still referenced by Unloop until
602 // the Unloop object is deleted.
Chandler Carruth691addc2015-01-18 01:25:51 +0000603 changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000604 }
605
606 // Remove the loop from the top-level LoopInfo object.
Chandler Carruth691addc2015-01-18 01:25:51 +0000607 for (iterator I = begin();; ++I) {
608 assert(I != end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000609 if (*I == Unloop) {
Chandler Carruth691addc2015-01-18 01:25:51 +0000610 removeLoop(I);
Andrew Trickd3530b92011-08-10 23:22:57 +0000611 break;
612 }
613 }
614
615 // Move all of the subloops to the top-level.
616 while (!Unloop->empty())
Chandler Carruth691addc2015-01-18 01:25:51 +0000617 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000618
619 return;
620 }
621
622 // Update the parent loop for all blocks within the loop. Blocks within
623 // subloops will not change parents.
624 UnloopUpdater Updater(Unloop, this);
625 Updater.updateBlockParents();
626
Andrew Trickc12c30a2011-08-11 20:27:32 +0000627 // Remove blocks from former ancestor loops.
628 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000629
630 // Add direct subloops as children in their new parent loop.
631 Updater.updateSubloopParents();
632
633 // Remove unloop from its parent loop.
634 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000635 for (Loop::iterator I = ParentLoop->begin();; ++I) {
636 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000637 if (*I == Unloop) {
638 ParentLoop->removeChildLoop(I);
639 break;
640 }
641 }
642}
643
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000644char LoopAnalysis::PassID;
645
646LoopInfo LoopAnalysis::run(Function &F, AnalysisManager<Function> *AM) {
647 // FIXME: Currently we create a LoopInfo from scratch for every function.
648 // This may prove to be too wasteful due to deallocating and re-allocating
649 // memory each time for the underlying map and vector datastructures. At some
650 // point it may prove worthwhile to use a freelist and recycle LoopInfo
651 // objects. I don't want to add that kind of complexity until the scope of
652 // the problem is better understood.
653 LoopInfo LI;
Cong Houd2c1d912015-07-16 18:23:57 +0000654 LI.analyze(AM->getResult<DominatorTreeAnalysis>(F));
Richard Trieu6ae37962015-04-30 23:07:00 +0000655 return LI;
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000656}
657
658PreservedAnalyses LoopPrinterPass::run(Function &F,
659 AnalysisManager<Function> *AM) {
660 AM->getResult<LoopAnalysis>(F).print(OS);
661 return PreservedAnalyses::all();
662}
663
Justin Bognerc2b98f02015-11-04 22:24:08 +0000664PrintLoopPass::PrintLoopPass() : OS(dbgs()) {}
665PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
666 : OS(OS), Banner(Banner) {}
667
668PreservedAnalyses PrintLoopPass::run(Loop &L) {
669 OS << Banner;
670 for (auto *Block : L.blocks())
671 if (Block)
672 Block->print(OS);
673 else
674 OS << "Printing <null> block";
675 return PreservedAnalyses::all();
676}
677
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000678//===----------------------------------------------------------------------===//
679// LoopInfo implementation
680//
681
682char LoopInfoWrapperPass::ID = 0;
683INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
684 true, true)
685INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
686INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
687 true, true)
688
689bool LoopInfoWrapperPass::runOnFunction(Function &) {
690 releaseMemory();
Cong Houd2c1d912015-07-16 18:23:57 +0000691 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000692 return false;
693}
694
695void LoopInfoWrapperPass::verifyAnalysis() const {
696 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
697 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman4dbb3012009-09-28 00:27:48 +0000698 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000699 // checking by default, LoopPass has been taught to call verifyLoop manually
700 // during loop pass sequences.
Chandler Carruth691addc2015-01-18 01:25:51 +0000701 if (VerifyLoopInfo)
702 LI.verify();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000703}
704
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000705void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000706 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000707 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000708}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000709
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000710void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Chandler Carruth691addc2015-01-18 01:25:51 +0000711 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000712}
713
Andrew Trick78b40c32011-08-10 01:59:05 +0000714//===----------------------------------------------------------------------===//
715// LoopBlocksDFS implementation
716//
717
718/// Traverse the loop blocks and store the DFS result.
719/// Useful for clients that just want the final DFS result and don't need to
720/// visit blocks during the initial traversal.
721void LoopBlocksDFS::perform(LoopInfo *LI) {
722 LoopBlocksTraversal Traversal(*this, LI);
723 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
724 POE = Traversal.end(); POI != POE; ++POI) ;
725}