blob: fb58a0bbcc02bb55ab7b6deb67365dab8a74f21c [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>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000068#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000069
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosserc1a269b2015-12-21 21:00:43 +000075// This option is set to a very high value, as analyzing such loops increases
76// compile time on several cases. For experiments that enable this option,
77// a value of around 40 has been working to avoid run-time regressions with
78// Polly while still exposing interesting optimization opportunities.
79static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80 "polly-detect-profitability-min-per-loop-insts",
81 cl::desc("The minimal number of per-loop instructions before a single loop "
82 "region is considered profitable"),
83 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84
Tobias Grosser575aca82015-10-06 16:10:29 +000085bool polly::PollyProcessUnprofitable;
86static cl::opt<bool, true> XPollyProcessUnprofitable(
87 "polly-process-unprofitable",
88 cl::desc(
89 "Process scops that are unlikely to benefit from Polly optimizations."),
90 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000092
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyFunction(
94 "polly-only-func",
95 cl::desc("Only run on functions that contain a certain string"),
96 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000098
Tobias Grosser483a90d2014-07-09 10:50:10 +000099static cl::opt<std::string> OnlyRegion(
100 "polly-only-region",
101 cl::desc("Only run on certain regions (The provided identifier must "
102 "appear in the name of the region's entry block"),
103 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
104 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000105
Tobias Grosser60cd9322011-11-10 12:47:26 +0000106static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 IgnoreAliasing("polly-ignore-aliasing",
108 cl::desc("Ignore possible aliasing of the array bases"),
109 cl::Hidden, cl::init(false), cl::ZeroOrMore,
110 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000111
Johannes Doerfertb164c792014-09-18 11:17:17 +0000112bool polly::PollyUseRuntimeAliasChecks;
113static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
114 "polly-use-runtime-alias-checks",
115 cl::desc("Use runtime alias checks to resolve possible aliasing."),
116 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Tobias Grosser637bd632013-05-07 07:31:10 +0000119static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000120 ReportLevel("polly-report",
121 cl::desc("Print information about the activities of Polly"),
122 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000123
124static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000125 AllowNonAffine("polly-allow-nonaffine",
126 cl::desc("Allow non affine access functions in arrays"),
127 cl::Hidden, cl::init(false), cl::ZeroOrMore,
128 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000129
Johannes Doerfertba65c162015-02-24 11:45:21 +0000130static cl::opt<bool> AllowNonAffineSubRegions(
131 "polly-allow-nonaffine-branches",
132 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000133 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000134
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000135static cl::opt<bool>
136 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
137 cl::desc("Allow non affine conditions for loops"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
140
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000141static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
142 cl::desc("Allow unsigned expressions"),
143 cl::Hidden, cl::init(false), cl::ZeroOrMore,
144 cl::cat(PollyCategory));
145
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000146static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000147 TrackFailures("polly-detect-track-failures",
148 cl::desc("Track failure strings in detecting scop regions"),
149 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000150 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000151
Andreas Simbuerger04472402014-05-24 09:25:10 +0000152static cl::opt<bool> KeepGoing("polly-detect-keep-going",
153 cl::desc("Do not fail on the first error."),
154 cl::Hidden, cl::ZeroOrMore, cl::init(false),
155 cl::cat(PollyCategory));
156
Sebastian Pop18016682014-04-08 21:20:44 +0000157static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000158 PollyDelinearizeX("polly-delinearize",
159 cl::desc("Delinearize array access functions"),
160 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000161 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000162
Tobias Grossera1689932014-02-18 18:49:49 +0000163static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000164 VerifyScops("polly-detect-verify",
165 cl::desc("Verify the detected SCoPs after each transformation"),
166 cl::Hidden, cl::init(false), cl::ZeroOrMore,
167 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000168
Johannes Doerferte526de52015-09-21 19:10:11 +0000169/// @brief The minimal trip count under which loops are considered unprofitable.
170static const unsigned MIN_LOOP_TRIP_COUNT = 8;
171
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000172bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000173bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000174StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000175
Tobias Grosser75805372011-04-29 06:27:02 +0000176//===----------------------------------------------------------------------===//
177// Statistics.
178
179STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
180
Tobias Grosser8519f892013-12-18 10:49:53 +0000181class DiagnosticScopFound : public DiagnosticInfo {
182private:
183 static int PluginDiagnosticKind;
184
185 Function &F;
186 std::string FileName;
187 unsigned EntryLine, ExitLine;
188
189public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000190 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
191 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000192 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000193 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000194
195 virtual void print(DiagnosticPrinter &DP) const;
196
197 static bool classof(const DiagnosticInfo *DI) {
198 return DI->getKind() == PluginDiagnosticKind;
199 }
200};
201
202int DiagnosticScopFound::PluginDiagnosticKind = 10;
203
Tobias Grosser8519f892013-12-18 10:49:53 +0000204void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000205 DP << "Polly detected an optimizable loop region (scop) in function '" << F
206 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000207
208 if (FileName.empty()) {
209 DP << "Scop location is unknown. Compile with debug info "
210 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000211 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000212 }
213
214 DP << FileName << ":" << EntryLine << ": Start of scop\n";
215 DP << FileName << ":" << ExitLine << ": End of scop";
216}
217
Tobias Grosser75805372011-04-29 06:27:02 +0000218//===----------------------------------------------------------------------===//
219// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000220
Johannes Doerfertb164c792014-09-18 11:17:17 +0000221ScopDetection::ScopDetection() : FunctionPass(ID) {
222 if (!PollyUseRuntimeAliasChecks)
223 return;
224
Johannes Doerfert928229f2014-09-29 17:06:29 +0000225 // Disable runtime alias checks if we ignore aliasing all together.
226 if (IgnoreAliasing) {
227 PollyUseRuntimeAliasChecks = false;
228 return;
229 }
230
Johannes Doerfertb164c792014-09-18 11:17:17 +0000231 if (AllowNonAffine) {
232 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
233 "accesses are enabled.\n");
234 PollyUseRuntimeAliasChecks = false;
235 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000236}
237
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000238template <class RR, typename... Args>
239inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
240 Args &&... Arguments) const {
241
242 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000243 RejectLog &Log = Context.Log;
244 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000245
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000246 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000247 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000248
249 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000250 DEBUG(dbgs() << "\n");
251 } else {
252 assert(!Assert && "Verification of detected scop failed");
253 }
254
255 return false;
256}
257
Tobias Grossera1689932014-02-18 18:49:49 +0000258bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
259 if (!ValidRegions.count(&R))
260 return false;
261
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000262 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000263 DetectionContextMap.erase(&R);
264 const auto &It = DetectionContextMap.insert(
265 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
266 false /*verifying*/)));
267 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000268 return isValidRegion(Context);
269 }
Tobias Grossera1689932014-02-18 18:49:49 +0000270
271 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000272}
273
Tobias Grosser4f129a62011-10-08 00:30:55 +0000274std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000275 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000276 return "";
277
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000278 // Get the first error we found. Even in keep-going mode, this is the first
279 // reason that caused the candidate to be rejected.
280 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000281
282 // This can happen when we marked a region invalid, but didn't track
283 // an error for it.
284 if (Errors.size() == 0)
285 return "";
286
287 RejectReasonPtr RR = *Errors.begin();
288 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000289}
290
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000291bool ScopDetection::addOverApproximatedRegion(Region *AR,
292 DetectionContext &Context) const {
293
294 // If we already know about Ar we can exit.
295 if (!Context.NonAffineSubRegionSet.insert(AR))
296 return true;
297
298 // All loops in the region have to be overapproximated too if there
299 // are accesses that depend on the iteration count.
300 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000301 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000302 if (AR->contains(L))
303 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000304 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000305
306 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000307}
308
Johannes Doerfert09e36972015-10-07 20:17:36 +0000309bool ScopDetection::onlyValidRequiredInvariantLoads(
310 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
311 Region &CurRegion = Context.CurRegion;
312
313 for (LoadInst *Load : RequiredILS)
314 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
315 return false;
316
317 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
318
319 return true;
320}
321
322bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
323 Value *BaseAddress) const {
324
325 InvariantLoadsSetTy AccessILS;
326 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
327 return false;
328
329 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
330 return false;
331
332 return true;
333}
334
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000335bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000336 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000337 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000338 Loop *L = LI->getLoopFor(&BB);
339 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000340
Johannes Doerfert09e36972015-10-07 20:17:36 +0000341 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000342 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000343
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000344 if (!IsLoopBranch && AllowNonAffineSubRegions &&
345 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
346 return true;
347
348 if (IsLoopBranch)
349 return false;
350
351 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
352 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000353}
354
355bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000356 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000357 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000358
359 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
360 auto Opcode = BinOp->getOpcode();
361 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
362 Value *Op0 = BinOp->getOperand(0);
363 Value *Op1 = BinOp->getOperand(1);
364 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
365 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
366 }
367 }
368
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000369 // Non constant conditions of branches need to be ICmpInst.
370 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000371 if (!IsLoopBranch && AllowNonAffineSubRegions &&
372 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
373 return true;
374 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000375 }
Tobias Grosser75805372011-04-29 06:27:02 +0000376
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000377 ICmpInst *ICmp = cast<ICmpInst>(Condition);
378 // Unsigned comparisons are not allowed. They trigger overflow problems
379 // in the code generation.
380 //
381 // TODO: This is not sufficient and just hides bugs. However it does pretty
382 // well.
383 if (ICmp->isUnsigned() && !AllowUnsigned)
384 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000385
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000386 // Are both operands of the ICmp affine?
387 if (isa<UndefValue>(ICmp->getOperand(0)) ||
388 isa<UndefValue>(ICmp->getOperand(1)))
389 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000390
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000391 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
392 // for arbitrary pointer expressions at the moment. Until
393 // this is fixed we disallow pointer expressions completely.
394 if (ICmp->getOperand(0)->getType()->isPointerTy())
395 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000396
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000397 Loop *L = LI->getLoopFor(ICmp->getParent());
398 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
399 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000400
Johannes Doerfert09e36972015-10-07 20:17:36 +0000401 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000402 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000403
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000404 if (!IsLoopBranch && AllowNonAffineSubRegions &&
405 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
406 return true;
407
408 if (IsLoopBranch)
409 return false;
410
411 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
412 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000413}
414
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000415bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000416 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000417 DetectionContext &Context) const {
418 Region &CurRegion = Context.CurRegion;
419
420 TerminatorInst *TI = BB.getTerminator();
421
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000422 if (AllowUnreachable && isa<UnreachableInst>(TI))
423 return true;
424
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000425 // Return instructions are only valid if the region is the top level region.
426 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
427 return true;
428
429 Value *Condition = getConditionFromTerminator(TI);
430
431 if (!Condition)
432 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
433
434 // UndefValue is not allowed as condition.
435 if (isa<UndefValue>(Condition))
436 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
437
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000438 // Constant integer conditions are always affine.
439 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000440 return true;
441
442 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000443 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000444
445 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
446 assert(SI && "Terminator was neither branch nor switch");
447
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000448 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000449}
450
Tobias Grosser75805372011-04-29 06:27:02 +0000451bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000452 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000453 return false;
454
455 if (CI.doesNotAccessMemory())
456 return true;
457
458 Function *CalledFunction = CI.getCalledFunction();
459
460 // Indirect calls are not supported.
461 if (CalledFunction == 0)
462 return false;
463
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000464 if (isIgnoredIntrinsic(&CI))
465 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000466
Tobias Grosser75805372011-04-29 06:27:02 +0000467 return false;
468}
469
Tobias Grosser458fb782014-01-28 12:58:58 +0000470bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
471 // A reference to function argument or constant value is invariant.
472 if (isa<Argument>(Val) || isa<Constant>(Val))
473 return true;
474
475 const Instruction *I = dyn_cast<Instruction>(&Val);
476 if (!I)
477 return false;
478
479 if (!Reg.contains(I))
480 return true;
481
482 if (I->mayHaveSideEffects())
483 return false;
484
485 // When Val is a Phi node, it is likely not invariant. We do not check whether
486 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
487 // invariant. Recursively checking the operators of Phi nodes would lead to
488 // infinite recursion.
489 if (isa<PHINode>(*I))
490 return false;
491
Tobias Grosser26108892014-04-02 20:18:19 +0000492 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000493 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000494 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000495
Tobias Grosser458fb782014-01-28 12:58:58 +0000496 return true;
497}
498
Sebastian Pop422e33f2014-06-03 18:16:31 +0000499MapInsnToMemAcc InsnToMemAcc;
500
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000501/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
502/// register the '...' components.
503///
504/// Array access expressions as they are generated by gfortran contain smax(0,
505/// size) expressions that confuse the 'normal' delinearization algorithm.
506/// However, if we extract such expressions before the normal delinearization
507/// takes place they can actually help to identify array size expressions in
508/// fortran accesses. For the subsequently following delinearization the smax(0,
509/// size) component can be replaced by just 'size'. This is correct as we will
510/// always add and verify the assumption that for all subscript expressions
511/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
512/// that 0 <= size, which means smax(0, size) == size.
513struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
514public:
515 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
516 std::vector<const SCEV *> *Terms = nullptr) {
517
518 SCEVRemoveMax D(SE, Terms);
519 return D.visit(Expr);
520 }
521
522 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
523 : SE(SE), Terms(Terms) {}
524
525 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
526
527 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
528 return Expr;
529 }
530
531 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
532 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
533 }
534
535 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
536
537 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000538 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000539 auto Res = visit(Expr->getOperand(1));
540 if (Terms)
541 (*Terms).push_back(Res);
542 return Res;
543 }
544
545 return Expr;
546 }
547
Roman Gareev8aa43752015-12-17 20:37:17 +0000548 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000549
550 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
551
552 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
553 return Expr;
554 }
555
556 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
557
558 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
559 SmallVector<const SCEV *, 5> NewOps;
560 for (const SCEV *Op : Expr->operands())
561 NewOps.push_back(visit(Op));
562
563 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
564 }
565
566 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
567 SmallVector<const SCEV *, 5> NewOps;
568 for (const SCEV *Op : Expr->operands())
569 NewOps.push_back(visit(Op));
570
571 return SE.getAddExpr(NewOps);
572 }
573
574 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
575 SmallVector<const SCEV *, 5> NewOps;
576 for (const SCEV *Op : Expr->operands())
577 NewOps.push_back(visit(Op));
578
579 return SE.getMulExpr(NewOps);
580 }
581
582private:
583 ScalarEvolution &SE;
584 std::vector<const SCEV *> *Terms;
585};
586
Tobias Grosserd68ba422015-11-24 05:00:36 +0000587SmallVector<const SCEV *, 4>
588ScopDetection::getDelinearizationTerms(DetectionContext &Context,
589 const SCEVUnknown *BasePointer) const {
590 SmallVector<const SCEV *, 4> Terms;
591 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000592 std::vector<const SCEV *> MaxTerms;
593 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
594 if (MaxTerms.size() > 0) {
595 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
596 continue;
597 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000598 // In case the outermost expression is a plain add, we check if any of its
599 // terms has the form 4 * %inst * %param * %param ..., aka a term that
600 // contains a product between a parameter and an instruction that is
601 // inside the scop. Such instructions, if allowed at all, are instructions
602 // SCEV can not represent, but Polly is still looking through. As a
603 // result, these instructions can depend on induction variables and are
604 // most likely no array sizes. However, terms that are multiplied with
605 // them are likely candidates for array sizes.
606 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
607 for (auto Op : AF->operands()) {
608 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
609 SE->collectParametricTerms(AF2, Terms);
610 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
611 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000612
Tobias Grosserd68ba422015-11-24 05:00:36 +0000613 for (auto *MulOp : AF2->operands()) {
614 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
615 Operands.push_back(Const);
616 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
617 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
618 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000619 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000620
621 } else {
622 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000623 }
624 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000625 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000626 if (Operands.size())
627 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000628 }
629 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000630 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000631 if (Terms.empty())
632 SE->collectParametricTerms(Pair.second, Terms);
633 }
634 return Terms;
635}
Sebastian Pope8863b82014-05-12 19:02:02 +0000636
Tobias Grosserd68ba422015-11-24 05:00:36 +0000637bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
638 SmallVectorImpl<const SCEV *> &Sizes,
639 const SCEVUnknown *BasePointer) const {
640 Value *BaseValue = BasePointer->getValue();
641 Region &CurRegion = Context.CurRegion;
642 for (const SCEV *DelinearizedSize : Sizes) {
643 if (!isAffine(DelinearizedSize, Context, nullptr)) {
644 Sizes.clear();
645 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000646 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000647 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
648 auto *V = dyn_cast<Value>(Unknown->getValue());
649 if (auto *Load = dyn_cast<LoadInst>(V)) {
650 if (Context.CurRegion.contains(Load) &&
651 isHoistableLoad(Load, CurRegion, *LI, *SE))
652 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000653 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000654 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000655 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000656 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000657 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000658 Context, /*Assert=*/true, DelinearizedSize,
659 Context.Accesses[BasePointer].front().first, BaseValue);
660 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000661
Tobias Grosserd68ba422015-11-24 05:00:36 +0000662 // No array shape derived.
663 if (Sizes.empty()) {
664 if (AllowNonAffine)
665 return true;
666
Tobias Grosser230acc42014-09-13 14:47:55 +0000667 for (const auto &Pair : Context.Accesses[BasePointer]) {
668 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000669 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000670
Tobias Grosserd68ba422015-11-24 05:00:36 +0000671 if (!isAffine(AF, Context, BaseValue)) {
672 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
673 BaseValue);
674 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000675 return false;
676 }
677 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000678 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000679 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000680 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000681}
682
Tobias Grosserd68ba422015-11-24 05:00:36 +0000683// We first store the resulting memory accesses in TempMemoryAccesses. Only
684// if the access functions for all memory accesses have been successfully
685// delinearized we continue. Otherwise, we either report a failure or, if
686// non-affine accesses are allowed, we drop the information. In case the
687// information is dropped the memory accesses need to be overapproximated
688// when translated to a polyhedral representation.
689bool ScopDetection::computeAccessFunctions(
690 DetectionContext &Context, const SCEVUnknown *BasePointer,
691 std::shared_ptr<ArrayShape> Shape) const {
692 Value *BaseValue = BasePointer->getValue();
693 bool BasePtrHasNonAffine = false;
694 MapInsnToMemAcc TempMemoryAccesses;
695 for (const auto &Pair : Context.Accesses[BasePointer]) {
696 const Instruction *Insn = Pair.first;
697 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000698 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000699 bool IsNonAffine = false;
700 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
701 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
702
703 if (!AF) {
704 if (isAffine(Pair.second, Context, BaseValue))
705 Acc->DelinearizedSubscripts.push_back(Pair.second);
706 else
707 IsNonAffine = true;
708 } else {
709 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
710 Shape->DelinearizedSizes);
711 if (Acc->DelinearizedSubscripts.size() == 0)
712 IsNonAffine = true;
713 for (const SCEV *S : Acc->DelinearizedSubscripts)
714 if (!isAffine(S, Context, BaseValue))
715 IsNonAffine = true;
716 }
717
718 // (Possibly) report non affine access
719 if (IsNonAffine) {
720 BasePtrHasNonAffine = true;
721 if (!AllowNonAffine)
722 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
723 Insn, BaseValue);
724 if (!KeepGoing && !AllowNonAffine)
725 return false;
726 }
727 }
728
729 if (!BasePtrHasNonAffine)
730 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
731
732 return true;
733}
734
735bool ScopDetection::hasBaseAffineAccesses(
736 DetectionContext &Context, const SCEVUnknown *BasePointer) const {
737 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
738
739 auto Terms = getDelinearizationTerms(Context, BasePointer);
740
741 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
742 Context.ElementSize[BasePointer]);
743
744 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer))
745 return false;
746
747 return computeAccessFunctions(Context, BasePointer, Shape);
748}
749
750bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
751 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses)
752 if (!hasBaseAffineAccesses(Context, BasePointer)) {
753 if (KeepGoing)
754 continue;
755 else
756 return false;
757 }
758 return true;
759}
760
Tobias Grosser75805372011-04-29 06:27:02 +0000761bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
762 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000763 Region &CurRegion = Context.CurRegion;
764
Tobias Grossere5e171e2011-11-10 12:45:03 +0000765 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000766 Loop *L = LI->getLoopFor(Inst.getParent());
767 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000768 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000769 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000770
Tobias Grosserb8710b52011-11-10 12:44:50 +0000771 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
772
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000773 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000774 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000775
776 BaseValue = BasePointer->getValue();
777
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000778 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000779 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000780
Tobias Grosser458fb782014-01-28 12:58:58 +0000781 // Check that the base address of the access is invariant in the current
782 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000783 if (!isInvariant(*BaseValue, CurRegion))
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000784 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BaseValue,
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000785 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000786
Tobias Grosserb8710b52011-11-10 12:44:50 +0000787 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
788
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000789 const SCEV *Size = SE->getElementSize(&Inst);
790 if (Context.ElementSize.count(BasePointer)) {
791 if (Context.ElementSize[BasePointer] != Size)
792 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
793 &Inst, BaseValue);
794 } else {
795 Context.ElementSize[BasePointer] = Size;
796 }
797
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000798 bool isVariantInNonAffineLoop = false;
799 SetVector<const Loop *> Loops;
800 findLoops(AccessFunction, Loops);
801 for (const Loop *L : Loops)
802 if (Context.BoxedLoopsSet.count(L))
803 isVariantInNonAffineLoop = true;
804
805 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000806 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000807
Johannes Doerfert09e36972015-10-07 20:17:36 +0000808 if (!isAffine(AccessFunction, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000809 Context.NonAffineAccesses.insert(BasePointer);
810 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000811 if (isVariantInNonAffineLoop ||
Johannes Doerfert09e36972015-10-07 20:17:36 +0000812 !isAffine(AccessFunction, Context, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000813 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000814 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000815 }
Tobias Grosser75805372011-04-29 06:27:02 +0000816
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000817 // FIXME: Think about allowing IntToPtrInst
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000818 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
819 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000820
Tobias Grosser1eedb672014-09-24 21:04:29 +0000821 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000822 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000823
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000824 // Check if the base pointer of the memory access does alias with
825 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000826 AAMDNodes AATags;
827 Inst.getAAMetadata(AATags);
828 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000829 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000830
Tobias Grosser1eedb672014-09-24 21:04:29 +0000831 if (!AS.isMustAlias()) {
832 if (PollyUseRuntimeAliasChecks) {
833 bool CanBuildRunTimeCheck = true;
834 // The run-time alias check places code that involves the base pointer at
835 // the beginning of the SCoP. This breaks if the base pointer is defined
836 // inside the scop. Hence, we can only create a run-time check if we are
837 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000838 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000839 for (const auto &Ptr : AS) {
840 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000841 if (Inst && CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000842 auto *Load = dyn_cast<LoadInst>(Inst);
843 if (Load && isHoistableLoad(Load, CurRegion, *LI, *SE)) {
844 Context.RequiredILS.insert(Load);
845 continue;
846 }
847
Tobias Grosser1eedb672014-09-24 21:04:29 +0000848 CanBuildRunTimeCheck = false;
849 break;
850 }
851 }
852
853 if (CanBuildRunTimeCheck)
854 return true;
855 }
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000856 return invalid<ReportAlias>(Context, /*Assert=*/true, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000857 }
Tobias Grosser75805372011-04-29 06:27:02 +0000858
859 return true;
860}
861
Tobias Grosser75805372011-04-29 06:27:02 +0000862bool ScopDetection::isValidInstruction(Instruction &Inst,
863 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000864 for (auto &Op : Inst.operands()) {
865 auto *OpInst = dyn_cast<Instruction>(&Op);
866
867 if (!OpInst)
868 continue;
869
870 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
871 return false;
872 }
873
Tobias Grosser75805372011-04-29 06:27:02 +0000874 // We only check the call instruction but not invoke instruction.
875 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
876 if (isValidCallInst(*CI))
877 return true;
878
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000879 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000880 }
881
882 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000883 if (!isa<AllocaInst>(Inst))
884 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000885
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000886 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000887 }
888
889 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000890 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
891 Context.hasStores |= isa<StoreInst>(Inst);
892 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +0000893 if (auto *Load = dyn_cast<LoadInst>(&Inst))
894 if (!Load->isSimple())
895 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
896 &Inst);
897 if (auto *Store = dyn_cast<StoreInst>(&Inst))
898 if (!Store->isSimple())
899 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
900 &Inst);
901
Tobias Grosser75805372011-04-29 06:27:02 +0000902 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000903 }
Tobias Grosser75805372011-04-29 06:27:02 +0000904
905 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000906 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000907}
908
Johannes Doerfertd020b772015-08-27 06:53:52 +0000909bool ScopDetection::canUseISLTripCount(Loop *L,
910 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000911 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
912 // need to overapproximate it as a boxed loop.
913 SmallVector<BasicBlock *, 4> LoopControlBlocks;
914 L->getLoopLatches(LoopControlBlocks);
915 L->getExitingBlocks(LoopControlBlocks);
916 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000917 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000918 return false;
919 }
920
Johannes Doerfertd020b772015-08-27 06:53:52 +0000921 // We can use ISL to compute the trip count of L.
922 return true;
923}
924
Tobias Grosser75805372011-04-29 06:27:02 +0000925bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000926 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000927 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000928
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000929 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000930 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000931 while (R != &Context.CurRegion && !R->contains(L))
932 R = R->getParent();
933
934 if (addOverApproximatedRegion(R, Context))
935 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000936 }
Tobias Grosser75805372011-04-29 06:27:02 +0000937
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000938 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000939 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000940}
941
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000942/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000943/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000944static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000945 auto *TripCount = SE.getBackedgeTakenCount(L);
946
Johannes Doerfertf61df692015-10-04 14:56:08 +0000947 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000948 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000949 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
950 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
951 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000952
953 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000954 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000955
956 return count;
957}
958
Johannes Doerfertf61df692015-10-04 14:56:08 +0000959int ScopDetection::countBeneficialLoops(Region *R) const {
960 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000961
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000962 auto L = LI->getLoopFor(R->getEntry());
963 L = L ? R->outermostLoopInRegion(L) : nullptr;
964 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000965
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000966 auto SubLoops =
967 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
968
969 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000970 if (R->contains(SubLoop))
971 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000972
Johannes Doerfertf61df692015-10-04 14:56:08 +0000973 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000974}
975
Tobias Grosser75805372011-04-29 06:27:02 +0000976Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000977 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000978 std::unique_ptr<Region> LastValidRegion;
979 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000980
981 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
982
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000983 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000984 const auto &It = DetectionContextMap.insert(std::make_pair(
985 ExpandedRegion.get(),
986 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
987 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000988 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000989 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000990
Johannes Doerfert717b8662015-09-08 21:44:27 +0000991 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000992 // If the exit is valid check all blocks
993 // - if true, a valid region was found => store it + keep expanding
994 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +0000995 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
996 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000997 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000998 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000999
Tobias Grosserd7e58642013-04-10 06:55:45 +00001000 // Store this region, because it is the greatest valid (encountered so
1001 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001002 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001003 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001004
1005 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001006 ExpandedRegion =
1007 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001008
1009 } else {
1010 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001011 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001012 ExpandedRegion =
1013 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001014 }
Tobias Grosser75805372011-04-29 06:27:02 +00001015 }
1016
Tobias Grosser378a9f22013-11-16 19:34:11 +00001017 DEBUG({
1018 if (LastValidRegion)
1019 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1020 else
1021 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1022 });
Tobias Grosser75805372011-04-29 06:27:02 +00001023
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001024 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001025}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001026static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001027 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001028 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001029 return false;
1030
1031 return true;
1032}
Tobias Grosser75805372011-04-29 06:27:02 +00001033
Johannes Doerferte46925f2015-10-01 10:59:14 +00001034unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001035 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001036 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001037 if (ValidRegions.count(SubRegion.get())) {
1038 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001039 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001040 } else
1041 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001042 }
1043 return Count;
1044}
1045
Johannes Doerferte46925f2015-10-01 10:59:14 +00001046void ScopDetection::removeCachedResults(const Region &R) {
1047 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001048 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001049}
1050
Tobias Grosser75805372011-04-29 06:27:02 +00001051void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001052 const auto &It = DetectionContextMap.insert(
1053 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1054 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001055
1056 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +00001057 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001058 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001059 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001060 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001061 RegionIsValid = isValidRegion(Context);
1062
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001063 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001064
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001065 if (PollyTrackFailures && HasErrors)
1066 RejectLogs.insert(std::make_pair(&R, Context.Log));
1067
Johannes Doerferte46925f2015-10-01 10:59:14 +00001068 if (HasErrors) {
1069 removeCachedResults(R);
1070 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001071 ++ValidRegion;
1072 ValidRegions.insert(&R);
1073 return;
1074 }
1075
David Blaikieb035f6d2014-04-15 18:45:27 +00001076 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001077 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001078
1079 // Try to expand regions.
1080 //
1081 // As the region tree normally only contains canonical regions, non canonical
1082 // regions that form a Scop are not found. Therefore, those non canonical
1083 // regions are checked by expanding the canonical ones.
1084
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001085 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001086
David Blaikieb035f6d2014-04-15 18:45:27 +00001087 for (auto &SubRegion : R)
1088 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001089
Tobias Grosser26108892014-04-02 20:18:19 +00001090 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001091 // Skip regions that had errors.
1092 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1093 if (HadErrors)
1094 continue;
1095
Tobias Grosser75805372011-04-29 06:27:02 +00001096 // Skip invalid regions. Regions may become invalid, if they are element of
1097 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001098 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001099 continue;
1100
1101 Region *ExpandedR = expandRegion(*CurrentRegion);
1102
1103 if (!ExpandedR)
1104 continue;
1105
1106 R.addSubRegion(ExpandedR, true);
1107 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001108 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001109
Tobias Grosser28a70c52014-01-29 19:05:30 +00001110 // Erase all (direct and indirect) children of ExpandedR from the valid
1111 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001112 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001113 }
1114}
1115
1116bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001117 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001118
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001119 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001120 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001121 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001122 return false;
1123 }
1124
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001125 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001126 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1127
1128 // Also check exception blocks (and possibly register them as non-affine
1129 // regions). Even though exception blocks are not modeled, we use them
1130 // to forward-propagate domain constraints during ScopInfo construction.
1131 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1132 return false;
1133
1134 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001135 continue;
1136
Tobias Grosser1d191902014-03-03 13:13:55 +00001137 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001138 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001139 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001140 }
Tobias Grosser75805372011-04-29 06:27:02 +00001141
Sebastian Pope8863b82014-05-12 19:02:02 +00001142 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001143 return false;
1144
Tobias Grosser75805372011-04-29 06:27:02 +00001145 return true;
1146}
1147
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001148bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1149 int NumLoops) const {
1150 int InstCount = 0;
1151
1152 for (auto *BB : Context.CurRegion.blocks())
1153 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001154 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001155
1156 InstCount = InstCount / NumLoops;
1157
1158 return InstCount >= ProfitabilityMinPerLoopInstructions;
1159}
1160
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001161bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1162 Region &CurRegion = Context.CurRegion;
1163
1164 if (PollyProcessUnprofitable)
1165 return true;
1166
1167 // We can probably not do a lot on scops that only write or only read
1168 // data.
1169 if (!Context.hasStores || !Context.hasLoads)
1170 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1171
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001172 int NumLoops = countBeneficialLoops(&CurRegion);
1173 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001174
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001175 // Scops with at least two loops may allow either loop fusion or tiling and
1176 // are consequently interesting to look at.
1177 if (NumAffineLoops >= 2)
1178 return true;
1179
1180 // Scops that contain a loop with a non-trivial amount of computation per
1181 // loop-iteration are interesting as we may be able to parallelize such
1182 // loops. Individual loops that have only a small amount of computation
1183 // per-iteration are performance-wise very fragile as any change to the
1184 // loop induction variables may affect performance. To not cause spurious
1185 // performance regressions, we do not consider such loops.
1186 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1187 return true;
1188
1189 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001190}
1191
Tobias Grosser75805372011-04-29 06:27:02 +00001192bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001193 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001194
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001195 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001196
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001197 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001198 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001199 return false;
1200 }
1201
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001202 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001203 DEBUG({
1204 dbgs() << "Region entry does not match -polly-region-only";
1205 dbgs() << "\n";
1206 });
1207 return false;
1208 }
1209
Tobias Grosserd654c252012-04-10 18:12:19 +00001210 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001211 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001212 if (CurRegion.getEntry() ==
1213 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1214 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001215
Hongbin Zheng94868e62012-04-07 12:29:17 +00001216 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001217 return false;
1218
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001219 DebugLoc DbgLoc;
1220 if (!isReducibleRegion(CurRegion, DbgLoc))
1221 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1222 &CurRegion, DbgLoc);
1223
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001224 if (!isProfitableRegion(Context))
1225 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001226
Tobias Grosser75805372011-04-29 06:27:02 +00001227 DEBUG(dbgs() << "OK\n");
1228 return true;
1229}
1230
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001231void ScopDetection::markFunctionAsInvalid(Function *F) const {
1232 F->addFnAttr(PollySkipFnAttr);
1233}
1234
Tobias Grosser75805372011-04-29 06:27:02 +00001235bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001236 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001237}
1238
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001239void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001240 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001241 unsigned LineEntry, LineExit;
1242 std::string FileName;
1243
Tobias Grosser00dc3092014-03-02 12:02:46 +00001244 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001245 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1246 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001247 }
1248}
1249
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001250void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001251 for (const Region *R : ValidRegions) {
1252 const Region *Parent = R->getParent();
1253 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1254 emitRejectionRemarks(F, RejectLogs.at(Parent));
1255 }
1256}
1257
1258void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1259 const Region *R) {
1260 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001261 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001262 if (IsValid)
1263 continue;
1264
1265 bool IsLeaf = Child->begin() == Child->end();
1266 if (!IsLeaf)
1267 emitMissedRemarksForLeaves(F, Child.get());
1268 else {
1269 if (RejectLogs.count(Child.get())) {
1270 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1271 }
1272 }
1273 }
1274}
1275
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001276bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1277 BasicBlock *REntry = R.getEntry();
1278 BasicBlock *RExit = R.getExit();
1279 // Map to match the color of a BasicBlock during the DFS walk.
1280 DenseMap<const BasicBlock *, Color> BBColorMap;
1281 // Stack keeping track of current BB and index of next child to be processed.
1282 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1283
1284 unsigned AdjacentBlockIndex = 0;
1285 BasicBlock *CurrBB, *SuccBB;
1286 CurrBB = REntry;
1287
1288 // Initialize the map for all BB with WHITE color.
1289 for (auto *BB : R.blocks())
1290 BBColorMap[BB] = ScopDetection::WHITE;
1291
1292 // Process the entry block of the Region.
1293 BBColorMap[CurrBB] = ScopDetection::GREY;
1294 DFSStack.push(std::make_pair(CurrBB, 0));
1295
1296 while (!DFSStack.empty()) {
1297 // Get next BB on stack to be processed.
1298 CurrBB = DFSStack.top().first;
1299 AdjacentBlockIndex = DFSStack.top().second;
1300 DFSStack.pop();
1301
1302 // Loop to iterate over the successors of current BB.
1303 const TerminatorInst *TInst = CurrBB->getTerminator();
1304 unsigned NSucc = TInst->getNumSuccessors();
1305 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1306 ++I, ++AdjacentBlockIndex) {
1307 SuccBB = TInst->getSuccessor(I);
1308
1309 // Checks for region exit block and self-loops in BB.
1310 if (SuccBB == RExit || SuccBB == CurrBB)
1311 continue;
1312
1313 // WHITE indicates an unvisited BB in DFS walk.
1314 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1315 // Push the current BB and the index of the next child to be visited.
1316 DFSStack.push(std::make_pair(CurrBB, I + 1));
1317 // Push the next BB to be processed.
1318 DFSStack.push(std::make_pair(SuccBB, 0));
1319 // First time the BB is being processed.
1320 BBColorMap[SuccBB] = ScopDetection::GREY;
1321 break;
1322 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1323 // GREY indicates a loop in the control flow.
1324 // If the destination dominates the source, it is a natural loop
1325 // else, an irreducible control flow in the region is detected.
1326 if (!DT->dominates(SuccBB, CurrBB)) {
1327 // Get debug info of instruction which causes irregular control flow.
1328 DbgLoc = TInst->getDebugLoc();
1329 return false;
1330 }
1331 }
1332 }
1333
1334 // If all children of current BB have been processed,
1335 // then mark that BB as fully processed.
1336 if (AdjacentBlockIndex == NSucc)
1337 BBColorMap[CurrBB] = ScopDetection::BLACK;
1338 }
1339
1340 return true;
1341}
1342
Tobias Grosser75805372011-04-29 06:27:02 +00001343bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001344 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001345 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001346 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001347 return false;
1348
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001349 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001350 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001351 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001352 Region *TopRegion = RI->getTopLevelRegion();
1353
Tobias Grosser2ff87232011-10-23 11:17:06 +00001354 releaseMemory();
1355
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001356 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001357 return false;
1358
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001359 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001360 return false;
1361
1362 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001363
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001364 // Only makes sense when we tracked errors.
1365 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001366 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001367 emitMissedRemarksForLeaves(F, TopRegion);
1368 }
1369
Johannes Doerferta05214f2014-10-15 23:24:28 +00001370 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001371 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001372
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001373 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001374 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001375 return false;
1376}
1377
Johannes Doerfertba65c162015-02-24 11:45:21 +00001378bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1379 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001380 const DetectionContext *DC = getDetectionContext(ScopR);
1381 assert(DC && "ScopR is no valid region!");
1382 return DC->NonAffineSubRegionSet.count(SubR);
1383}
1384
1385const ScopDetection::DetectionContext *
1386ScopDetection::getDetectionContext(const Region *R) const {
1387 auto DCMIt = DetectionContextMap.find(R);
1388 if (DCMIt == DetectionContextMap.end())
1389 return nullptr;
1390 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001391}
1392
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001393const ScopDetection::BoxedLoopsSetTy *
1394ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001395 const DetectionContext *DC = getDetectionContext(R);
1396 assert(DC && "ScopR is no valid region!");
1397 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001398}
1399
Johannes Doerfert09e36972015-10-07 20:17:36 +00001400const InvariantLoadsSetTy *
1401ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001402 const DetectionContext *DC = getDetectionContext(R);
1403 assert(DC && "ScopR is no valid region!");
1404 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001405}
1406
Tobias Grosser75805372011-04-29 06:27:02 +00001407void polly::ScopDetection::verifyRegion(const Region &R) const {
1408 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001409
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001410 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001411 isValidRegion(Context);
1412}
1413
1414void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001415 if (!VerifyScops)
1416 return;
1417
Tobias Grosser26108892014-04-02 20:18:19 +00001418 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001419 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001420}
1421
1422void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001423 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001424 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001425 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001426 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001427 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001428 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001429 AU.setPreservesAll();
1430}
1431
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001432void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001433 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001434 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001435
1436 OS << "\n";
1437}
1438
1439void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001440 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001441 ValidRegions.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001442 InsnToMemAcc.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001443 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001444
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001445 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001446}
1447
1448char ScopDetection::ID = 0;
1449
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001450Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1451
Tobias Grosser73600b82011-10-08 00:30:40 +00001452INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1453 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001454 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001455INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001456INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001457INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001458INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001459INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001460INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1461 "Polly - Detect static control parts (SCoPs)", false, false)