blob: 7e8075d831576f3e9bd22d63e9e89c84fd4145f2 [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 Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000050#include "polly/Options.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 Grosserc1a269b2015-12-21 21:00:43 +000074// This option is set to a very high value, as analyzing such loops increases
75// compile time on several cases. For experiments that enable this option,
76// a value of around 40 has been working to avoid run-time regressions with
77// Polly while still exposing interesting optimization opportunities.
78static cl::opt<int> ProfitabilityMinPerLoopInstructions(
79 "polly-detect-profitability-min-per-loop-insts",
80 cl::desc("The minimal number of per-loop instructions before a single loop "
81 "region is considered profitable"),
82 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
83
Tobias Grosser575aca82015-10-06 16:10:29 +000084bool polly::PollyProcessUnprofitable;
85static cl::opt<bool, true> XPollyProcessUnprofitable(
86 "polly-process-unprofitable",
87 cl::desc(
88 "Process scops that are unlikely to benefit from Polly optimizations."),
89 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
90 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000091
Tobias Grosser483a90d2014-07-09 10:50:10 +000092static cl::opt<std::string> OnlyFunction(
93 "polly-only-func",
94 cl::desc("Only run on functions that contain a certain string"),
95 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
96 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000097
Tobias Grosser483a90d2014-07-09 10:50:10 +000098static cl::opt<std::string> OnlyRegion(
99 "polly-only-region",
100 cl::desc("Only run on certain regions (The provided identifier must "
101 "appear in the name of the region's entry block"),
102 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
103 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000104
Tobias Grosser60cd9322011-11-10 12:47:26 +0000105static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000106 IgnoreAliasing("polly-ignore-aliasing",
107 cl::desc("Ignore possible aliasing of the array bases"),
108 cl::Hidden, cl::init(false), cl::ZeroOrMore,
109 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000110
Johannes Doerfertb164c792014-09-18 11:17:17 +0000111bool polly::PollyUseRuntimeAliasChecks;
112static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
113 "polly-use-runtime-alias-checks",
114 cl::desc("Use runtime alias checks to resolve possible aliasing."),
115 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
116 cl::init(true), cl::cat(PollyCategory));
117
Tobias Grosser637bd632013-05-07 07:31:10 +0000118static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000119 ReportLevel("polly-report",
120 cl::desc("Print information about the activities of Polly"),
121 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000122
123static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000124 AllowNonAffine("polly-allow-nonaffine",
125 cl::desc("Allow non affine access functions in arrays"),
126 cl::Hidden, cl::init(false), cl::ZeroOrMore,
127 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000128
Johannes Doerfertba65c162015-02-24 11:45:21 +0000129static cl::opt<bool> AllowNonAffineSubRegions(
130 "polly-allow-nonaffine-branches",
131 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000132 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000133
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000134static cl::opt<bool>
135 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
136 cl::desc("Allow non affine conditions for loops"),
137 cl::Hidden, cl::init(false), cl::ZeroOrMore,
138 cl::cat(PollyCategory));
139
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000140static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
141 cl::desc("Allow unsigned expressions"),
142 cl::Hidden, cl::init(false), cl::ZeroOrMore,
143 cl::cat(PollyCategory));
144
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000145static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000146 TrackFailures("polly-detect-track-failures",
147 cl::desc("Track failure strings in detecting scop regions"),
148 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000149 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000150
Andreas Simbuerger04472402014-05-24 09:25:10 +0000151static cl::opt<bool> KeepGoing("polly-detect-keep-going",
152 cl::desc("Do not fail on the first error."),
153 cl::Hidden, cl::ZeroOrMore, cl::init(false),
154 cl::cat(PollyCategory));
155
Sebastian Pop18016682014-04-08 21:20:44 +0000156static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000157 PollyDelinearizeX("polly-delinearize",
158 cl::desc("Delinearize array access functions"),
159 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000160 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000161
Tobias Grossera1689932014-02-18 18:49:49 +0000162static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000163 VerifyScops("polly-detect-verify",
164 cl::desc("Verify the detected SCoPs after each transformation"),
165 cl::Hidden, cl::init(false), cl::ZeroOrMore,
166 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000167
Johannes Doerferte526de52015-09-21 19:10:11 +0000168/// @brief The minimal trip count under which loops are considered unprofitable.
169static const unsigned MIN_LOOP_TRIP_COUNT = 8;
170
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000171bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000172bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000173StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000174
Tobias Grosser75805372011-04-29 06:27:02 +0000175//===----------------------------------------------------------------------===//
176// Statistics.
177
178STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
179
Tobias Grosser8519f892013-12-18 10:49:53 +0000180class DiagnosticScopFound : public DiagnosticInfo {
181private:
182 static int PluginDiagnosticKind;
183
184 Function &F;
185 std::string FileName;
186 unsigned EntryLine, ExitLine;
187
188public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000189 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
190 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000191 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000192 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000193
194 virtual void print(DiagnosticPrinter &DP) const;
195
196 static bool classof(const DiagnosticInfo *DI) {
197 return DI->getKind() == PluginDiagnosticKind;
198 }
199};
200
201int DiagnosticScopFound::PluginDiagnosticKind = 10;
202
Tobias Grosser8519f892013-12-18 10:49:53 +0000203void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000204 DP << "Polly detected an optimizable loop region (scop) in function '" << F
205 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000206
207 if (FileName.empty()) {
208 DP << "Scop location is unknown. Compile with debug info "
209 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000210 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000211 }
212
213 DP << FileName << ":" << EntryLine << ": Start of scop\n";
214 DP << FileName << ":" << ExitLine << ": End of scop";
215}
216
Tobias Grosser75805372011-04-29 06:27:02 +0000217//===----------------------------------------------------------------------===//
218// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000219
Johannes Doerfertb164c792014-09-18 11:17:17 +0000220ScopDetection::ScopDetection() : FunctionPass(ID) {
221 if (!PollyUseRuntimeAliasChecks)
222 return;
223
Johannes Doerfert928229f2014-09-29 17:06:29 +0000224 // Disable runtime alias checks if we ignore aliasing all together.
225 if (IgnoreAliasing) {
226 PollyUseRuntimeAliasChecks = false;
227 return;
228 }
229
Johannes Doerfertb164c792014-09-18 11:17:17 +0000230 if (AllowNonAffine) {
231 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
232 "accesses are enabled.\n");
233 PollyUseRuntimeAliasChecks = false;
234 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000235}
236
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000237template <class RR, typename... Args>
238inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
239 Args &&... Arguments) const {
240
241 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000242 RejectLog &Log = Context.Log;
243 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000244
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000245 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000246 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000247
248 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000249 DEBUG(dbgs() << "\n");
250 } else {
251 assert(!Assert && "Verification of detected scop failed");
252 }
253
254 return false;
255}
256
Tobias Grossera1689932014-02-18 18:49:49 +0000257bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
258 if (!ValidRegions.count(&R))
259 return false;
260
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000261 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000262 DetectionContextMap.erase(&R);
263 const auto &It = DetectionContextMap.insert(
264 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
265 false /*verifying*/)));
266 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000267 return isValidRegion(Context);
268 }
Tobias Grossera1689932014-02-18 18:49:49 +0000269
270 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000271}
272
Tobias Grosser4f129a62011-10-08 00:30:55 +0000273std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000274 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000275 return "";
276
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000277 // Get the first error we found. Even in keep-going mode, this is the first
278 // reason that caused the candidate to be rejected.
279 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000280
281 // This can happen when we marked a region invalid, but didn't track
282 // an error for it.
283 if (Errors.size() == 0)
284 return "";
285
286 RejectReasonPtr RR = *Errors.begin();
287 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000288}
289
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000290bool ScopDetection::addOverApproximatedRegion(Region *AR,
291 DetectionContext &Context) const {
292
293 // If we already know about Ar we can exit.
294 if (!Context.NonAffineSubRegionSet.insert(AR))
295 return true;
296
297 // All loops in the region have to be overapproximated too if there
298 // are accesses that depend on the iteration count.
299 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000300 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000301 if (AR->contains(L))
302 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000303 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000304
305 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000306}
307
Johannes Doerfert09e36972015-10-07 20:17:36 +0000308bool ScopDetection::onlyValidRequiredInvariantLoads(
309 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
310 Region &CurRegion = Context.CurRegion;
311
312 for (LoadInst *Load : RequiredILS)
313 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
314 return false;
315
316 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
317
318 return true;
319}
320
321bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
322 Value *BaseAddress) const {
323
324 InvariantLoadsSetTy AccessILS;
325 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
326 return false;
327
328 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
329 return false;
330
331 return true;
332}
333
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000334bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000335 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000336 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000337 Loop *L = LI->getLoopFor(&BB);
338 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000339
Johannes Doerfert09e36972015-10-07 20:17:36 +0000340 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000341 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000342
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000343 if (!IsLoopBranch && AllowNonAffineSubRegions &&
344 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
345 return true;
346
347 if (IsLoopBranch)
348 return false;
349
350 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
351 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000352}
353
354bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000355 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000356 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000357
358 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
359 auto Opcode = BinOp->getOpcode();
360 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
361 Value *Op0 = BinOp->getOperand(0);
362 Value *Op1 = BinOp->getOperand(1);
363 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
364 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
365 }
366 }
367
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000368 // Non constant conditions of branches need to be ICmpInst.
369 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000370 if (!IsLoopBranch && AllowNonAffineSubRegions &&
371 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
372 return true;
373 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000374 }
Tobias Grosser75805372011-04-29 06:27:02 +0000375
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000376 ICmpInst *ICmp = cast<ICmpInst>(Condition);
377 // Unsigned comparisons are not allowed. They trigger overflow problems
378 // in the code generation.
379 //
380 // TODO: This is not sufficient and just hides bugs. However it does pretty
381 // well.
382 if (ICmp->isUnsigned() && !AllowUnsigned)
383 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000384
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000385 // Are both operands of the ICmp affine?
386 if (isa<UndefValue>(ICmp->getOperand(0)) ||
387 isa<UndefValue>(ICmp->getOperand(1)))
388 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000389
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000390 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
391 // for arbitrary pointer expressions at the moment. Until
392 // this is fixed we disallow pointer expressions completely.
393 if (ICmp->getOperand(0)->getType()->isPointerTy())
394 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000395
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000396 Loop *L = LI->getLoopFor(ICmp->getParent());
397 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
398 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000399
Johannes Doerfert09e36972015-10-07 20:17:36 +0000400 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000401 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000402
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000403 if (!IsLoopBranch && AllowNonAffineSubRegions &&
404 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
405 return true;
406
407 if (IsLoopBranch)
408 return false;
409
410 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
411 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000412}
413
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000414bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000415 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000416 DetectionContext &Context) const {
417 Region &CurRegion = Context.CurRegion;
418
419 TerminatorInst *TI = BB.getTerminator();
420
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000421 if (AllowUnreachable && isa<UnreachableInst>(TI))
422 return true;
423
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000424 // Return instructions are only valid if the region is the top level region.
425 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
426 return true;
427
428 Value *Condition = getConditionFromTerminator(TI);
429
430 if (!Condition)
431 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
432
433 // UndefValue is not allowed as condition.
434 if (isa<UndefValue>(Condition))
435 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
436
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000437 // Constant integer conditions are always affine.
438 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000439 return true;
440
441 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000442 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000443
444 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
445 assert(SI && "Terminator was neither branch nor switch");
446
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000447 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000448}
449
Tobias Grosser75805372011-04-29 06:27:02 +0000450bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000451 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000452 return false;
453
454 if (CI.doesNotAccessMemory())
455 return true;
456
457 Function *CalledFunction = CI.getCalledFunction();
458
459 // Indirect calls are not supported.
460 if (CalledFunction == 0)
461 return false;
462
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000463 if (isIgnoredIntrinsic(&CI))
464 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000465
Tobias Grosser75805372011-04-29 06:27:02 +0000466 return false;
467}
468
Tobias Grosser458fb782014-01-28 12:58:58 +0000469bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
470 // A reference to function argument or constant value is invariant.
471 if (isa<Argument>(Val) || isa<Constant>(Val))
472 return true;
473
474 const Instruction *I = dyn_cast<Instruction>(&Val);
475 if (!I)
476 return false;
477
478 if (!Reg.contains(I))
479 return true;
480
481 if (I->mayHaveSideEffects())
482 return false;
483
484 // When Val is a Phi node, it is likely not invariant. We do not check whether
485 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
486 // invariant. Recursively checking the operators of Phi nodes would lead to
487 // infinite recursion.
488 if (isa<PHINode>(*I))
489 return false;
490
Tobias Grosser26108892014-04-02 20:18:19 +0000491 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000492 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000493 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000494
Tobias Grosser458fb782014-01-28 12:58:58 +0000495 return true;
496}
497
Sebastian Pop422e33f2014-06-03 18:16:31 +0000498MapInsnToMemAcc InsnToMemAcc;
499
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000500/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
501/// register the '...' components.
502///
503/// Array access expressions as they are generated by gfortran contain smax(0,
504/// size) expressions that confuse the 'normal' delinearization algorithm.
505/// However, if we extract such expressions before the normal delinearization
506/// takes place they can actually help to identify array size expressions in
507/// fortran accesses. For the subsequently following delinearization the smax(0,
508/// size) component can be replaced by just 'size'. This is correct as we will
509/// always add and verify the assumption that for all subscript expressions
510/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
511/// that 0 <= size, which means smax(0, size) == size.
512struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
513public:
514 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
515 std::vector<const SCEV *> *Terms = nullptr) {
516
517 SCEVRemoveMax D(SE, Terms);
518 return D.visit(Expr);
519 }
520
521 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
522 : SE(SE), Terms(Terms) {}
523
524 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
525
526 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
527 return Expr;
528 }
529
530 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
531 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
532 }
533
534 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
535
536 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000537 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000538 auto Res = visit(Expr->getOperand(1));
539 if (Terms)
540 (*Terms).push_back(Res);
541 return Res;
542 }
543
544 return Expr;
545 }
546
Roman Gareev8aa43752015-12-17 20:37:17 +0000547 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000548
549 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
550
551 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
552 return Expr;
553 }
554
555 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
556
557 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
558 SmallVector<const SCEV *, 5> NewOps;
559 for (const SCEV *Op : Expr->operands())
560 NewOps.push_back(visit(Op));
561
562 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
563 }
564
565 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
566 SmallVector<const SCEV *, 5> NewOps;
567 for (const SCEV *Op : Expr->operands())
568 NewOps.push_back(visit(Op));
569
570 return SE.getAddExpr(NewOps);
571 }
572
573 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
574 SmallVector<const SCEV *, 5> NewOps;
575 for (const SCEV *Op : Expr->operands())
576 NewOps.push_back(visit(Op));
577
578 return SE.getMulExpr(NewOps);
579 }
580
581private:
582 ScalarEvolution &SE;
583 std::vector<const SCEV *> *Terms;
584};
585
Tobias Grosserd68ba422015-11-24 05:00:36 +0000586SmallVector<const SCEV *, 4>
587ScopDetection::getDelinearizationTerms(DetectionContext &Context,
588 const SCEVUnknown *BasePointer) const {
589 SmallVector<const SCEV *, 4> Terms;
590 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000591 std::vector<const SCEV *> MaxTerms;
592 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
593 if (MaxTerms.size() > 0) {
594 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
595 continue;
596 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000597 // In case the outermost expression is a plain add, we check if any of its
598 // terms has the form 4 * %inst * %param * %param ..., aka a term that
599 // contains a product between a parameter and an instruction that is
600 // inside the scop. Such instructions, if allowed at all, are instructions
601 // SCEV can not represent, but Polly is still looking through. As a
602 // result, these instructions can depend on induction variables and are
603 // most likely no array sizes. However, terms that are multiplied with
604 // them are likely candidates for array sizes.
605 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
606 for (auto Op : AF->operands()) {
607 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
608 SE->collectParametricTerms(AF2, Terms);
609 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
610 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000611
Tobias Grosserd68ba422015-11-24 05:00:36 +0000612 for (auto *MulOp : AF2->operands()) {
613 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
614 Operands.push_back(Const);
615 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
616 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
617 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000618 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000619
620 } else {
621 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000622 }
623 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000624 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000625 if (Operands.size())
626 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000627 }
628 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000629 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000630 if (Terms.empty())
631 SE->collectParametricTerms(Pair.second, Terms);
632 }
633 return Terms;
634}
Sebastian Pope8863b82014-05-12 19:02:02 +0000635
Tobias Grosserd68ba422015-11-24 05:00:36 +0000636bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
637 SmallVectorImpl<const SCEV *> &Sizes,
638 const SCEVUnknown *BasePointer) const {
639 Value *BaseValue = BasePointer->getValue();
640 Region &CurRegion = Context.CurRegion;
641 for (const SCEV *DelinearizedSize : Sizes) {
642 if (!isAffine(DelinearizedSize, Context, nullptr)) {
643 Sizes.clear();
644 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000645 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000646 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
647 auto *V = dyn_cast<Value>(Unknown->getValue());
648 if (auto *Load = dyn_cast<LoadInst>(V)) {
649 if (Context.CurRegion.contains(Load) &&
650 isHoistableLoad(Load, CurRegion, *LI, *SE))
651 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000652 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000653 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000654 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000655 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000656 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000657 Context, /*Assert=*/true, DelinearizedSize,
658 Context.Accesses[BasePointer].front().first, BaseValue);
659 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000660
Tobias Grosserd68ba422015-11-24 05:00:36 +0000661 // No array shape derived.
662 if (Sizes.empty()) {
663 if (AllowNonAffine)
664 return true;
665
Tobias Grosser230acc42014-09-13 14:47:55 +0000666 for (const auto &Pair : Context.Accesses[BasePointer]) {
667 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000668 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000669
Tobias Grosserd68ba422015-11-24 05:00:36 +0000670 if (!isAffine(AF, Context, BaseValue)) {
671 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
672 BaseValue);
673 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000674 return false;
675 }
676 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000677 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000678 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000679 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000680}
681
Tobias Grosserd68ba422015-11-24 05:00:36 +0000682// We first store the resulting memory accesses in TempMemoryAccesses. Only
683// if the access functions for all memory accesses have been successfully
684// delinearized we continue. Otherwise, we either report a failure or, if
685// non-affine accesses are allowed, we drop the information. In case the
686// information is dropped the memory accesses need to be overapproximated
687// when translated to a polyhedral representation.
688bool ScopDetection::computeAccessFunctions(
689 DetectionContext &Context, const SCEVUnknown *BasePointer,
690 std::shared_ptr<ArrayShape> Shape) const {
691 Value *BaseValue = BasePointer->getValue();
692 bool BasePtrHasNonAffine = false;
693 MapInsnToMemAcc TempMemoryAccesses;
694 for (const auto &Pair : Context.Accesses[BasePointer]) {
695 const Instruction *Insn = Pair.first;
696 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000697 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000698 bool IsNonAffine = false;
699 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
700 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
701
702 if (!AF) {
703 if (isAffine(Pair.second, Context, BaseValue))
704 Acc->DelinearizedSubscripts.push_back(Pair.second);
705 else
706 IsNonAffine = true;
707 } else {
708 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
709 Shape->DelinearizedSizes);
710 if (Acc->DelinearizedSubscripts.size() == 0)
711 IsNonAffine = true;
712 for (const SCEV *S : Acc->DelinearizedSubscripts)
713 if (!isAffine(S, Context, BaseValue))
714 IsNonAffine = true;
715 }
716
717 // (Possibly) report non affine access
718 if (IsNonAffine) {
719 BasePtrHasNonAffine = true;
720 if (!AllowNonAffine)
721 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
722 Insn, BaseValue);
723 if (!KeepGoing && !AllowNonAffine)
724 return false;
725 }
726 }
727
728 if (!BasePtrHasNonAffine)
729 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
730
731 return true;
732}
733
734bool ScopDetection::hasBaseAffineAccesses(
735 DetectionContext &Context, const SCEVUnknown *BasePointer) const {
736 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
737
738 auto Terms = getDelinearizationTerms(Context, BasePointer);
739
740 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
741 Context.ElementSize[BasePointer]);
742
743 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer))
744 return false;
745
746 return computeAccessFunctions(Context, BasePointer, Shape);
747}
748
749bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
750 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses)
751 if (!hasBaseAffineAccesses(Context, BasePointer)) {
752 if (KeepGoing)
753 continue;
754 else
755 return false;
756 }
757 return true;
758}
759
Tobias Grosser75805372011-04-29 06:27:02 +0000760bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
761 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000762 Region &CurRegion = Context.CurRegion;
763
Tobias Grossere5e171e2011-11-10 12:45:03 +0000764 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000765 Loop *L = LI->getLoopFor(Inst.getParent());
766 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000767 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000768 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000769
Tobias Grosserb8710b52011-11-10 12:44:50 +0000770 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
771
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000772 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000773 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000774
775 BaseValue = BasePointer->getValue();
776
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000777 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000778 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000779
Tobias Grosser458fb782014-01-28 12:58:58 +0000780 // Check that the base address of the access is invariant in the current
781 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000782 if (!isInvariant(*BaseValue, CurRegion))
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000783 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BaseValue,
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000784 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000785
Tobias Grosserb8710b52011-11-10 12:44:50 +0000786 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
787
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000788 const SCEV *Size = SE->getElementSize(&Inst);
789 if (Context.ElementSize.count(BasePointer)) {
790 if (Context.ElementSize[BasePointer] != Size)
791 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
792 &Inst, BaseValue);
793 } else {
794 Context.ElementSize[BasePointer] = Size;
795 }
796
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000797 bool isVariantInNonAffineLoop = false;
798 SetVector<const Loop *> Loops;
799 findLoops(AccessFunction, Loops);
800 for (const Loop *L : Loops)
801 if (Context.BoxedLoopsSet.count(L))
802 isVariantInNonAffineLoop = true;
803
804 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000805 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000806
Johannes Doerfert09e36972015-10-07 20:17:36 +0000807 if (!isAffine(AccessFunction, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000808 Context.NonAffineAccesses.insert(BasePointer);
809 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000810 if (isVariantInNonAffineLoop ||
Johannes Doerfert09e36972015-10-07 20:17:36 +0000811 !isAffine(AccessFunction, Context, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000812 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000813 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000814 }
Tobias Grosser75805372011-04-29 06:27:02 +0000815
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000816 // FIXME: Think about allowing IntToPtrInst
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000817 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
818 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000819
Tobias Grosser1eedb672014-09-24 21:04:29 +0000820 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000821 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000822
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000823 // Check if the base pointer of the memory access does alias with
824 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000825 AAMDNodes AATags;
826 Inst.getAAMetadata(AATags);
827 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000828 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000829
Tobias Grosser1eedb672014-09-24 21:04:29 +0000830 if (!AS.isMustAlias()) {
831 if (PollyUseRuntimeAliasChecks) {
832 bool CanBuildRunTimeCheck = true;
833 // The run-time alias check places code that involves the base pointer at
834 // the beginning of the SCoP. This breaks if the base pointer is defined
835 // inside the scop. Hence, we can only create a run-time check if we are
836 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000837 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000838 for (const auto &Ptr : AS) {
839 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000840 if (Inst && CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000841 auto *Load = dyn_cast<LoadInst>(Inst);
842 if (Load && isHoistableLoad(Load, CurRegion, *LI, *SE)) {
843 Context.RequiredILS.insert(Load);
844 continue;
845 }
846
Tobias Grosser1eedb672014-09-24 21:04:29 +0000847 CanBuildRunTimeCheck = false;
848 break;
849 }
850 }
851
852 if (CanBuildRunTimeCheck)
853 return true;
854 }
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000855 return invalid<ReportAlias>(Context, /*Assert=*/true, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000856 }
Tobias Grosser75805372011-04-29 06:27:02 +0000857
858 return true;
859}
860
Tobias Grosser75805372011-04-29 06:27:02 +0000861bool ScopDetection::isValidInstruction(Instruction &Inst,
862 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000863 for (auto &Op : Inst.operands()) {
864 auto *OpInst = dyn_cast<Instruction>(&Op);
865
866 if (!OpInst)
867 continue;
868
869 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
870 return false;
871 }
872
Tobias Grosser75805372011-04-29 06:27:02 +0000873 // We only check the call instruction but not invoke instruction.
874 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
875 if (isValidCallInst(*CI))
876 return true;
877
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000878 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000879 }
880
881 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000882 if (!isa<AllocaInst>(Inst))
883 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000884
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000885 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000886 }
887
888 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000889 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
890 Context.hasStores |= isa<StoreInst>(Inst);
891 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +0000892 if (auto *Load = dyn_cast<LoadInst>(&Inst))
893 if (!Load->isSimple())
894 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
895 &Inst);
896 if (auto *Store = dyn_cast<StoreInst>(&Inst))
897 if (!Store->isSimple())
898 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
899 &Inst);
900
Tobias Grosser75805372011-04-29 06:27:02 +0000901 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000902 }
Tobias Grosser75805372011-04-29 06:27:02 +0000903
904 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000905 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000906}
907
Johannes Doerfertd020b772015-08-27 06:53:52 +0000908bool ScopDetection::canUseISLTripCount(Loop *L,
909 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000910 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
911 // need to overapproximate it as a boxed loop.
912 SmallVector<BasicBlock *, 4> LoopControlBlocks;
913 L->getLoopLatches(LoopControlBlocks);
914 L->getExitingBlocks(LoopControlBlocks);
915 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000916 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000917 return false;
918 }
919
Johannes Doerfertd020b772015-08-27 06:53:52 +0000920 // We can use ISL to compute the trip count of L.
921 return true;
922}
923
Tobias Grosser75805372011-04-29 06:27:02 +0000924bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000925 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000926 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000927
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000928 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000929 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000930 while (R != &Context.CurRegion && !R->contains(L))
931 R = R->getParent();
932
933 if (addOverApproximatedRegion(R, Context))
934 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000935 }
Tobias Grosser75805372011-04-29 06:27:02 +0000936
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000937 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000938 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000939}
940
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000941/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000942/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000943static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000944 auto *TripCount = SE.getBackedgeTakenCount(L);
945
Johannes Doerfertf61df692015-10-04 14:56:08 +0000946 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000947 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000948 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
949 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
950 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000951
952 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000953 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000954
955 return count;
956}
957
Johannes Doerfertf61df692015-10-04 14:56:08 +0000958int ScopDetection::countBeneficialLoops(Region *R) const {
959 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000960
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000961 auto L = LI->getLoopFor(R->getEntry());
962 L = L ? R->outermostLoopInRegion(L) : nullptr;
963 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000964
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000965 auto SubLoops =
966 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
967
968 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000969 if (R->contains(SubLoop))
970 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000971
Johannes Doerfertf61df692015-10-04 14:56:08 +0000972 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000973}
974
Tobias Grosser75805372011-04-29 06:27:02 +0000975Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000976 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000977 std::unique_ptr<Region> LastValidRegion;
978 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000979
980 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
981
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000982 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000983 const auto &It = DetectionContextMap.insert(std::make_pair(
984 ExpandedRegion.get(),
985 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
986 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000987 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000988 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000989
Johannes Doerfert717b8662015-09-08 21:44:27 +0000990 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000991 // If the exit is valid check all blocks
992 // - if true, a valid region was found => store it + keep expanding
993 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +0000994 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
995 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000996 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000997 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000998
Tobias Grosserd7e58642013-04-10 06:55:45 +0000999 // Store this region, because it is the greatest valid (encountered so
1000 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001001 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001002 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001003
1004 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001005 ExpandedRegion =
1006 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001007
1008 } else {
1009 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001010 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001011 ExpandedRegion =
1012 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001013 }
Tobias Grosser75805372011-04-29 06:27:02 +00001014 }
1015
Tobias Grosser378a9f22013-11-16 19:34:11 +00001016 DEBUG({
1017 if (LastValidRegion)
1018 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1019 else
1020 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1021 });
Tobias Grosser75805372011-04-29 06:27:02 +00001022
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001023 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001024}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001025static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001026 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001027 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001028 return false;
1029
1030 return true;
1031}
Tobias Grosser75805372011-04-29 06:27:02 +00001032
Johannes Doerferte46925f2015-10-01 10:59:14 +00001033unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001034 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001035 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001036 if (ValidRegions.count(SubRegion.get())) {
1037 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001038 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001039 } else
1040 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001041 }
1042 return Count;
1043}
1044
Johannes Doerferte46925f2015-10-01 10:59:14 +00001045void ScopDetection::removeCachedResults(const Region &R) {
1046 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001047 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001048}
1049
Tobias Grosser75805372011-04-29 06:27:02 +00001050void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001051 const auto &It = DetectionContextMap.insert(
1052 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1053 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001054
1055 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +00001056 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001057 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001058 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001059 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001060 RegionIsValid = isValidRegion(Context);
1061
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001062 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001063
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001064 if (PollyTrackFailures && HasErrors)
1065 RejectLogs.insert(std::make_pair(&R, Context.Log));
1066
Johannes Doerferte46925f2015-10-01 10:59:14 +00001067 if (HasErrors) {
1068 removeCachedResults(R);
1069 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001070 ++ValidRegion;
1071 ValidRegions.insert(&R);
1072 return;
1073 }
1074
David Blaikieb035f6d2014-04-15 18:45:27 +00001075 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001076 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001077
1078 // Try to expand regions.
1079 //
1080 // As the region tree normally only contains canonical regions, non canonical
1081 // regions that form a Scop are not found. Therefore, those non canonical
1082 // regions are checked by expanding the canonical ones.
1083
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001084 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001085
David Blaikieb035f6d2014-04-15 18:45:27 +00001086 for (auto &SubRegion : R)
1087 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001088
Tobias Grosser26108892014-04-02 20:18:19 +00001089 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001090 // Skip regions that had errors.
1091 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1092 if (HadErrors)
1093 continue;
1094
Tobias Grosser75805372011-04-29 06:27:02 +00001095 // Skip invalid regions. Regions may become invalid, if they are element of
1096 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001097 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001098 continue;
1099
1100 Region *ExpandedR = expandRegion(*CurrentRegion);
1101
1102 if (!ExpandedR)
1103 continue;
1104
1105 R.addSubRegion(ExpandedR, true);
1106 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001107 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001108
Tobias Grosser28a70c52014-01-29 19:05:30 +00001109 // Erase all (direct and indirect) children of ExpandedR from the valid
1110 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001111 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001112 }
1113}
1114
1115bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001116 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001117
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001118 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001119 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001120 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001121 return false;
1122 }
1123
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001124 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001125 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1126
1127 // Also check exception blocks (and possibly register them as non-affine
1128 // regions). Even though exception blocks are not modeled, we use them
1129 // to forward-propagate domain constraints during ScopInfo construction.
1130 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1131 return false;
1132
1133 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001134 continue;
1135
Tobias Grosser1d191902014-03-03 13:13:55 +00001136 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001137 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001138 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001139 }
Tobias Grosser75805372011-04-29 06:27:02 +00001140
Sebastian Pope8863b82014-05-12 19:02:02 +00001141 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001142 return false;
1143
Tobias Grosser75805372011-04-29 06:27:02 +00001144 return true;
1145}
1146
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001147bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1148 int NumLoops) const {
1149 int InstCount = 0;
1150
1151 for (auto *BB : Context.CurRegion.blocks())
1152 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001153 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001154
1155 InstCount = InstCount / NumLoops;
1156
1157 return InstCount >= ProfitabilityMinPerLoopInstructions;
1158}
1159
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001160bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1161 Region &CurRegion = Context.CurRegion;
1162
1163 if (PollyProcessUnprofitable)
1164 return true;
1165
1166 // We can probably not do a lot on scops that only write or only read
1167 // data.
1168 if (!Context.hasStores || !Context.hasLoads)
1169 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1170
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001171 int NumLoops = countBeneficialLoops(&CurRegion);
1172 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001173
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001174 // Scops with at least two loops may allow either loop fusion or tiling and
1175 // are consequently interesting to look at.
1176 if (NumAffineLoops >= 2)
1177 return true;
1178
1179 // Scops that contain a loop with a non-trivial amount of computation per
1180 // loop-iteration are interesting as we may be able to parallelize such
1181 // loops. Individual loops that have only a small amount of computation
1182 // per-iteration are performance-wise very fragile as any change to the
1183 // loop induction variables may affect performance. To not cause spurious
1184 // performance regressions, we do not consider such loops.
1185 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1186 return true;
1187
1188 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001189}
1190
Tobias Grosser75805372011-04-29 06:27:02 +00001191bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001192 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001193
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001194 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001195
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001196 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001197 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001198 return false;
1199 }
1200
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001201 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001202 DEBUG({
1203 dbgs() << "Region entry does not match -polly-region-only";
1204 dbgs() << "\n";
1205 });
1206 return false;
1207 }
1208
Tobias Grosserd654c252012-04-10 18:12:19 +00001209 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001210 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001211 if (CurRegion.getEntry() ==
1212 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1213 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001214
Hongbin Zheng94868e62012-04-07 12:29:17 +00001215 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001216 return false;
1217
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001218 if (!isProfitableRegion(Context))
1219 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001220
Tobias Grosser75805372011-04-29 06:27:02 +00001221 DEBUG(dbgs() << "OK\n");
1222 return true;
1223}
1224
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001225void ScopDetection::markFunctionAsInvalid(Function *F) const {
1226 F->addFnAttr(PollySkipFnAttr);
1227}
1228
Tobias Grosser75805372011-04-29 06:27:02 +00001229bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001230 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001231}
1232
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001233void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001234 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001235 unsigned LineEntry, LineExit;
1236 std::string FileName;
1237
Tobias Grosser00dc3092014-03-02 12:02:46 +00001238 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001239 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1240 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001241 }
1242}
1243
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001244void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001245 for (const Region *R : ValidRegions) {
1246 const Region *Parent = R->getParent();
1247 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1248 emitRejectionRemarks(F, RejectLogs.at(Parent));
1249 }
1250}
1251
1252void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1253 const Region *R) {
1254 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001255 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001256 if (IsValid)
1257 continue;
1258
1259 bool IsLeaf = Child->begin() == Child->end();
1260 if (!IsLeaf)
1261 emitMissedRemarksForLeaves(F, Child.get());
1262 else {
1263 if (RejectLogs.count(Child.get())) {
1264 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1265 }
1266 }
1267 }
1268}
1269
Tobias Grosser75805372011-04-29 06:27:02 +00001270bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001271 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001272 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001273 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001274 return false;
1275
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001276 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001277 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001278 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001279 Region *TopRegion = RI->getTopLevelRegion();
1280
Tobias Grosser2ff87232011-10-23 11:17:06 +00001281 releaseMemory();
1282
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001283 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001284 return false;
1285
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001286 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001287 return false;
1288
1289 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001290
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001291 // Only makes sense when we tracked errors.
1292 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001293 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001294 emitMissedRemarksForLeaves(F, TopRegion);
1295 }
1296
Johannes Doerferta05214f2014-10-15 23:24:28 +00001297 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001298 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001299
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001300 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001301 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001302 return false;
1303}
1304
Johannes Doerfertba65c162015-02-24 11:45:21 +00001305bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1306 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001307 const DetectionContext *DC = getDetectionContext(ScopR);
1308 assert(DC && "ScopR is no valid region!");
1309 return DC->NonAffineSubRegionSet.count(SubR);
1310}
1311
1312const ScopDetection::DetectionContext *
1313ScopDetection::getDetectionContext(const Region *R) const {
1314 auto DCMIt = DetectionContextMap.find(R);
1315 if (DCMIt == DetectionContextMap.end())
1316 return nullptr;
1317 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001318}
1319
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001320const ScopDetection::BoxedLoopsSetTy *
1321ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001322 const DetectionContext *DC = getDetectionContext(R);
1323 assert(DC && "ScopR is no valid region!");
1324 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001325}
1326
Johannes Doerfert09e36972015-10-07 20:17:36 +00001327const InvariantLoadsSetTy *
1328ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001329 const DetectionContext *DC = getDetectionContext(R);
1330 assert(DC && "ScopR is no valid region!");
1331 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001332}
1333
Tobias Grosser75805372011-04-29 06:27:02 +00001334void polly::ScopDetection::verifyRegion(const Region &R) const {
1335 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001336
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001337 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001338 isValidRegion(Context);
1339}
1340
1341void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001342 if (!VerifyScops)
1343 return;
1344
Tobias Grosser26108892014-04-02 20:18:19 +00001345 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001346 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001347}
1348
1349void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001350 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001351 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001352 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001353 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001354 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001355 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001356 AU.setPreservesAll();
1357}
1358
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001359void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001360 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001361 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001362
1363 OS << "\n";
1364}
1365
1366void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001367 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001368 ValidRegions.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001369 InsnToMemAcc.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001370 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001371
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001372 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001373}
1374
1375char ScopDetection::ID = 0;
1376
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001377Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1378
Tobias Grosser73600b82011-10-08 00:30:40 +00001379INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1380 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001381 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001382INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001383INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001384INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001385INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001386INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001387INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1388 "Polly - Detect static control parts (SCoPs)", false, false)