blob: ef2b1257015ce19e66bce77bcac4049753ab8223 [file] [log] [blame]
Chris Lattnercf3056d2003-10-13 03:32:08 +00001//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner0bbe58f2001-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 Brukman10d208d2004-01-30 17:26:24 +000017#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/DepthFirstIterator.h"
Sanjoy Das198959c2017-09-20 02:31:57 +000019#include "llvm/ADT/ScopeExit.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "llvm/ADT/SmallPtrSet.h"
Andrew Trickcbf24b42012-06-20 03:42:09 +000021#include "llvm/Analysis/LoopInfoImpl.h"
Andrew Trick2d31ae32011-08-10 01:59:05 +000022#include "llvm/Analysis/LoopIterator.h"
Dan Gohmanf0426602011-12-14 23:49:11 +000023#include "llvm/Analysis/ValueTracking.h"
Nico Weber0f38c602018-04-30 14:59:11 +000024#include "llvm/Config/llvm-config.h"
Chandler Carruth03e36d72014-03-04 11:45:46 +000025#include "llvm/IR/CFG.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
Hal Finkeld86e7af2016-05-25 21:42:37 +000027#include "llvm/IR/DebugLoc.h"
Chandler Carruth56e13942014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Fedor Sergeeva7c23702018-09-24 16:08:15 +000029#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/Instructions.h"
Philip Reames9be94732014-10-21 00:13:20 +000031#include "llvm/IR/LLVMContext.h"
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +000032#include "llvm/IR/Metadata.h"
Chandler Carrutha3751202015-01-20 10:58:50 +000033#include "llvm/IR/PassManager.h"
Dan Gohman9450b0e2009-09-28 00:27:48 +000034#include "llvm/Support/CommandLine.h"
Dan Gohmandda30cd2010-01-05 21:08:02 +000035#include "llvm/Support/Debug.h"
Benjamin Kramer1bfcd1f2015-03-23 19:32:43 +000036#include "llvm/Support/raw_ostream.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000037#include <algorithm>
Chris Lattner46758a82004-04-12 20:26:17 +000038using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000039
Andrew Trickcbf24b42012-06-20 03:42:09 +000040// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
41template class llvm::LoopBase<BasicBlock, Loop>;
42template class llvm::LoopInfoBase<BasicBlock, Loop>;
43
Dan Gohman9450b0e2009-09-28 00:27:48 +000044// Always verify loopinfo if expensive checking is enabled.
Filipe Cabecinhas2fd54342016-04-29 15:22:48 +000045#ifdef EXPENSIVE_CHECKS
Serge Pavlov85a1ed12017-01-24 05:52:07 +000046bool llvm::VerifyLoopInfo = true;
Dan Gohman9450b0e2009-09-28 00:27:48 +000047#else
Serge Pavlov85a1ed12017-01-24 05:52:07 +000048bool llvm::VerifyLoopInfo = false;
Dan Gohman9450b0e2009-09-28 00:27:48 +000049#endif
Sanjoy Dasf4845c82017-09-20 01:12:09 +000050static cl::opt<bool, true>
51 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
Zachary Turner9a4e15c2017-12-01 00:53:10 +000052 cl::Hidden, cl::desc("Verify loop info (time consuming)"));
Dan Gohman9450b0e2009-09-28 00:27:48 +000053
Chris Lattner93193f82002-01-31 00:42:27 +000054//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000055// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000056//
Misha Brukman6b290a52002-10-11 05:31:10 +000057
Pete Cooperc83d5912015-05-13 01:12:06 +000058bool Loop::isLoopInvariant(const Value *V) const {
59 if (const Instruction *I = dyn_cast<Instruction>(V))
Chris Lattneradc79912010-09-06 01:05:37 +000060 return !contains(I);
Sanjoy Dasf4845c82017-09-20 01:12:09 +000061 return true; // All non-instructions are loop invariant
Dan Gohman16a2c922009-07-13 22:02:44 +000062}
63
Pete Cooperc83d5912015-05-13 01:12:06 +000064bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
Pete Cooper33bf03e2015-05-13 22:19:13 +000065 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
Dan Gohmana3420262009-07-14 01:06:29 +000066}
67
Dan Gohmanbdc017e2009-07-15 01:25:43 +000068bool Loop::makeLoopInvariant(Value *V, bool &Changed,
69 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000070 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanbdc017e2009-07-15 01:25:43 +000071 return makeLoopInvariant(I, Changed, InsertPt);
Sanjoy Dasf4845c82017-09-20 01:12:09 +000072 return true; // All non-instructions are loop-invariant.
Dan Gohmana3420262009-07-14 01:06:29 +000073}
74
Dan Gohmanbdc017e2009-07-15 01:25:43 +000075bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
76 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000077 // Test if the value is already loop-invariant.
78 if (isLoopInvariant(I))
79 return true;
Dan Gohmanf0426602011-12-14 23:49:11 +000080 if (!isSafeToSpeculativelyExecute(I))
Dan Gohmana3420262009-07-14 01:06:29 +000081 return false;
Eli Friedman0b79a772009-07-17 04:28:42 +000082 if (I->mayReadFromMemory())
Dan Gohmana3420262009-07-14 01:06:29 +000083 return false;
David Majnemer4a45f082015-07-31 17:58:14 +000084 // EH block instructions are immobile.
85 if (I->isEHPad())
Bill Wendlingc9b2a982011-08-17 20:36:44 +000086 return false;
Dan Gohmana3420262009-07-14 01:06:29 +000087 // Determine the insertion point, unless one was given.
88 if (!InsertPt) {
89 BasicBlock *Preheader = getLoopPreheader();
90 // Without a preheader, hoisting is not feasible.
91 if (!Preheader)
92 return false;
93 InsertPt = Preheader->getTerminator();
94 }
95 // Don't hoist instructions with loop-variant operands.
Sanjay Patel961c8522016-01-15 00:08:10 +000096 for (Value *Operand : I->operands())
97 if (!makeLoopInvariant(Operand, Changed, InsertPt))
Dan Gohmana3420262009-07-14 01:06:29 +000098 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +000099
Dan Gohmana3420262009-07-14 01:06:29 +0000100 // Hoist.
101 I->moveBefore(InsertPt);
Igor Laevskya90859a2015-11-18 14:50:18 +0000102
103 // There is possibility of hoisting this instruction above some arbitrary
104 // condition. Any metadata defined on it can be control dependent on this
105 // condition. Conservatively strip it here so that we don't give any wrong
106 // information to the optimizer.
107 I->dropUnknownNonDebugMetadata();
108
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000109 Changed = true;
Dan Gohmana3420262009-07-14 01:06:29 +0000110 return true;
111}
112
Dan Gohman16a2c922009-07-13 22:02:44 +0000113PHINode *Loop::getCanonicalInductionVariable() const {
114 BasicBlock *H = getHeader();
115
Craig Topper570e52c2014-04-15 04:59:12 +0000116 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohman63137d52010-07-23 21:25:16 +0000117 pred_iterator PI = pred_begin(H);
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000118 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
Dan Gohman16a2c922009-07-13 22:02:44 +0000119 Backedge = *PI++;
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000120 if (PI == pred_end(H))
121 return nullptr; // dead loop
Dan Gohman16a2c922009-07-13 22:02:44 +0000122 Incoming = *PI++;
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000123 if (PI != pred_end(H))
124 return nullptr; // multiple backedges?
Dan Gohman16a2c922009-07-13 22:02:44 +0000125
126 if (contains(Incoming)) {
127 if (contains(Backedge))
Craig Topper570e52c2014-04-15 04:59:12 +0000128 return nullptr;
Dan Gohman16a2c922009-07-13 22:02:44 +0000129 std::swap(Incoming, Backedge);
130 } else if (!contains(Backedge))
Craig Topper570e52c2014-04-15 04:59:12 +0000131 return nullptr;
Dan Gohman16a2c922009-07-13 22:02:44 +0000132
133 // Loop over all of the PHI nodes, looking for a canonical indvar.
134 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
135 PHINode *PN = cast<PHINode>(I);
136 if (ConstantInt *CI =
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000137 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
Craig Topper6dbd34d2017-07-06 18:39:47 +0000138 if (CI->isZero())
Dan Gohman16a2c922009-07-13 22:02:44 +0000139 if (Instruction *Inc =
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000140 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
141 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
Dan Gohman16a2c922009-07-13 22:02:44 +0000142 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
Craig Topper099c15e2017-07-06 18:39:49 +0000143 if (CI->isOne())
Dan Gohman16a2c922009-07-13 22:02:44 +0000144 return PN;
145 }
Craig Topper570e52c2014-04-15 04:59:12 +0000146 return nullptr;
Dan Gohman16a2c922009-07-13 22:02:44 +0000147}
148
Igor Laevsky00eb3c92016-10-11 13:37:22 +0000149// Check that 'BB' doesn't have any uses outside of the 'L'
150static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
151 DominatorTree &DT) {
152 for (const Instruction &I : BB) {
153 // Tokens can't be used in PHI nodes and live-out tokens prevent loop
154 // optimizations, so for the purposes of considered LCSSA form, we
155 // can ignore them.
156 if (I.getType()->isTokenTy())
157 continue;
Andrew Kaylor81cf1672015-12-18 18:12:35 +0000158
Igor Laevsky00eb3c92016-10-11 13:37:22 +0000159 for (const Use &U : I.uses()) {
160 const Instruction *UI = cast<Instruction>(U.getUser());
161 const BasicBlock *UserBB = UI->getParent();
162 if (const PHINode *P = dyn_cast<PHINode>(UI))
163 UserBB = P->getIncomingBlock(U);
Dan Gohman16a2c922009-07-13 22:02:44 +0000164
Igor Laevsky00eb3c92016-10-11 13:37:22 +0000165 // Check the current block, as a fast-path, before checking whether
166 // the use is anywhere in the loop. Most values are used in the same
167 // block they are defined in. Also, blocks not reachable from the
168 // entry are special; uses in them don't need to go through PHIs.
169 if (UserBB != &BB && !L.contains(UserBB) &&
170 DT.isReachableFromEntry(UserBB))
171 return false;
Andrew Kaylor81cf1672015-12-18 18:12:35 +0000172 }
Dan Gohman16a2c922009-07-13 22:02:44 +0000173 }
Dan Gohman16a2c922009-07-13 22:02:44 +0000174 return true;
175}
Dan Gohman93773862009-07-16 16:16:23 +0000176
Igor Laevsky00eb3c92016-10-11 13:37:22 +0000177bool Loop::isLCSSAForm(DominatorTree &DT) const {
178 // For each block we check that it doesn't have any uses outside of this loop.
179 return all_of(this->blocks(), [&](const BasicBlock *BB) {
180 return isBlockInLCSSAForm(*this, *BB, DT);
181 });
182}
Sanjoy Dasca401612015-12-08 00:13:21 +0000183
Igor Laevsky00eb3c92016-10-11 13:37:22 +0000184bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const {
Davide Italiano2ab4f6e2017-01-08 22:22:09 +0000185 // For each block we check that it doesn't have any uses outside of its
186 // innermost loop. This process will transitively guarantee that the current
187 // loop and all of the nested loops are in LCSSA form.
Igor Laevsky00eb3c92016-10-11 13:37:22 +0000188 return all_of(this->blocks(), [&](const BasicBlock *BB) {
189 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT);
190 });
Sanjoy Dasca401612015-12-08 00:13:21 +0000191}
192
Dan Gohman93773862009-07-16 16:16:23 +0000193bool Loop::isLoopSimplifyForm() const {
Dan Gohmanf17e95112009-11-05 19:21:41 +0000194 // Normal-form loops have a preheader, a single backedge, and all of their
195 // exits have all their predecessors inside the loop.
196 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
197}
198
Sanjay Patelc66c94a2016-01-14 23:23:04 +0000199// Routines that reform the loop CFG and split edges often fail on indirectbr.
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000200bool Loop::isSafeToClone() const {
James Molloy67ae1352012-12-20 16:04:27 +0000201 // Return false if any loop blocks contain indirectbrs, or there are any calls
202 // to noduplicate functions.
Sanjay Patel961c8522016-01-15 00:08:10 +0000203 for (BasicBlock *BB : this->blocks()) {
204 if (isa<IndirectBrInst>(BB->getTerminator()))
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000205 return false;
Jakub Staszakdc9a2172013-11-13 20:18:38 +0000206
David Majnemer67d4f302016-05-03 03:57:40 +0000207 for (Instruction &I : *BB)
208 if (auto CS = CallSite(&I))
209 if (CS.cannotDuplicate())
James Molloy67ae1352012-12-20 16:04:27 +0000210 return false;
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000211 }
212 return true;
213}
214
Paul Redmondee21b6f2013-05-28 20:00:34 +0000215MDNode *Loop::getLoopID() const {
Craig Topper570e52c2014-04-15 04:59:12 +0000216 MDNode *LoopID = nullptr;
Paul Redmondee21b6f2013-05-28 20:00:34 +0000217
Michael Kruse2f778b82018-09-17 18:40:29 +0000218 // Go through the latch blocks and check the terminator for the metadata.
219 SmallVector<BasicBlock *, 4> LatchesBlocks;
220 getLoopLatches(LatchesBlocks);
221 for (BasicBlock *BB : LatchesBlocks) {
Chandler Carruth2aaf7222018-10-15 10:04:59 +0000222 Instruction *TI = BB->getTerminator();
Michael Kruse2f778b82018-09-17 18:40:29 +0000223 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
Paul Redmondee21b6f2013-05-28 20:00:34 +0000224
Michael Kruse2f778b82018-09-17 18:40:29 +0000225 if (!MD)
226 return nullptr;
227
228 if (!LoopID)
229 LoopID = MD;
230 else if (MD != LoopID)
231 return nullptr;
Paul Redmondee21b6f2013-05-28 20:00:34 +0000232 }
233 if (!LoopID || LoopID->getNumOperands() == 0 ||
234 LoopID->getOperand(0) != LoopID)
Craig Topper570e52c2014-04-15 04:59:12 +0000235 return nullptr;
Paul Redmondee21b6f2013-05-28 20:00:34 +0000236 return LoopID;
237}
238
239void Loop::setLoopID(MDNode *LoopID) const {
Michael Kruse9a395de2018-12-12 17:32:52 +0000240 assert((!LoopID || LoopID->getNumOperands() > 0) &&
241 "Loop ID needs at least one operand");
242 assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
243 "Loop ID should refer to itself");
Paul Redmondee21b6f2013-05-28 20:00:34 +0000244
Paul Redmondee21b6f2013-05-28 20:00:34 +0000245 BasicBlock *H = getHeader();
Sanjay Patel961c8522016-01-15 00:08:10 +0000246 for (BasicBlock *BB : this->blocks()) {
Chandler Carruth2aaf7222018-10-15 10:04:59 +0000247 Instruction *TI = BB->getTerminator();
Chandler Carruth5eb83c52018-08-26 08:41:15 +0000248 for (BasicBlock *Successor : successors(TI)) {
Michael Kruse9a395de2018-12-12 17:32:52 +0000249 if (Successor == H) {
Duncan P. N. Exon Smith1adb3812016-03-25 00:35:38 +0000250 TI->setMetadata(LLVMContext::MD_loop, LoopID);
Michael Kruse9a395de2018-12-12 17:32:52 +0000251 break;
252 }
Paul Redmondee21b6f2013-05-28 20:00:34 +0000253 }
254 }
255}
256
Hongbin Zheng0446db22017-10-15 07:31:02 +0000257void Loop::setLoopAlreadyUnrolled() {
258 MDNode *LoopID = getLoopID();
259 // First remove any existing loop unrolling metadata.
260 SmallVector<Metadata *, 4> MDs;
261 // Reserve first location for self reference to the LoopID metadata node.
262 MDs.push_back(nullptr);
263
264 if (LoopID) {
265 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
266 bool IsUnrollMetadata = false;
267 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
268 if (MD) {
269 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
270 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
271 }
272 if (!IsUnrollMetadata)
273 MDs.push_back(LoopID->getOperand(i));
274 }
275 }
276
277 // Add unroll(disable) metadata to disable future unrolling.
278 LLVMContext &Context = getHeader()->getContext();
279 SmallVector<Metadata *, 1> DisableOperands;
280 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
281 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
282 MDs.push_back(DisableNode);
283
284 MDNode *NewLoopID = MDNode::get(Context, MDs);
285 // Set operand 0 to refer to the loop id itself.
286 NewLoopID->replaceOperandWith(0, NewLoopID);
287 setLoopID(NewLoopID);
288}
289
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000290bool Loop::isAnnotatedParallel() const {
Sanjay Patelebc85eb2016-01-17 23:18:05 +0000291 MDNode *DesiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000292
Sanjay Patelebc85eb2016-01-17 23:18:05 +0000293 if (!DesiredLoopIdMetadata)
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000294 return false;
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000295
Michael Kruse42a382c2018-12-20 04:58:07 +0000296 MDNode *ParallelAccesses =
297 findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
298 SmallPtrSet<MDNode *, 4>
299 ParallelAccessGroups; // For scalable 'contains' check.
300 if (ParallelAccesses) {
301 for (const MDOperand &MD : drop_begin(ParallelAccesses->operands(), 1)) {
302 MDNode *AccGroup = cast<MDNode>(MD.get());
303 assert(isValidAsAccessGroup(AccGroup) &&
304 "List item must be an access group");
305 ParallelAccessGroups.insert(AccGroup);
306 }
307 }
308
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000309 // The loop branch contains the parallel loop metadata. In order to ensure
310 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
311 // dependencies (thus converted the loop back to a sequential loop), check
Michael Kruse42a382c2018-12-20 04:58:07 +0000312 // that all the memory instructions in the loop belong to an access group that
313 // is parallel to this loop.
Sanjay Patel961c8522016-01-15 00:08:10 +0000314 for (BasicBlock *BB : this->blocks()) {
315 for (Instruction &I : *BB) {
316 if (!I.mayReadOrWriteMemory())
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000317 continue;
318
Michael Kruse42a382c2018-12-20 04:58:07 +0000319 if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
320 auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
321 if (AG->getNumOperands() == 0) {
322 assert(isValidAsAccessGroup(AG) && "Item must be an access group");
323 return ParallelAccessGroups.count(AG);
324 }
325
326 for (const MDOperand &AccessListItem : AG->operands()) {
327 MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
328 assert(isValidAsAccessGroup(AccGroup) &&
329 "List item must be an access group");
330 if (ParallelAccessGroups.count(AccGroup))
331 return true;
332 }
333 return false;
334 };
335
336 if (ContainsAccessGroup(AccessGroup))
337 continue;
338 }
339
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000340 // The memory instruction can refer to the loop identifier metadata
341 // directly or indirectly through another list metadata (in case of
342 // nested parallel loops). The loop identifier metadata refers to
343 // itself so we can check both cases with the same routine.
Sanjay Patelebc85eb2016-01-17 23:18:05 +0000344 MDNode *LoopIdMD =
Sanjay Patel961c8522016-01-15 00:08:10 +0000345 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszakdc9a2172013-11-13 20:18:38 +0000346
Sanjay Patelebc85eb2016-01-17 23:18:05 +0000347 if (!LoopIdMD)
Jakub Staszakdc9a2172013-11-13 20:18:38 +0000348 return false;
349
Sanjay Patelebc85eb2016-01-17 23:18:05 +0000350 bool LoopIdMDFound = false;
351 for (const MDOperand &MDOp : LoopIdMD->operands()) {
352 if (MDOp == DesiredLoopIdMetadata) {
353 LoopIdMDFound = true;
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000354 break;
355 }
356 }
357
Sanjay Patelebc85eb2016-01-17 23:18:05 +0000358 if (!LoopIdMDFound)
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000359 return false;
360 }
361 }
362 return true;
363}
364
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000365DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
Amara Emerson0a1b0ce2016-11-08 11:18:59 +0000366
367Loop::LocRange Loop::getLocRange() const {
Hal Finkeld86e7af2016-05-25 21:42:37 +0000368 // If we have a debug location in the loop ID, then use it.
Amara Emerson0a1b0ce2016-11-08 11:18:59 +0000369 if (MDNode *LoopID = getLoopID()) {
370 DebugLoc Start;
371 // We use the first DebugLoc in the header as the start location of the loop
372 // and if there is a second DebugLoc in the header we use it as end location
373 // of the loop.
374 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
375 if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
376 if (!Start)
377 Start = DebugLoc(L);
378 else
379 return LocRange(Start, DebugLoc(L));
380 }
381 }
382
383 if (Start)
384 return LocRange(Start);
385 }
Hal Finkeld86e7af2016-05-25 21:42:37 +0000386
387 // Try the pre-header first.
388 if (BasicBlock *PHeadBB = getLoopPreheader())
389 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
Amara Emerson0a1b0ce2016-11-08 11:18:59 +0000390 return LocRange(DL);
Hal Finkeld86e7af2016-05-25 21:42:37 +0000391
392 // If we have no pre-header or there are no instructions with debug
393 // info in it, try the header.
394 if (BasicBlock *HeadBB = getHeader())
Amara Emerson0a1b0ce2016-11-08 11:18:59 +0000395 return LocRange(HeadBB->getTerminator()->getDebugLoc());
Hal Finkeld86e7af2016-05-25 21:42:37 +0000396
Amara Emerson0a1b0ce2016-11-08 11:18:59 +0000397 return LocRange();
Hal Finkeld86e7af2016-05-25 21:42:37 +0000398}
399
Aaron Ballman1d03d382017-10-15 14:32:27 +0000400#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000401LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
Sebastian Pop906c5ef2016-07-27 05:02:17 +0000402
403LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000404 print(dbgs(), /*Depth=*/0, /*Verbose=*/true);
Sebastian Pop906c5ef2016-07-27 05:02:17 +0000405}
Manman Rencc77eec2012-09-06 19:55:56 +0000406#endif
Dan Gohmandda30cd2010-01-05 21:08:02 +0000407
Chris Lattnera59cbb22002-07-27 01:12:17 +0000408//===----------------------------------------------------------------------===//
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000409// UnloopUpdater implementation
410//
411
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000412namespace {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000413/// Find the new parent loop for all blocks within the "unloop" whose last
414/// backedges has just been removed.
415class UnloopUpdater {
Silviu Baranga412498b2016-05-13 14:54:50 +0000416 Loop &Unloop;
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000417 LoopInfo *LI;
418
419 LoopBlocksDFS DFS;
420
421 // Map unloop's immediate subloops to their nearest reachable parents. Nested
422 // loops within these subloops will not change parents. However, an immediate
423 // subloop's new parent will be the nearest loop reachable from either its own
424 // exits *or* any of its nested loop's exits.
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000425 DenseMap<Loop *, Loop *> SubloopParents;
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000426
427 // Flag the presence of an irreducible backedge whose destination is a block
428 // directly contained by the original unloop.
429 bool FoundIB;
430
431public:
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000432 UnloopUpdater(Loop *UL, LoopInfo *LInfo)
433 : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000434
435 void updateBlockParents();
436
Andrew Trickc12d9b92011-08-11 20:27:32 +0000437 void removeBlocksFromAncestors();
438
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000439 void updateSubloopParents();
440
441protected:
442 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
443};
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000444} // end anonymous namespace
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000445
Sanjay Patelc66c94a2016-01-14 23:23:04 +0000446/// Update the parent loop for all blocks that are directly contained within the
447/// original "unloop".
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000448void UnloopUpdater::updateBlockParents() {
Silviu Baranga412498b2016-05-13 14:54:50 +0000449 if (Unloop.getNumBlocks()) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000450 // Perform a post order CFG traversal of all blocks within this loop,
Hiroshi Inoue5c99c6a2017-07-09 05:54:44 +0000451 // propagating the nearest loop from successors to predecessors.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000452 LoopBlocksTraversal Traversal(DFS, LI);
Benjamin Kramer8d0d2b62016-06-26 17:27:42 +0000453 for (BasicBlock *POI : Traversal) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000454
Benjamin Kramer8d0d2b62016-06-26 17:27:42 +0000455 Loop *L = LI->getLoopFor(POI);
456 Loop *NL = getNearestLoop(POI, L);
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000457
458 if (NL != L) {
459 // For reducible loops, NL is now an ancestor of Unloop.
Silviu Baranga412498b2016-05-13 14:54:50 +0000460 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000461 "uninitialized successor");
Benjamin Kramer8d0d2b62016-06-26 17:27:42 +0000462 LI->changeLoopFor(POI, NL);
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000463 } else {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000464 // Or the current block is part of a subloop, in which case its parent
465 // is unchanged.
Silviu Baranga412498b2016-05-13 14:54:50 +0000466 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000467 }
468 }
469 }
470 // Each irreducible loop within the unloop induces a round of iteration using
471 // the DFS result cached by Traversal.
472 bool Changed = FoundIB;
473 for (unsigned NIters = 0; Changed; ++NIters) {
Silviu Baranga412498b2016-05-13 14:54:50 +0000474 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000475
476 // Iterate over the postorder list of blocks, propagating the nearest loop
477 // from successors to predecessors as before.
478 Changed = false;
479 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000480 POE = DFS.endPostorder();
481 POI != POE; ++POI) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000482
483 Loop *L = LI->getLoopFor(*POI);
484 Loop *NL = getNearestLoop(*POI, L);
485 if (NL != L) {
Silviu Baranga412498b2016-05-13 14:54:50 +0000486 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000487 "uninitialized successor");
488 LI->changeLoopFor(*POI, NL);
489 Changed = true;
490 }
491 }
492 }
493}
494
Sanjay Patelc66c94a2016-01-14 23:23:04 +0000495/// Remove unloop's blocks from all ancestors below their new parents.
Andrew Trickc12d9b92011-08-11 20:27:32 +0000496void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000497 // Remove all unloop's blocks (including those in nested subloops) from
498 // ancestors below the new parent loop.
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000499 for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end();
500 BI != BE; ++BI) {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000501 Loop *OuterParent = LI->getLoopFor(*BI);
Silviu Baranga412498b2016-05-13 14:54:50 +0000502 if (Unloop.contains(OuterParent)) {
503 while (OuterParent->getParentLoop() != &Unloop)
Andrew Trick5865a8d2011-11-18 03:42:41 +0000504 OuterParent = OuterParent->getParentLoop();
505 OuterParent = SubloopParents[OuterParent];
506 }
Andrew Trickc12d9b92011-08-11 20:27:32 +0000507 // Remove blocks from former Ancestors except Unloop itself which will be
508 // deleted.
Silviu Baranga412498b2016-05-13 14:54:50 +0000509 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
Andrew Trickc12d9b92011-08-11 20:27:32 +0000510 OldParent = OldParent->getParentLoop()) {
511 assert(OldParent && "new loop is not an ancestor of the original");
512 OldParent->removeBlockFromLoop(*BI);
513 }
514 }
515}
516
Sanjay Patelc66c94a2016-01-14 23:23:04 +0000517/// Update the parent loop for all subloops directly nested within unloop.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000518void UnloopUpdater::updateSubloopParents() {
Silviu Baranga412498b2016-05-13 14:54:50 +0000519 while (!Unloop.empty()) {
520 Loop *Subloop = *std::prev(Unloop.end());
521 Unloop.removeChildLoop(std::prev(Unloop.end()));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000522
523 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramer05d96f92012-08-22 15:37:57 +0000524 if (Loop *Parent = SubloopParents[Subloop])
525 Parent->addChildLoop(Subloop);
Andrew Trick5434c1e2011-08-26 03:06:34 +0000526 else
527 LI->addTopLevelLoop(Subloop);
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000528 }
529}
530
Sanjay Patelc66c94a2016-01-14 23:23:04 +0000531/// Return the nearest parent loop among this block's successors. If a successor
532/// is a subloop header, consider its parent to be the nearest parent of the
533/// subloop's exits.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000534///
535/// For subloop blocks, simply update SubloopParents and return NULL.
536Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
537
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000538 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
539 // is considered uninitialized.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000540 Loop *NearLoop = BBLoop;
541
Craig Topper570e52c2014-04-15 04:59:12 +0000542 Loop *Subloop = nullptr;
Silviu Baranga412498b2016-05-13 14:54:50 +0000543 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000544 Subloop = NearLoop;
545 // Find the subloop ancestor that is directly contained within Unloop.
Silviu Baranga412498b2016-05-13 14:54:50 +0000546 while (Subloop->getParentLoop() != &Unloop) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000547 Subloop = Subloop->getParentLoop();
548 assert(Subloop && "subloop is not an ancestor of the original loop");
549 }
550 // Get the current nearest parent of the Subloop exits, initially Unloop.
David Majnemerdc9c7372016-08-11 21:15:00 +0000551 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000552 }
553
554 succ_iterator I = succ_begin(BB), E = succ_end(BB);
555 if (I == E) {
556 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper570e52c2014-04-15 04:59:12 +0000557 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000558 }
559 for (; I != E; ++I) {
560 if (*I == BB)
561 continue; // self loops are uninteresting
562
563 Loop *L = LI->getLoopFor(*I);
Silviu Baranga412498b2016-05-13 14:54:50 +0000564 if (L == &Unloop) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000565 // This successor has not been processed. This path must lead to an
566 // irreducible backedge.
567 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
568 FoundIB = true;
569 }
Silviu Baranga412498b2016-05-13 14:54:50 +0000570 if (L != &Unloop && Unloop.contains(L)) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000571 // Successor is in a subloop.
572 if (Subloop)
573 continue; // Branching within subloops. Ignore it.
574
575 // BB branches from the original into a subloop header.
Silviu Baranga412498b2016-05-13 14:54:50 +0000576 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000577
578 // Get the current nearest parent of the Subloop's exits.
579 L = SubloopParents[L];
580 // L could be Unloop if the only exit was an irreducible backedge.
581 }
Silviu Baranga412498b2016-05-13 14:54:50 +0000582 if (L == &Unloop) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000583 continue;
584 }
585 // Handle critical edges from Unloop into a sibling loop.
Silviu Baranga412498b2016-05-13 14:54:50 +0000586 if (L && !L->contains(&Unloop)) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000587 L = L->getParentLoop();
588 }
589 // Remember the nearest parent loop among successors or subloop exits.
Silviu Baranga412498b2016-05-13 14:54:50 +0000590 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000591 NearLoop = L;
592 }
593 if (Subloop) {
594 SubloopParents[Subloop] = NearLoop;
595 return BBLoop;
596 }
597 return NearLoop;
598}
599
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000600LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
Cong Hou1dd3d832015-07-16 23:23:35 +0000601
Chandler Carruth10dd00c2017-01-15 06:32:49 +0000602bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
603 FunctionAnalysisManager::Invalidator &) {
604 // Check whether the analysis, all analyses on functions, or the function's
605 // CFG have been preserved.
606 auto PAC = PA.getChecker<LoopAnalysis>();
607 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
608 PAC.preservedSet<CFGAnalyses>());
609}
610
Sanjoy Das909d3772017-09-22 01:47:41 +0000611void LoopInfo::erase(Loop *Unloop) {
Sanjoy Das6199cad2017-09-19 23:19:00 +0000612 assert(!Unloop->isInvalid() && "Loop has already been erased!");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000613
Sanjoy Dase87cf872017-09-28 02:45:42 +0000614 auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
Sanjoy Das198959c2017-09-20 02:31:57 +0000615
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000616 // First handle the special case of no parent loop to simplify the algorithm.
617 if (!Unloop->getParentLoop()) {
618 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
619 for (Loop::block_iterator I = Unloop->block_begin(),
Chandler Carruth5a2d01e2015-01-18 01:25:51 +0000620 E = Unloop->block_end();
621 I != E; ++I) {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000622
623 // Don't reparent blocks in subloops.
624 if (getLoopFor(*I) != Unloop)
625 continue;
626
627 // Blocks no longer have a parent but are still referenced by Unloop until
628 // the Unloop object is deleted.
Chandler Carruth5a2d01e2015-01-18 01:25:51 +0000629 changeLoopFor(*I, nullptr);
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000630 }
631
632 // Remove the loop from the top-level LoopInfo object.
Chandler Carruth5a2d01e2015-01-18 01:25:51 +0000633 for (iterator I = begin();; ++I) {
634 assert(I != end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000635 if (*I == Unloop) {
Chandler Carruth5a2d01e2015-01-18 01:25:51 +0000636 removeLoop(I);
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000637 break;
638 }
639 }
640
641 // Move all of the subloops to the top-level.
642 while (!Unloop->empty())
Chandler Carruth5a2d01e2015-01-18 01:25:51 +0000643 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000644
645 return;
646 }
647
648 // Update the parent loop for all blocks within the loop. Blocks within
649 // subloops will not change parents.
650 UnloopUpdater Updater(Unloop, this);
651 Updater.updateBlockParents();
652
Andrew Trickc12d9b92011-08-11 20:27:32 +0000653 // Remove blocks from former ancestor loops.
654 Updater.removeBlocksFromAncestors();
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000655
656 // Add direct subloops as children in their new parent loop.
657 Updater.updateSubloopParents();
658
659 // Remove unloop from its parent loop.
660 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sands1f6a3292011-08-12 14:54:45 +0000661 for (Loop::iterator I = ParentLoop->begin();; ++I) {
662 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000663 if (*I == Unloop) {
664 ParentLoop->removeChildLoop(I);
665 break;
666 }
667 }
668}
669
Chandler Carruth33d56812016-11-23 17:53:26 +0000670AnalysisKey LoopAnalysis::Key;
NAKAMURA Takumid9b6afb2016-02-28 17:17:00 +0000671
Sean Silva20b343c2016-08-09 00:28:15 +0000672LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carrutha3751202015-01-20 10:58:50 +0000673 // FIXME: Currently we create a LoopInfo from scratch for every function.
674 // This may prove to be too wasteful due to deallocating and re-allocating
675 // memory each time for the underlying map and vector datastructures. At some
676 // point it may prove worthwhile to use a freelist and recycle LoopInfo
677 // objects. I don't want to add that kind of complexity until the scope of
678 // the problem is better understood.
679 LoopInfo LI;
Chandler Carruth8e27cb22016-03-11 11:05:24 +0000680 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
Richard Trieu509e9d92015-04-30 23:07:00 +0000681 return LI;
Chandler Carrutha3751202015-01-20 10:58:50 +0000682}
683
684PreservedAnalyses LoopPrinterPass::run(Function &F,
Sean Silva20b343c2016-08-09 00:28:15 +0000685 FunctionAnalysisManager &AM) {
Chandler Carruth8e27cb22016-03-11 11:05:24 +0000686 AM.getResult<LoopAnalysis>(F).print(OS);
Chandler Carrutha3751202015-01-20 10:58:50 +0000687 return PreservedAnalyses::all();
688}
689
Chandler Carruthd27a39a2017-01-11 06:23:21 +0000690void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
Fedor Sergeev56082592017-12-01 18:33:58 +0000691
692 if (forcePrintModuleIR()) {
693 // handling -print-module-scope
694 OS << Banner << " (loop: ";
695 L.getHeader()->printAsOperand(OS, false);
696 OS << ")\n";
697
698 // printing whole module
699 OS << *L.getHeader()->getModule();
700 return;
701 }
702
Justin Bogner32968f12015-11-04 22:24:08 +0000703 OS << Banner;
Fedor Sergeeva51f0912017-11-22 20:59:53 +0000704
705 auto *PreHeader = L.getLoopPreheader();
706 if (PreHeader) {
707 OS << "\n; Preheader:";
708 PreHeader->print(OS);
709 OS << "\n; Loop:";
710 }
711
Justin Bogner32968f12015-11-04 22:24:08 +0000712 for (auto *Block : L.blocks())
713 if (Block)
714 Block->print(OS);
715 else
716 OS << "Printing <null> block";
Fedor Sergeeva51f0912017-11-22 20:59:53 +0000717
718 SmallVector<BasicBlock *, 8> ExitBlocks;
719 L.getExitBlocks(ExitBlocks);
720 if (!ExitBlocks.empty()) {
721 OS << "\n; Exit blocks";
722 for (auto *Block : ExitBlocks)
723 if (Block)
724 Block->print(OS);
725 else
726 OS << "Printing <null> block";
727 }
Justin Bogner32968f12015-11-04 22:24:08 +0000728}
729
Michael Kruse42a382c2018-12-20 04:58:07 +0000730MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
731 // No loop metadata node, no loop properties.
732 if (!LoopID)
733 return nullptr;
734
735 // First operand should refer to the metadata node itself, for legacy reasons.
736 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
737 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
738
739 // Iterate over the metdata node operands and look for MDString metadata.
740 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
741 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
742 if (!MD || MD->getNumOperands() < 1)
743 continue;
744 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
745 if (!S)
746 continue;
747 // Return the operand node if MDString holds expected metadata.
748 if (Name.equals(S->getString()))
749 return MD;
750 }
751
752 // Loop property not found.
753 return nullptr;
754}
755
756MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) {
757 return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
758}
759
760bool llvm::isValidAsAccessGroup(MDNode *Node) {
761 return Node->getNumOperands() == 0 && Node->isDistinct();
762}
763
Chandler Carruthde5df292015-01-17 14:16:18 +0000764//===----------------------------------------------------------------------===//
765// LoopInfo implementation
766//
767
768char LoopInfoWrapperPass::ID = 0;
769INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
770 true, true)
771INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
772INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
773 true, true)
774
775bool LoopInfoWrapperPass::runOnFunction(Function &) {
776 releaseMemory();
Cong Hou204b5902015-07-16 18:23:57 +0000777 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chandler Carruthde5df292015-01-17 14:16:18 +0000778 return false;
779}
780
781void LoopInfoWrapperPass::verifyAnalysis() const {
782 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
783 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman9450b0e2009-09-28 00:27:48 +0000784 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruthde5df292015-01-17 14:16:18 +0000785 // checking by default, LoopPass has been taught to call verifyLoop manually
786 // during loop pass sequences.
Michael Zolotukhindbd67f62016-08-31 19:26:19 +0000787 if (VerifyLoopInfo) {
Serge Pavlov69a1a202017-01-15 10:23:18 +0000788 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
789 LI.verify(DT);
Michael Zolotukhindbd67f62016-08-31 19:26:19 +0000790 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000791}
792
Chandler Carruthde5df292015-01-17 14:16:18 +0000793void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000794 AU.setPreservesAll();
Chandler Carruth7f2eff72014-01-13 13:07:17 +0000795 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattner93193f82002-01-31 00:42:27 +0000796}
Chris Lattner791102f2009-08-23 05:17:37 +0000797
Chandler Carruthde5df292015-01-17 14:16:18 +0000798void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Chandler Carruth5a2d01e2015-01-18 01:25:51 +0000799 LI.print(OS);
Chris Lattner791102f2009-08-23 05:17:37 +0000800}
801
Sean Silvad8c90ea2016-07-19 23:54:23 +0000802PreservedAnalyses LoopVerifierPass::run(Function &F,
Sean Silva20b343c2016-08-09 00:28:15 +0000803 FunctionAnalysisManager &AM) {
Sean Silvad8c90ea2016-07-19 23:54:23 +0000804 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
Michael Zolotukhindbd67f62016-08-31 19:26:19 +0000805 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
806 LI.verify(DT);
Sean Silvad8c90ea2016-07-19 23:54:23 +0000807 return PreservedAnalyses::all();
808}
809
Andrew Trick2d31ae32011-08-10 01:59:05 +0000810//===----------------------------------------------------------------------===//
811// LoopBlocksDFS implementation
812//
813
814/// Traverse the loop blocks and store the DFS result.
815/// Useful for clients that just want the final DFS result and don't need to
816/// visit blocks during the initial traversal.
817void LoopBlocksDFS::perform(LoopInfo *LI) {
818 LoopBlocksTraversal Traversal(*this, LI);
819 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
Sanjoy Dasf4845c82017-09-20 01:12:09 +0000820 POE = Traversal.end();
821 POI != POE; ++POI)
822 ;
Andrew Trick2d31ae32011-08-10 01:59:05 +0000823}