blob: b360419d894961d34493d97d9b92a36549d49a32 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- ScopDetection.cpp - Detect Scops --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
16// Every Scop fullfills these restrictions:
17//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
37// Only function calls and intrinsics that do not have side effects are allowed
38// (readnone).
39//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000049#include "polly/Options.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000050#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000057#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000059#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000060#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000061#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000062#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000064#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000065#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000066#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
68
Tobias Grosser75805372011-04-29 06:27:02 +000069using namespace llvm;
70using namespace polly;
71
Chandler Carruth95fef942014-04-22 03:30:19 +000072#define DEBUG_TYPE "polly-detect"
73
Tobias Grosser575aca82015-10-06 16:10:29 +000074bool polly::PollyProcessUnprofitable;
75static cl::opt<bool, true> XPollyProcessUnprofitable(
76 "polly-process-unprofitable",
77 cl::desc(
78 "Process scops that are unlikely to benefit from Polly optimizations."),
79 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
80 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000081
Tobias Grosser483a90d2014-07-09 10:50:10 +000082static cl::opt<std::string> OnlyFunction(
83 "polly-only-func",
84 cl::desc("Only run on functions that contain a certain string"),
85 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
86 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000087
Tobias Grosser483a90d2014-07-09 10:50:10 +000088static cl::opt<std::string> OnlyRegion(
89 "polly-only-region",
90 cl::desc("Only run on certain regions (The provided identifier must "
91 "appear in the name of the region's entry block"),
92 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
93 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +000094
Tobias Grosser60cd9322011-11-10 12:47:26 +000095static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000096 IgnoreAliasing("polly-ignore-aliasing",
97 cl::desc("Ignore possible aliasing of the array bases"),
98 cl::Hidden, cl::init(false), cl::ZeroOrMore,
99 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000100
Johannes Doerfertb164c792014-09-18 11:17:17 +0000101bool polly::PollyUseRuntimeAliasChecks;
102static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
103 "polly-use-runtime-alias-checks",
104 cl::desc("Use runtime alias checks to resolve possible aliasing."),
105 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
106 cl::init(true), cl::cat(PollyCategory));
107
Tobias Grosser637bd632013-05-07 07:31:10 +0000108static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000109 ReportLevel("polly-report",
110 cl::desc("Print information about the activities of Polly"),
111 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000112
113static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000114 AllowNonAffine("polly-allow-nonaffine",
115 cl::desc("Allow non affine access functions in arrays"),
116 cl::Hidden, cl::init(false), cl::ZeroOrMore,
117 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000118
Johannes Doerfertba65c162015-02-24 11:45:21 +0000119static cl::opt<bool> AllowNonAffineSubRegions(
120 "polly-allow-nonaffine-branches",
121 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000122 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000123
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000124static cl::opt<bool>
125 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
126 cl::desc("Allow non affine conditions for loops"),
127 cl::Hidden, cl::init(false), cl::ZeroOrMore,
128 cl::cat(PollyCategory));
129
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000130static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
131 cl::desc("Allow unsigned expressions"),
132 cl::Hidden, cl::init(false), cl::ZeroOrMore,
133 cl::cat(PollyCategory));
134
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000135static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000136 TrackFailures("polly-detect-track-failures",
137 cl::desc("Track failure strings in detecting scop regions"),
138 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000139 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000140
Andreas Simbuerger04472402014-05-24 09:25:10 +0000141static cl::opt<bool> KeepGoing("polly-detect-keep-going",
142 cl::desc("Do not fail on the first error."),
143 cl::Hidden, cl::ZeroOrMore, cl::init(false),
144 cl::cat(PollyCategory));
145
Sebastian Pop18016682014-04-08 21:20:44 +0000146static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000147 PollyDelinearizeX("polly-delinearize",
148 cl::desc("Delinearize array access functions"),
149 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000150 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000151
Tobias Grossera1689932014-02-18 18:49:49 +0000152static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000153 VerifyScops("polly-detect-verify",
154 cl::desc("Verify the detected SCoPs after each transformation"),
155 cl::Hidden, cl::init(false), cl::ZeroOrMore,
156 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000157
Johannes Doerferte526de52015-09-21 19:10:11 +0000158/// @brief The minimal trip count under which loops are considered unprofitable.
159static const unsigned MIN_LOOP_TRIP_COUNT = 8;
160
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000161bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000162bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000163StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000164
Tobias Grosser75805372011-04-29 06:27:02 +0000165//===----------------------------------------------------------------------===//
166// Statistics.
167
168STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
169
Tobias Grosser8519f892013-12-18 10:49:53 +0000170class DiagnosticScopFound : public DiagnosticInfo {
171private:
172 static int PluginDiagnosticKind;
173
174 Function &F;
175 std::string FileName;
176 unsigned EntryLine, ExitLine;
177
178public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000179 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
180 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000181 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000182 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000183
184 virtual void print(DiagnosticPrinter &DP) const;
185
186 static bool classof(const DiagnosticInfo *DI) {
187 return DI->getKind() == PluginDiagnosticKind;
188 }
189};
190
191int DiagnosticScopFound::PluginDiagnosticKind = 10;
192
Tobias Grosser8519f892013-12-18 10:49:53 +0000193void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000194 DP << "Polly detected an optimizable loop region (scop) in function '" << F
195 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000196
197 if (FileName.empty()) {
198 DP << "Scop location is unknown. Compile with debug info "
199 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000200 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000201 }
202
203 DP << FileName << ":" << EntryLine << ": Start of scop\n";
204 DP << FileName << ":" << ExitLine << ": End of scop";
205}
206
Tobias Grosser75805372011-04-29 06:27:02 +0000207//===----------------------------------------------------------------------===//
208// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000209
Johannes Doerfertb164c792014-09-18 11:17:17 +0000210ScopDetection::ScopDetection() : FunctionPass(ID) {
211 if (!PollyUseRuntimeAliasChecks)
212 return;
213
Johannes Doerfert928229f2014-09-29 17:06:29 +0000214 // Disable runtime alias checks if we ignore aliasing all together.
215 if (IgnoreAliasing) {
216 PollyUseRuntimeAliasChecks = false;
217 return;
218 }
219
Johannes Doerfertb164c792014-09-18 11:17:17 +0000220 if (AllowNonAffine) {
221 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
222 "accesses are enabled.\n");
223 PollyUseRuntimeAliasChecks = false;
224 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000225}
226
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000227template <class RR, typename... Args>
228inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
229 Args &&... Arguments) const {
230
231 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000232 RejectLog &Log = Context.Log;
233 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000234
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000235 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000236 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000237
238 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000239 DEBUG(dbgs() << "\n");
240 } else {
241 assert(!Assert && "Verification of detected scop failed");
242 }
243
244 return false;
245}
246
Tobias Grossera1689932014-02-18 18:49:49 +0000247bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
248 if (!ValidRegions.count(&R))
249 return false;
250
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000251 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000252 DetectionContextMap.erase(&R);
253 const auto &It = DetectionContextMap.insert(
254 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
255 false /*verifying*/)));
256 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000257 return isValidRegion(Context);
258 }
Tobias Grossera1689932014-02-18 18:49:49 +0000259
260 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000261}
262
Tobias Grosser4f129a62011-10-08 00:30:55 +0000263std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000264 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000265 return "";
266
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000267 // Get the first error we found. Even in keep-going mode, this is the first
268 // reason that caused the candidate to be rejected.
269 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000270
271 // This can happen when we marked a region invalid, but didn't track
272 // an error for it.
273 if (Errors.size() == 0)
274 return "";
275
276 RejectReasonPtr RR = *Errors.begin();
277 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000278}
279
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000280bool ScopDetection::addOverApproximatedRegion(Region *AR,
281 DetectionContext &Context) const {
282
283 // If we already know about Ar we can exit.
284 if (!Context.NonAffineSubRegionSet.insert(AR))
285 return true;
286
287 // All loops in the region have to be overapproximated too if there
288 // are accesses that depend on the iteration count.
289 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000290 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000291 if (AR->contains(L))
292 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000293 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000294
295 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000296}
297
Johannes Doerfert09e36972015-10-07 20:17:36 +0000298bool ScopDetection::onlyValidRequiredInvariantLoads(
299 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
300 Region &CurRegion = Context.CurRegion;
301
302 for (LoadInst *Load : RequiredILS)
303 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
304 return false;
305
306 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
307
308 return true;
309}
310
311bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
312 Value *BaseAddress) const {
313
314 InvariantLoadsSetTy AccessILS;
315 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
316 return false;
317
318 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
319 return false;
320
321 return true;
322}
323
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000324bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000325 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000326 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000327 Loop *L = LI->getLoopFor(&BB);
328 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000329
Johannes Doerfert09e36972015-10-07 20:17:36 +0000330 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000331 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000332
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000333 if (!IsLoopBranch && AllowNonAffineSubRegions &&
334 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
335 return true;
336
337 if (IsLoopBranch)
338 return false;
339
340 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
341 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000342}
343
344bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000345 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000346 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000347
348 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
349 auto Opcode = BinOp->getOpcode();
350 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
351 Value *Op0 = BinOp->getOperand(0);
352 Value *Op1 = BinOp->getOperand(1);
353 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
354 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
355 }
356 }
357
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000358 // Non constant conditions of branches need to be ICmpInst.
359 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000360 if (!IsLoopBranch && AllowNonAffineSubRegions &&
361 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
362 return true;
363 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000364 }
Tobias Grosser75805372011-04-29 06:27:02 +0000365
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000366 ICmpInst *ICmp = cast<ICmpInst>(Condition);
367 // Unsigned comparisons are not allowed. They trigger overflow problems
368 // in the code generation.
369 //
370 // TODO: This is not sufficient and just hides bugs. However it does pretty
371 // well.
372 if (ICmp->isUnsigned() && !AllowUnsigned)
373 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000374
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000375 // Are both operands of the ICmp affine?
376 if (isa<UndefValue>(ICmp->getOperand(0)) ||
377 isa<UndefValue>(ICmp->getOperand(1)))
378 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000379
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000380 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
381 // for arbitrary pointer expressions at the moment. Until
382 // this is fixed we disallow pointer expressions completely.
383 if (ICmp->getOperand(0)->getType()->isPointerTy())
384 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000385
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000386 Loop *L = LI->getLoopFor(ICmp->getParent());
387 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
388 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000389
Johannes Doerfert09e36972015-10-07 20:17:36 +0000390 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000391 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000392
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000393 if (!IsLoopBranch && AllowNonAffineSubRegions &&
394 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
395 return true;
396
397 if (IsLoopBranch)
398 return false;
399
400 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
401 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000402}
403
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000404bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000405 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000406 DetectionContext &Context) const {
407 Region &CurRegion = Context.CurRegion;
408
409 TerminatorInst *TI = BB.getTerminator();
410
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000411 if (AllowUnreachable && isa<UnreachableInst>(TI))
412 return true;
413
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000414 // Return instructions are only valid if the region is the top level region.
415 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
416 return true;
417
418 Value *Condition = getConditionFromTerminator(TI);
419
420 if (!Condition)
421 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
422
423 // UndefValue is not allowed as condition.
424 if (isa<UndefValue>(Condition))
425 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
426
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000427 // Constant integer conditions are always affine.
428 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000429 return true;
430
431 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000432 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000433
434 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
435 assert(SI && "Terminator was neither branch nor switch");
436
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000437 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000438}
439
Tobias Grosser75805372011-04-29 06:27:02 +0000440bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000441 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000442 return false;
443
444 if (CI.doesNotAccessMemory())
445 return true;
446
447 Function *CalledFunction = CI.getCalledFunction();
448
449 // Indirect calls are not supported.
450 if (CalledFunction == 0)
451 return false;
452
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000453 if (isIgnoredIntrinsic(&CI))
454 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000455
Tobias Grosser75805372011-04-29 06:27:02 +0000456 return false;
457}
458
Tobias Grosser458fb782014-01-28 12:58:58 +0000459bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
460 // A reference to function argument or constant value is invariant.
461 if (isa<Argument>(Val) || isa<Constant>(Val))
462 return true;
463
464 const Instruction *I = dyn_cast<Instruction>(&Val);
465 if (!I)
466 return false;
467
468 if (!Reg.contains(I))
469 return true;
470
471 if (I->mayHaveSideEffects())
472 return false;
473
474 // When Val is a Phi node, it is likely not invariant. We do not check whether
475 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
476 // invariant. Recursively checking the operators of Phi nodes would lead to
477 // infinite recursion.
478 if (isa<PHINode>(*I))
479 return false;
480
Tobias Grosser26108892014-04-02 20:18:19 +0000481 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000482 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000483 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000484
Tobias Grosser458fb782014-01-28 12:58:58 +0000485 return true;
486}
487
Sebastian Pop422e33f2014-06-03 18:16:31 +0000488MapInsnToMemAcc InsnToMemAcc;
489
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000490/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
491/// register the '...' components.
492///
493/// Array access expressions as they are generated by gfortran contain smax(0,
494/// size) expressions that confuse the 'normal' delinearization algorithm.
495/// However, if we extract such expressions before the normal delinearization
496/// takes place they can actually help to identify array size expressions in
497/// fortran accesses. For the subsequently following delinearization the smax(0,
498/// size) component can be replaced by just 'size'. This is correct as we will
499/// always add and verify the assumption that for all subscript expressions
500/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
501/// that 0 <= size, which means smax(0, size) == size.
502struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
503public:
504 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
505 std::vector<const SCEV *> *Terms = nullptr) {
506
507 SCEVRemoveMax D(SE, Terms);
508 return D.visit(Expr);
509 }
510
511 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
512 : SE(SE), Terms(Terms) {}
513
514 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
515
516 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
517 return Expr;
518 }
519
520 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
521 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
522 }
523
524 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
525
526 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Roman Gareev8aa43752015-12-17 20:37:17 +0000527 if ((Expr->getNumOperands() == 2) and Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000528 auto Res = visit(Expr->getOperand(1));
529 if (Terms)
530 (*Terms).push_back(Res);
531 return Res;
532 }
533
534 return Expr;
535 }
536
Roman Gareev8aa43752015-12-17 20:37:17 +0000537 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000538
539 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
540
541 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
542 return Expr;
543 }
544
545 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
546
547 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
548 SmallVector<const SCEV *, 5> NewOps;
549 for (const SCEV *Op : Expr->operands())
550 NewOps.push_back(visit(Op));
551
552 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
553 }
554
555 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
556 SmallVector<const SCEV *, 5> NewOps;
557 for (const SCEV *Op : Expr->operands())
558 NewOps.push_back(visit(Op));
559
560 return SE.getAddExpr(NewOps);
561 }
562
563 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
564 SmallVector<const SCEV *, 5> NewOps;
565 for (const SCEV *Op : Expr->operands())
566 NewOps.push_back(visit(Op));
567
568 return SE.getMulExpr(NewOps);
569 }
570
571private:
572 ScalarEvolution &SE;
573 std::vector<const SCEV *> *Terms;
574};
575
Tobias Grosserd68ba422015-11-24 05:00:36 +0000576SmallVector<const SCEV *, 4>
577ScopDetection::getDelinearizationTerms(DetectionContext &Context,
578 const SCEVUnknown *BasePointer) const {
579 SmallVector<const SCEV *, 4> Terms;
580 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000581 std::vector<const SCEV *> MaxTerms;
582 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
583 if (MaxTerms.size() > 0) {
584 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
585 continue;
586 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000587 // In case the outermost expression is a plain add, we check if any of its
588 // terms has the form 4 * %inst * %param * %param ..., aka a term that
589 // contains a product between a parameter and an instruction that is
590 // inside the scop. Such instructions, if allowed at all, are instructions
591 // SCEV can not represent, but Polly is still looking through. As a
592 // result, these instructions can depend on induction variables and are
593 // most likely no array sizes. However, terms that are multiplied with
594 // them are likely candidates for array sizes.
595 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
596 for (auto Op : AF->operands()) {
597 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
598 SE->collectParametricTerms(AF2, Terms);
599 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
600 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000601
Tobias Grosserd68ba422015-11-24 05:00:36 +0000602 for (auto *MulOp : AF2->operands()) {
603 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
604 Operands.push_back(Const);
605 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
606 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
607 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000608 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000609
610 } else {
611 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000612 }
613 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000614 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000615 if (Operands.size())
616 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000617 }
618 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000619 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000620 if (Terms.empty())
621 SE->collectParametricTerms(Pair.second, Terms);
622 }
623 return Terms;
624}
Sebastian Pope8863b82014-05-12 19:02:02 +0000625
Tobias Grosserd68ba422015-11-24 05:00:36 +0000626bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
627 SmallVectorImpl<const SCEV *> &Sizes,
628 const SCEVUnknown *BasePointer) const {
629 Value *BaseValue = BasePointer->getValue();
630 Region &CurRegion = Context.CurRegion;
631 for (const SCEV *DelinearizedSize : Sizes) {
632 if (!isAffine(DelinearizedSize, Context, nullptr)) {
633 Sizes.clear();
634 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000635 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000636 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
637 auto *V = dyn_cast<Value>(Unknown->getValue());
638 if (auto *Load = dyn_cast<LoadInst>(V)) {
639 if (Context.CurRegion.contains(Load) &&
640 isHoistableLoad(Load, CurRegion, *LI, *SE))
641 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000642 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000643 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000644 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000645 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
646 invalid<ReportNonAffineAccess>(
647 Context, /*Assert=*/true, DelinearizedSize,
648 Context.Accesses[BasePointer].front().first, BaseValue);
649 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000650
Tobias Grosserd68ba422015-11-24 05:00:36 +0000651 // No array shape derived.
652 if (Sizes.empty()) {
653 if (AllowNonAffine)
654 return true;
655
Tobias Grosser230acc42014-09-13 14:47:55 +0000656 for (const auto &Pair : Context.Accesses[BasePointer]) {
657 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000658 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000659
Tobias Grosserd68ba422015-11-24 05:00:36 +0000660 if (!isAffine(AF, Context, BaseValue)) {
661 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
662 BaseValue);
663 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000664 return false;
665 }
666 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000667 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000668 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000669 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000670}
671
Tobias Grosserd68ba422015-11-24 05:00:36 +0000672// We first store the resulting memory accesses in TempMemoryAccesses. Only
673// if the access functions for all memory accesses have been successfully
674// delinearized we continue. Otherwise, we either report a failure or, if
675// non-affine accesses are allowed, we drop the information. In case the
676// information is dropped the memory accesses need to be overapproximated
677// when translated to a polyhedral representation.
678bool ScopDetection::computeAccessFunctions(
679 DetectionContext &Context, const SCEVUnknown *BasePointer,
680 std::shared_ptr<ArrayShape> Shape) const {
681 Value *BaseValue = BasePointer->getValue();
682 bool BasePtrHasNonAffine = false;
683 MapInsnToMemAcc TempMemoryAccesses;
684 for (const auto &Pair : Context.Accesses[BasePointer]) {
685 const Instruction *Insn = Pair.first;
686 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000687 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000688 bool IsNonAffine = false;
689 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
690 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
691
692 if (!AF) {
693 if (isAffine(Pair.second, Context, BaseValue))
694 Acc->DelinearizedSubscripts.push_back(Pair.second);
695 else
696 IsNonAffine = true;
697 } else {
698 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
699 Shape->DelinearizedSizes);
700 if (Acc->DelinearizedSubscripts.size() == 0)
701 IsNonAffine = true;
702 for (const SCEV *S : Acc->DelinearizedSubscripts)
703 if (!isAffine(S, Context, BaseValue))
704 IsNonAffine = true;
705 }
706
707 // (Possibly) report non affine access
708 if (IsNonAffine) {
709 BasePtrHasNonAffine = true;
710 if (!AllowNonAffine)
711 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
712 Insn, BaseValue);
713 if (!KeepGoing && !AllowNonAffine)
714 return false;
715 }
716 }
717
718 if (!BasePtrHasNonAffine)
719 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
720
721 return true;
722}
723
724bool ScopDetection::hasBaseAffineAccesses(
725 DetectionContext &Context, const SCEVUnknown *BasePointer) const {
726 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
727
728 auto Terms = getDelinearizationTerms(Context, BasePointer);
729
730 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
731 Context.ElementSize[BasePointer]);
732
733 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer))
734 return false;
735
736 return computeAccessFunctions(Context, BasePointer, Shape);
737}
738
739bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
740 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses)
741 if (!hasBaseAffineAccesses(Context, BasePointer)) {
742 if (KeepGoing)
743 continue;
744 else
745 return false;
746 }
747 return true;
748}
749
Tobias Grosser75805372011-04-29 06:27:02 +0000750bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
751 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000752 Region &CurRegion = Context.CurRegion;
753
Tobias Grossere5e171e2011-11-10 12:45:03 +0000754 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000755 Loop *L = LI->getLoopFor(Inst.getParent());
756 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000757 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000758 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000759
Tobias Grosserb8710b52011-11-10 12:44:50 +0000760 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
761
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000762 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000763 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000764
765 BaseValue = BasePointer->getValue();
766
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000767 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000768 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000769
Tobias Grosser458fb782014-01-28 12:58:58 +0000770 // Check that the base address of the access is invariant in the current
771 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000772 if (!isInvariant(*BaseValue, CurRegion))
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000773 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BaseValue,
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000774 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000775
Tobias Grosserb8710b52011-11-10 12:44:50 +0000776 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
777
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000778 const SCEV *Size = SE->getElementSize(&Inst);
779 if (Context.ElementSize.count(BasePointer)) {
780 if (Context.ElementSize[BasePointer] != Size)
781 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
782 &Inst, BaseValue);
783 } else {
784 Context.ElementSize[BasePointer] = Size;
785 }
786
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000787 bool isVariantInNonAffineLoop = false;
788 SetVector<const Loop *> Loops;
789 findLoops(AccessFunction, Loops);
790 for (const Loop *L : Loops)
791 if (Context.BoxedLoopsSet.count(L))
792 isVariantInNonAffineLoop = true;
793
794 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000795 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000796
Johannes Doerfert09e36972015-10-07 20:17:36 +0000797 if (!isAffine(AccessFunction, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000798 Context.NonAffineAccesses.insert(BasePointer);
799 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000800 if (isVariantInNonAffineLoop ||
Johannes Doerfert09e36972015-10-07 20:17:36 +0000801 !isAffine(AccessFunction, Context, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000802 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000803 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000804 }
Tobias Grosser75805372011-04-29 06:27:02 +0000805
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000806 // FIXME: Think about allowing IntToPtrInst
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000807 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
808 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000809
Tobias Grosser1eedb672014-09-24 21:04:29 +0000810 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000811 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000812
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000813 // Check if the base pointer of the memory access does alias with
814 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000815 AAMDNodes AATags;
816 Inst.getAAMetadata(AATags);
817 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000818 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000819
Tobias Grosser1eedb672014-09-24 21:04:29 +0000820 if (!AS.isMustAlias()) {
821 if (PollyUseRuntimeAliasChecks) {
822 bool CanBuildRunTimeCheck = true;
823 // The run-time alias check places code that involves the base pointer at
824 // the beginning of the SCoP. This breaks if the base pointer is defined
825 // inside the scop. Hence, we can only create a run-time check if we are
826 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000827 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000828 for (const auto &Ptr : AS) {
829 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000830 if (Inst && CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000831 auto *Load = dyn_cast<LoadInst>(Inst);
832 if (Load && isHoistableLoad(Load, CurRegion, *LI, *SE)) {
833 Context.RequiredILS.insert(Load);
834 continue;
835 }
836
Tobias Grosser1eedb672014-09-24 21:04:29 +0000837 CanBuildRunTimeCheck = false;
838 break;
839 }
840 }
841
842 if (CanBuildRunTimeCheck)
843 return true;
844 }
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000845 return invalid<ReportAlias>(Context, /*Assert=*/true, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000846 }
Tobias Grosser75805372011-04-29 06:27:02 +0000847
848 return true;
849}
850
Tobias Grosser75805372011-04-29 06:27:02 +0000851bool ScopDetection::isValidInstruction(Instruction &Inst,
852 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000853 for (auto &Op : Inst.operands()) {
854 auto *OpInst = dyn_cast<Instruction>(&Op);
855
856 if (!OpInst)
857 continue;
858
859 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
860 return false;
861 }
862
Tobias Grosser75805372011-04-29 06:27:02 +0000863 // We only check the call instruction but not invoke instruction.
864 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
865 if (isValidCallInst(*CI))
866 return true;
867
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000868 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000869 }
870
871 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000872 if (!isa<AllocaInst>(Inst))
873 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000874
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000875 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000876 }
877
878 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000879 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
880 Context.hasStores |= isa<StoreInst>(Inst);
881 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +0000882 if (auto *Load = dyn_cast<LoadInst>(&Inst))
883 if (!Load->isSimple())
884 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
885 &Inst);
886 if (auto *Store = dyn_cast<StoreInst>(&Inst))
887 if (!Store->isSimple())
888 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
889 &Inst);
890
Tobias Grosser75805372011-04-29 06:27:02 +0000891 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000892 }
Tobias Grosser75805372011-04-29 06:27:02 +0000893
894 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000895 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000896}
897
Johannes Doerfertd020b772015-08-27 06:53:52 +0000898bool ScopDetection::canUseISLTripCount(Loop *L,
899 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000900 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
901 // need to overapproximate it as a boxed loop.
902 SmallVector<BasicBlock *, 4> LoopControlBlocks;
903 L->getLoopLatches(LoopControlBlocks);
904 L->getExitingBlocks(LoopControlBlocks);
905 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000906 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000907 return false;
908 }
909
Johannes Doerfertd020b772015-08-27 06:53:52 +0000910 // We can use ISL to compute the trip count of L.
911 return true;
912}
913
Tobias Grosser75805372011-04-29 06:27:02 +0000914bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000915 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000916 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000917
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000918 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000919 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000920 while (R != &Context.CurRegion && !R->contains(L))
921 R = R->getParent();
922
923 if (addOverApproximatedRegion(R, Context))
924 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000925 }
Tobias Grosser75805372011-04-29 06:27:02 +0000926
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000927 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000928 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000929}
930
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000931/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000932/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000933static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000934 auto *TripCount = SE.getBackedgeTakenCount(L);
935
Johannes Doerfertf61df692015-10-04 14:56:08 +0000936 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000937 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000938 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
939 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
940 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000941
942 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000943 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000944
945 return count;
946}
947
Johannes Doerfertf61df692015-10-04 14:56:08 +0000948int ScopDetection::countBeneficialLoops(Region *R) const {
949 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000950
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000951 auto L = LI->getLoopFor(R->getEntry());
952 L = L ? R->outermostLoopInRegion(L) : nullptr;
953 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000954
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000955 auto SubLoops =
956 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
957
958 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000959 if (R->contains(SubLoop))
960 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000961
Johannes Doerfertf61df692015-10-04 14:56:08 +0000962 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000963}
964
Tobias Grosser75805372011-04-29 06:27:02 +0000965Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000966 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000967 std::unique_ptr<Region> LastValidRegion;
968 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000969
970 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
971
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000972 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000973 const auto &It = DetectionContextMap.insert(std::make_pair(
974 ExpandedRegion.get(),
975 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
976 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000977 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000978 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000979
Johannes Doerfert717b8662015-09-08 21:44:27 +0000980 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000981 // If the exit is valid check all blocks
982 // - if true, a valid region was found => store it + keep expanding
983 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +0000984 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
985 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000986 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000987 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000988
Tobias Grosserd7e58642013-04-10 06:55:45 +0000989 // Store this region, because it is the greatest valid (encountered so
990 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +0000991 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000992 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000993
994 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000995 ExpandedRegion =
996 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000997
998 } else {
999 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001000 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001001 ExpandedRegion =
1002 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001003 }
Tobias Grosser75805372011-04-29 06:27:02 +00001004 }
1005
Tobias Grosser378a9f22013-11-16 19:34:11 +00001006 DEBUG({
1007 if (LastValidRegion)
1008 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1009 else
1010 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1011 });
Tobias Grosser75805372011-04-29 06:27:02 +00001012
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001013 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001014}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001015static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001016 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001017 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001018 return false;
1019
1020 return true;
1021}
Tobias Grosser75805372011-04-29 06:27:02 +00001022
Johannes Doerferte46925f2015-10-01 10:59:14 +00001023unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001024 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001025 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001026 if (ValidRegions.count(SubRegion.get())) {
1027 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001028 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001029 } else
1030 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001031 }
1032 return Count;
1033}
1034
Johannes Doerferte46925f2015-10-01 10:59:14 +00001035void ScopDetection::removeCachedResults(const Region &R) {
1036 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001037 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001038}
1039
Tobias Grosser75805372011-04-29 06:27:02 +00001040void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001041 const auto &It = DetectionContextMap.insert(
1042 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1043 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001044
1045 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +00001046 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001047 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001048 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001049 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001050 RegionIsValid = isValidRegion(Context);
1051
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001052 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001053
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001054 if (PollyTrackFailures && HasErrors)
1055 RejectLogs.insert(std::make_pair(&R, Context.Log));
1056
Johannes Doerferte46925f2015-10-01 10:59:14 +00001057 if (HasErrors) {
1058 removeCachedResults(R);
1059 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001060 ++ValidRegion;
1061 ValidRegions.insert(&R);
1062 return;
1063 }
1064
David Blaikieb035f6d2014-04-15 18:45:27 +00001065 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001066 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001067
1068 // Try to expand regions.
1069 //
1070 // As the region tree normally only contains canonical regions, non canonical
1071 // regions that form a Scop are not found. Therefore, those non canonical
1072 // regions are checked by expanding the canonical ones.
1073
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001074 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001075
David Blaikieb035f6d2014-04-15 18:45:27 +00001076 for (auto &SubRegion : R)
1077 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001078
Tobias Grosser26108892014-04-02 20:18:19 +00001079 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001080 // Skip regions that had errors.
1081 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1082 if (HadErrors)
1083 continue;
1084
Tobias Grosser75805372011-04-29 06:27:02 +00001085 // Skip invalid regions. Regions may become invalid, if they are element of
1086 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001087 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001088 continue;
1089
1090 Region *ExpandedR = expandRegion(*CurrentRegion);
1091
1092 if (!ExpandedR)
1093 continue;
1094
1095 R.addSubRegion(ExpandedR, true);
1096 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001097 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001098
Tobias Grosser28a70c52014-01-29 19:05:30 +00001099 // Erase all (direct and indirect) children of ExpandedR from the valid
1100 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001101 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001102 }
1103}
1104
1105bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001106 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001107
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001108 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001109 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001110 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001111 return false;
1112 }
1113
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001114 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001115 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1116
1117 // Also check exception blocks (and possibly register them as non-affine
1118 // regions). Even though exception blocks are not modeled, we use them
1119 // to forward-propagate domain constraints during ScopInfo construction.
1120 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1121 return false;
1122
1123 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001124 continue;
1125
Tobias Grosser1d191902014-03-03 13:13:55 +00001126 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001127 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001128 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001129 }
Tobias Grosser75805372011-04-29 06:27:02 +00001130
Sebastian Pope8863b82014-05-12 19:02:02 +00001131 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001132 return false;
1133
Tobias Grosser75805372011-04-29 06:27:02 +00001134 return true;
1135}
1136
Tobias Grosser75805372011-04-29 06:27:02 +00001137bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001138 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001139
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001140 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001141
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001142 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001143 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001144 return false;
1145 }
1146
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001147 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001148 DEBUG({
1149 dbgs() << "Region entry does not match -polly-region-only";
1150 dbgs() << "\n";
1151 });
1152 return false;
1153 }
1154
Tobias Grosserd654c252012-04-10 18:12:19 +00001155 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001156 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001157 if (CurRegion.getEntry() ==
1158 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1159 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001160
Johannes Doerfertf61df692015-10-04 14:56:08 +00001161 int NumLoops = countBeneficialLoops(&CurRegion);
Tobias Grosser575aca82015-10-06 16:10:29 +00001162 if (!PollyProcessUnprofitable && NumLoops < 2)
Tobias Grossered21a1f2015-08-27 16:55:18 +00001163 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1164
Hongbin Zheng94868e62012-04-07 12:29:17 +00001165 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001166 return false;
1167
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001168 // We can probably not do a lot on scops that only write or only read
1169 // data.
Tobias Grosser575aca82015-10-06 16:10:29 +00001170 if (!PollyProcessUnprofitable && (!Context.hasStores || !Context.hasLoads))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001171 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001172
Johannes Doerfertf61df692015-10-04 14:56:08 +00001173 // Check if there are sufficent non-overapproximated loops.
1174 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser575aca82015-10-06 16:10:29 +00001175 if (!PollyProcessUnprofitable && NumAffineLoops < 2)
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001176 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1177
Tobias Grosser75805372011-04-29 06:27:02 +00001178 DEBUG(dbgs() << "OK\n");
1179 return true;
1180}
1181
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001182void ScopDetection::markFunctionAsInvalid(Function *F) const {
1183 F->addFnAttr(PollySkipFnAttr);
1184}
1185
Tobias Grosser75805372011-04-29 06:27:02 +00001186bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001187 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001188}
1189
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001190void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001191 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001192 unsigned LineEntry, LineExit;
1193 std::string FileName;
1194
Tobias Grosser00dc3092014-03-02 12:02:46 +00001195 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001196 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1197 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001198 }
1199}
1200
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001201void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001202 for (const Region *R : ValidRegions) {
1203 const Region *Parent = R->getParent();
1204 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1205 emitRejectionRemarks(F, RejectLogs.at(Parent));
1206 }
1207}
1208
1209void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1210 const Region *R) {
1211 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001212 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001213 if (IsValid)
1214 continue;
1215
1216 bool IsLeaf = Child->begin() == Child->end();
1217 if (!IsLeaf)
1218 emitMissedRemarksForLeaves(F, Child.get());
1219 else {
1220 if (RejectLogs.count(Child.get())) {
1221 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1222 }
1223 }
1224 }
1225}
1226
Tobias Grosser75805372011-04-29 06:27:02 +00001227bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001228 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001229 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001230 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001231 return false;
1232
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001233 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001234 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001235 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001236 Region *TopRegion = RI->getTopLevelRegion();
1237
Tobias Grosser2ff87232011-10-23 11:17:06 +00001238 releaseMemory();
1239
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001240 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001241 return false;
1242
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001243 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001244 return false;
1245
1246 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001247
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001248 // Only makes sense when we tracked errors.
1249 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001250 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001251 emitMissedRemarksForLeaves(F, TopRegion);
1252 }
1253
Johannes Doerferta05214f2014-10-15 23:24:28 +00001254 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001255 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001256
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001257 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001258 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001259 return false;
1260}
1261
Johannes Doerfertba65c162015-02-24 11:45:21 +00001262bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1263 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001264 const DetectionContext *DC = getDetectionContext(ScopR);
1265 assert(DC && "ScopR is no valid region!");
1266 return DC->NonAffineSubRegionSet.count(SubR);
1267}
1268
1269const ScopDetection::DetectionContext *
1270ScopDetection::getDetectionContext(const Region *R) const {
1271 auto DCMIt = DetectionContextMap.find(R);
1272 if (DCMIt == DetectionContextMap.end())
1273 return nullptr;
1274 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001275}
1276
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001277const ScopDetection::BoxedLoopsSetTy *
1278ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001279 const DetectionContext *DC = getDetectionContext(R);
1280 assert(DC && "ScopR is no valid region!");
1281 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001282}
1283
Johannes Doerfert09e36972015-10-07 20:17:36 +00001284const InvariantLoadsSetTy *
1285ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001286 const DetectionContext *DC = getDetectionContext(R);
1287 assert(DC && "ScopR is no valid region!");
1288 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001289}
1290
Tobias Grosser75805372011-04-29 06:27:02 +00001291void polly::ScopDetection::verifyRegion(const Region &R) const {
1292 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001293
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001294 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001295 isValidRegion(Context);
1296}
1297
1298void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001299 if (!VerifyScops)
1300 return;
1301
Tobias Grosser26108892014-04-02 20:18:19 +00001302 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001303 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001304}
1305
1306void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001307 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001308 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001309 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001310 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001311 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001312 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001313 AU.setPreservesAll();
1314}
1315
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001316void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001317 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001318 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001319
1320 OS << "\n";
1321}
1322
1323void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001324 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001325 ValidRegions.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001326 InsnToMemAcc.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001327 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001328
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001329 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001330}
1331
1332char ScopDetection::ID = 0;
1333
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001334Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1335
Tobias Grosser73600b82011-10-08 00:30:40 +00001336INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1337 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001338 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001339INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001340INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001341INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001342INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001343INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001344INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1345 "Polly - Detect static control parts (SCoPs)", false, false)