blob: a8833f193e9c8dd09c3d9d44e74b031bec5dc619 [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//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
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
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000124static cl::opt<bool> AllowDifferentTypes(
125 "polly-allow-differing-element-types",
126 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000127 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000128
Tobias Grosser531891e2012-11-01 16:45:20 +0000129static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000130 AllowNonAffine("polly-allow-nonaffine",
131 cl::desc("Allow non affine access functions in arrays"),
132 cl::Hidden, cl::init(false), cl::ZeroOrMore,
133 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000134
Johannes Doerfertba65c162015-02-24 11:45:21 +0000135static cl::opt<bool> AllowNonAffineSubRegions(
136 "polly-allow-nonaffine-branches",
137 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000138 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000139
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000140static cl::opt<bool>
141 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
142 cl::desc("Allow non affine conditions for loops"),
143 cl::Hidden, cl::init(false), cl::ZeroOrMore,
144 cl::cat(PollyCategory));
145
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000146static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
147 cl::desc("Allow unsigned expressions"),
148 cl::Hidden, cl::init(false), cl::ZeroOrMore,
149 cl::cat(PollyCategory));
150
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000151static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000152 TrackFailures("polly-detect-track-failures",
153 cl::desc("Track failure strings in detecting scop regions"),
154 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000155 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000156
Andreas Simbuerger04472402014-05-24 09:25:10 +0000157static cl::opt<bool> KeepGoing("polly-detect-keep-going",
158 cl::desc("Do not fail on the first error."),
159 cl::Hidden, cl::ZeroOrMore, cl::init(false),
160 cl::cat(PollyCategory));
161
Sebastian Pop18016682014-04-08 21:20:44 +0000162static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000163 PollyDelinearizeX("polly-delinearize",
164 cl::desc("Delinearize array access functions"),
165 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000166 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000167
Tobias Grossera1689932014-02-18 18:49:49 +0000168static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000169 VerifyScops("polly-detect-verify",
170 cl::desc("Verify the detected SCoPs after each transformation"),
171 cl::Hidden, cl::init(false), cl::ZeroOrMore,
172 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000173
Johannes Doerferte526de52015-09-21 19:10:11 +0000174/// @brief The minimal trip count under which loops are considered unprofitable.
175static const unsigned MIN_LOOP_TRIP_COUNT = 8;
176
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000177bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000178bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000179StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000180
Tobias Grosser75805372011-04-29 06:27:02 +0000181//===----------------------------------------------------------------------===//
182// Statistics.
183
184STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
185
Tobias Grosser8519f892013-12-18 10:49:53 +0000186class DiagnosticScopFound : public DiagnosticInfo {
187private:
188 static int PluginDiagnosticKind;
189
190 Function &F;
191 std::string FileName;
192 unsigned EntryLine, ExitLine;
193
194public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000195 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
196 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000197 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000198 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000199
200 virtual void print(DiagnosticPrinter &DP) const;
201
202 static bool classof(const DiagnosticInfo *DI) {
203 return DI->getKind() == PluginDiagnosticKind;
204 }
205};
206
207int DiagnosticScopFound::PluginDiagnosticKind = 10;
208
Tobias Grosser8519f892013-12-18 10:49:53 +0000209void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000210 DP << "Polly detected an optimizable loop region (scop) in function '" << F
211 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000212
213 if (FileName.empty()) {
214 DP << "Scop location is unknown. Compile with debug info "
215 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000216 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000217 }
218
219 DP << FileName << ":" << EntryLine << ": Start of scop\n";
220 DP << FileName << ":" << ExitLine << ": End of scop";
221}
222
Tobias Grosser75805372011-04-29 06:27:02 +0000223//===----------------------------------------------------------------------===//
224// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000225
Johannes Doerfertb164c792014-09-18 11:17:17 +0000226ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000227 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000228 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000229 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000230}
231
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000232template <class RR, typename... Args>
233inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
234 Args &&... Arguments) const {
235
236 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000237 RejectLog &Log = Context.Log;
238 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000239
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000240 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000241 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000242
243 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000244 DEBUG(dbgs() << "\n");
245 } else {
246 assert(!Assert && "Verification of detected scop failed");
247 }
248
249 return false;
250}
251
Tobias Grossera1689932014-02-18 18:49:49 +0000252bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
253 if (!ValidRegions.count(&R))
254 return false;
255
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000256 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000257 DetectionContextMap.erase(&R);
258 const auto &It = DetectionContextMap.insert(
259 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
260 false /*verifying*/)));
261 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000262 return isValidRegion(Context);
263 }
Tobias Grossera1689932014-02-18 18:49:49 +0000264
265 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000266}
267
Tobias Grosser4f129a62011-10-08 00:30:55 +0000268std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000269 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000270 return "";
271
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000272 // Get the first error we found. Even in keep-going mode, this is the first
273 // reason that caused the candidate to be rejected.
274 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000275
276 // This can happen when we marked a region invalid, but didn't track
277 // an error for it.
278 if (Errors.size() == 0)
279 return "";
280
281 RejectReasonPtr RR = *Errors.begin();
282 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000283}
284
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000285bool ScopDetection::addOverApproximatedRegion(Region *AR,
286 DetectionContext &Context) const {
287
288 // If we already know about Ar we can exit.
289 if (!Context.NonAffineSubRegionSet.insert(AR))
290 return true;
291
292 // All loops in the region have to be overapproximated too if there
293 // are accesses that depend on the iteration count.
294 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000295 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000296 if (AR->contains(L))
297 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000298 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000299
300 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000301}
302
Johannes Doerfert09e36972015-10-07 20:17:36 +0000303bool ScopDetection::onlyValidRequiredInvariantLoads(
304 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
305 Region &CurRegion = Context.CurRegion;
306
307 for (LoadInst *Load : RequiredILS)
308 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
309 return false;
310
311 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
312
313 return true;
314}
315
316bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
317 Value *BaseAddress) const {
318
319 InvariantLoadsSetTy AccessILS;
320 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
321 return false;
322
323 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
324 return false;
325
326 return true;
327}
328
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000329bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000330 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000331 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000332 Loop *L = LI->getLoopFor(&BB);
333 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000334
Johannes Doerfert09e36972015-10-07 20:17:36 +0000335 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000336 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000337
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000338 if (!IsLoopBranch && AllowNonAffineSubRegions &&
339 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
340 return true;
341
342 if (IsLoopBranch)
343 return false;
344
345 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
346 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000347}
348
349bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000350 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000351 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000352
353 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
354 auto Opcode = BinOp->getOpcode();
355 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
356 Value *Op0 = BinOp->getOperand(0);
357 Value *Op1 = BinOp->getOperand(1);
358 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
359 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
360 }
361 }
362
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000363 // Non constant conditions of branches need to be ICmpInst.
364 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000365 if (!IsLoopBranch && AllowNonAffineSubRegions &&
366 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
367 return true;
368 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000369 }
Tobias Grosser75805372011-04-29 06:27:02 +0000370
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000371 ICmpInst *ICmp = cast<ICmpInst>(Condition);
372 // Unsigned comparisons are not allowed. They trigger overflow problems
373 // in the code generation.
374 //
375 // TODO: This is not sufficient and just hides bugs. However it does pretty
376 // well.
377 if (ICmp->isUnsigned() && !AllowUnsigned)
378 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000379
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000380 // Are both operands of the ICmp affine?
381 if (isa<UndefValue>(ICmp->getOperand(0)) ||
382 isa<UndefValue>(ICmp->getOperand(1)))
383 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000384
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000385 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
386 // for arbitrary pointer expressions at the moment. Until
387 // this is fixed we disallow pointer expressions completely.
388 if (ICmp->getOperand(0)->getType()->isPointerTy())
389 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000390
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000391 Loop *L = LI->getLoopFor(ICmp->getParent());
392 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
393 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000394
Johannes Doerfert09e36972015-10-07 20:17:36 +0000395 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000396 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000397
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000398 if (!IsLoopBranch && AllowNonAffineSubRegions &&
399 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
400 return true;
401
402 if (IsLoopBranch)
403 return false;
404
405 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
406 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000407}
408
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000409bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000410 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000411 DetectionContext &Context) const {
412 Region &CurRegion = Context.CurRegion;
413
414 TerminatorInst *TI = BB.getTerminator();
415
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000416 if (AllowUnreachable && isa<UnreachableInst>(TI))
417 return true;
418
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000419 // Return instructions are only valid if the region is the top level region.
420 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
421 return true;
422
423 Value *Condition = getConditionFromTerminator(TI);
424
425 if (!Condition)
426 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
427
428 // UndefValue is not allowed as condition.
429 if (isa<UndefValue>(Condition))
430 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
431
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000432 // Constant integer conditions are always affine.
433 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000434 return true;
435
436 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000437 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000438
439 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
440 assert(SI && "Terminator was neither branch nor switch");
441
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000442 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000443}
444
Johannes Doerfertcea61932016-02-21 19:13:19 +0000445bool ScopDetection::isValidCallInst(CallInst &CI,
446 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000447 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000448 return false;
449
450 if (CI.doesNotAccessMemory())
451 return true;
452
Johannes Doerfertcea61932016-02-21 19:13:19 +0000453 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000454 if (isValidIntrinsicInst(*II, Context))
455 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000456
Tobias Grosser75805372011-04-29 06:27:02 +0000457 Function *CalledFunction = CI.getCalledFunction();
458
459 // Indirect calls are not supported.
460 if (CalledFunction == 0)
461 return false;
462
Johannes Doerferta7920982016-02-25 14:08:48 +0000463 switch (AA->getModRefBehavior(CalledFunction)) {
464 case llvm::FMRB_UnknownModRefBehavior:
465 return false;
466 case llvm::FMRB_DoesNotAccessMemory:
467 case llvm::FMRB_OnlyReadsMemory:
468 // Implicitly disable delinearization since we have an unknown
469 // accesses with an unknown access function.
470 Context.HasUnknownAccess = true;
471 Context.AST.add(&CI);
472 return true;
473 case llvm::FMRB_OnlyReadsArgumentPointees:
474 case llvm::FMRB_OnlyAccessesArgumentPointees:
475 for (const auto &Arg : CI.arg_operands()) {
476 if (!Arg->getType()->isPointerTy())
477 continue;
478
479 // Bail if a pointer argument has a base address not known to
480 // ScalarEvolution. Note that a zero pointer is acceptable.
481 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
482 if (ArgSCEV->isZero())
483 continue;
484
485 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
486 if (!BP)
487 return false;
488
489 // Implicitly disable delinearization since we have an unknown
490 // accesses with an unknown access function.
491 Context.HasUnknownAccess = true;
492 }
493
494 Context.AST.add(&CI);
495 return true;
496 }
497
Johannes Doerfertcea61932016-02-21 19:13:19 +0000498 return false;
499}
500
501bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
502 DetectionContext &Context) const {
503 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000504 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000505
Johannes Doerfertcea61932016-02-21 19:13:19 +0000506 // The closest loop surrounding the call instruction.
507 Loop *L = LI->getLoopFor(II.getParent());
508
509 // The access function and base pointer for memory intrinsics.
510 const SCEV *AF;
511 const SCEVUnknown *BP;
512
513 switch (II.getIntrinsicID()) {
514 // Memory intrinsics that can be represented are supported.
515 case llvm::Intrinsic::memmove:
516 case llvm::Intrinsic::memcpy:
517 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
518 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
519 // Bail if the source pointer is not valid.
520 if (!isValidAccess(&II, AF, BP, Context))
521 return false;
522 // Fall through
523 case llvm::Intrinsic::memset:
524 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
525 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
526 // Bail if the destination pointer is not valid.
527 if (!isValidAccess(&II, AF, BP, Context))
528 return false;
529
530 // Bail if the length is not affine.
531 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L),
532 Context))
533 return false;
534
535 return true;
536 default:
537 break;
538 }
539
Tobias Grosser75805372011-04-29 06:27:02 +0000540 return false;
541}
542
Tobias Grosser458fb782014-01-28 12:58:58 +0000543bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
544 // A reference to function argument or constant value is invariant.
545 if (isa<Argument>(Val) || isa<Constant>(Val))
546 return true;
547
548 const Instruction *I = dyn_cast<Instruction>(&Val);
549 if (!I)
550 return false;
551
552 if (!Reg.contains(I))
553 return true;
554
555 if (I->mayHaveSideEffects())
556 return false;
557
558 // When Val is a Phi node, it is likely not invariant. We do not check whether
559 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
560 // invariant. Recursively checking the operators of Phi nodes would lead to
561 // infinite recursion.
562 if (isa<PHINode>(*I))
563 return false;
564
Tobias Grosser26108892014-04-02 20:18:19 +0000565 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000566 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000567 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000568
Tobias Grosser458fb782014-01-28 12:58:58 +0000569 return true;
570}
571
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000572/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
573/// register the '...' components.
574///
575/// Array access expressions as they are generated by gfortran contain smax(0,
576/// size) expressions that confuse the 'normal' delinearization algorithm.
577/// However, if we extract such expressions before the normal delinearization
578/// takes place they can actually help to identify array size expressions in
579/// fortran accesses. For the subsequently following delinearization the smax(0,
580/// size) component can be replaced by just 'size'. This is correct as we will
581/// always add and verify the assumption that for all subscript expressions
582/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
583/// that 0 <= size, which means smax(0, size) == size.
584struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
585public:
586 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
587 std::vector<const SCEV *> *Terms = nullptr) {
588
589 SCEVRemoveMax D(SE, Terms);
590 return D.visit(Expr);
591 }
592
593 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
594 : SE(SE), Terms(Terms) {}
595
596 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
597
598 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
599 return Expr;
600 }
601
602 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
603 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
604 }
605
606 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
607
608 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000609 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000610 auto Res = visit(Expr->getOperand(1));
611 if (Terms)
612 (*Terms).push_back(Res);
613 return Res;
614 }
615
616 return Expr;
617 }
618
Roman Gareev8aa43752015-12-17 20:37:17 +0000619 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000620
621 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
622
623 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
624 return Expr;
625 }
626
627 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
628
629 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
630 SmallVector<const SCEV *, 5> NewOps;
631 for (const SCEV *Op : Expr->operands())
632 NewOps.push_back(visit(Op));
633
634 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
635 }
636
637 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
638 SmallVector<const SCEV *, 5> NewOps;
639 for (const SCEV *Op : Expr->operands())
640 NewOps.push_back(visit(Op));
641
642 return SE.getAddExpr(NewOps);
643 }
644
645 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
646 SmallVector<const SCEV *, 5> NewOps;
647 for (const SCEV *Op : Expr->operands())
648 NewOps.push_back(visit(Op));
649
650 return SE.getMulExpr(NewOps);
651 }
652
653private:
654 ScalarEvolution &SE;
655 std::vector<const SCEV *> *Terms;
656};
657
Tobias Grosserd68ba422015-11-24 05:00:36 +0000658SmallVector<const SCEV *, 4>
659ScopDetection::getDelinearizationTerms(DetectionContext &Context,
660 const SCEVUnknown *BasePointer) const {
661 SmallVector<const SCEV *, 4> Terms;
662 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000663 std::vector<const SCEV *> MaxTerms;
664 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
665 if (MaxTerms.size() > 0) {
666 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
667 continue;
668 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000669 // In case the outermost expression is a plain add, we check if any of its
670 // terms has the form 4 * %inst * %param * %param ..., aka a term that
671 // contains a product between a parameter and an instruction that is
672 // inside the scop. Such instructions, if allowed at all, are instructions
673 // SCEV can not represent, but Polly is still looking through. As a
674 // result, these instructions can depend on induction variables and are
675 // most likely no array sizes. However, terms that are multiplied with
676 // them are likely candidates for array sizes.
677 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
678 for (auto Op : AF->operands()) {
679 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
680 SE->collectParametricTerms(AF2, Terms);
681 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
682 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000683
Tobias Grosserd68ba422015-11-24 05:00:36 +0000684 for (auto *MulOp : AF2->operands()) {
685 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
686 Operands.push_back(Const);
687 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
688 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
689 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000690 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000691
692 } else {
693 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000694 }
695 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000696 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000697 if (Operands.size())
698 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000699 }
700 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000701 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000702 if (Terms.empty())
703 SE->collectParametricTerms(Pair.second, Terms);
704 }
705 return Terms;
706}
Sebastian Pope8863b82014-05-12 19:02:02 +0000707
Tobias Grosserd68ba422015-11-24 05:00:36 +0000708bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
709 SmallVectorImpl<const SCEV *> &Sizes,
710 const SCEVUnknown *BasePointer) const {
711 Value *BaseValue = BasePointer->getValue();
712 Region &CurRegion = Context.CurRegion;
713 for (const SCEV *DelinearizedSize : Sizes) {
714 if (!isAffine(DelinearizedSize, Context, nullptr)) {
715 Sizes.clear();
716 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000717 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000718 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
719 auto *V = dyn_cast<Value>(Unknown->getValue());
720 if (auto *Load = dyn_cast<LoadInst>(V)) {
721 if (Context.CurRegion.contains(Load) &&
722 isHoistableLoad(Load, CurRegion, *LI, *SE))
723 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000724 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000725 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000726 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000727 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000728 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000729 Context, /*Assert=*/true, DelinearizedSize,
730 Context.Accesses[BasePointer].front().first, BaseValue);
731 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000732
Tobias Grosserd68ba422015-11-24 05:00:36 +0000733 // No array shape derived.
734 if (Sizes.empty()) {
735 if (AllowNonAffine)
736 return true;
737
Tobias Grosser230acc42014-09-13 14:47:55 +0000738 for (const auto &Pair : Context.Accesses[BasePointer]) {
739 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000740 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000741
Tobias Grosserd68ba422015-11-24 05:00:36 +0000742 if (!isAffine(AF, Context, BaseValue)) {
743 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
744 BaseValue);
745 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000746 return false;
747 }
748 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000749 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000750 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000751 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000752}
753
Tobias Grosserd68ba422015-11-24 05:00:36 +0000754// We first store the resulting memory accesses in TempMemoryAccesses. Only
755// if the access functions for all memory accesses have been successfully
756// delinearized we continue. Otherwise, we either report a failure or, if
757// non-affine accesses are allowed, we drop the information. In case the
758// information is dropped the memory accesses need to be overapproximated
759// when translated to a polyhedral representation.
760bool ScopDetection::computeAccessFunctions(
761 DetectionContext &Context, const SCEVUnknown *BasePointer,
762 std::shared_ptr<ArrayShape> Shape) const {
763 Value *BaseValue = BasePointer->getValue();
764 bool BasePtrHasNonAffine = false;
765 MapInsnToMemAcc TempMemoryAccesses;
766 for (const auto &Pair : Context.Accesses[BasePointer]) {
767 const Instruction *Insn = Pair.first;
768 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000769 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000770 bool IsNonAffine = false;
771 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
772 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
773
774 if (!AF) {
775 if (isAffine(Pair.second, Context, BaseValue))
776 Acc->DelinearizedSubscripts.push_back(Pair.second);
777 else
778 IsNonAffine = true;
779 } else {
780 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
781 Shape->DelinearizedSizes);
782 if (Acc->DelinearizedSubscripts.size() == 0)
783 IsNonAffine = true;
784 for (const SCEV *S : Acc->DelinearizedSubscripts)
785 if (!isAffine(S, Context, BaseValue))
786 IsNonAffine = true;
787 }
788
789 // (Possibly) report non affine access
790 if (IsNonAffine) {
791 BasePtrHasNonAffine = true;
792 if (!AllowNonAffine)
793 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
794 Insn, BaseValue);
795 if (!KeepGoing && !AllowNonAffine)
796 return false;
797 }
798 }
799
800 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000801 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
802 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000803
804 return true;
805}
806
807bool ScopDetection::hasBaseAffineAccesses(
808 DetectionContext &Context, const SCEVUnknown *BasePointer) const {
809 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
810
811 auto Terms = getDelinearizationTerms(Context, BasePointer);
812
813 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
814 Context.ElementSize[BasePointer]);
815
816 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer))
817 return false;
818
819 return computeAccessFunctions(Context, BasePointer, Shape);
820}
821
822bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000823 // TODO: If we have an unknown access and other non-affine accesses we do
824 // not try to delinearize them for now.
825 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
826 return AllowNonAffine;
827
Tobias Grosserd68ba422015-11-24 05:00:36 +0000828 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses)
829 if (!hasBaseAffineAccesses(Context, BasePointer)) {
830 if (KeepGoing)
831 continue;
832 else
833 return false;
834 }
835 return true;
836}
837
Johannes Doerfertcea61932016-02-21 19:13:19 +0000838bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
839 const SCEVUnknown *BP,
840 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000841
Johannes Doerfertcea61932016-02-21 19:13:19 +0000842 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000843 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000844
Johannes Doerfertcea61932016-02-21 19:13:19 +0000845 auto *BV = BP->getValue();
846 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000847 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000848
Johannes Doerfertcea61932016-02-21 19:13:19 +0000849 // FIXME: Think about allowing IntToPtrInst
850 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
851 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
852
Tobias Grosser458fb782014-01-28 12:58:58 +0000853 // Check that the base address of the access is invariant in the current
854 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000855 if (!isInvariant(*BV, Context.CurRegion))
856 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000857
Johannes Doerfertcea61932016-02-21 19:13:19 +0000858 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000859
Johannes Doerfertcea61932016-02-21 19:13:19 +0000860 const SCEV *Size;
861 if (!isa<MemIntrinsic>(Inst)) {
862 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000863 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000864 auto *SizeTy =
865 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
866 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000867 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000868
Johannes Doerfertcea61932016-02-21 19:13:19 +0000869 if (Context.ElementSize[BP]) {
870 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
871 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
872 Inst, BV);
873
874 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
875 } else {
876 Context.ElementSize[BP] = Size;
877 }
878
879 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000880 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000881 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000882 for (const Loop *L : Loops)
883 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000884 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000885
Johannes Doerfertcea61932016-02-21 19:13:19 +0000886 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Context, BV);
887 // Do not try to delinearize memory intrinsics and force them to be affine.
888 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
889 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
890 BV);
891 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
892 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000893
Johannes Doerfertcea61932016-02-21 19:13:19 +0000894 if (!IsAffine)
895 Context.NonAffineAccesses.insert(BP);
896 } else if (!AllowNonAffine && !IsAffine) {
897 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
898 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000899 }
Tobias Grosser75805372011-04-29 06:27:02 +0000900
Tobias Grosser1eedb672014-09-24 21:04:29 +0000901 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000902 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000903
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000904 // Check if the base pointer of the memory access does alias with
905 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000906 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000907 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000908 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000909 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000910
Tobias Grosser1eedb672014-09-24 21:04:29 +0000911 if (!AS.isMustAlias()) {
912 if (PollyUseRuntimeAliasChecks) {
913 bool CanBuildRunTimeCheck = true;
914 // The run-time alias check places code that involves the base pointer at
915 // the beginning of the SCoP. This breaks if the base pointer is defined
916 // inside the scop. Hence, we can only create a run-time check if we are
917 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000918 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000919 for (const auto &Ptr : AS) {
920 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000921 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000922 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000923 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000924 Context.RequiredILS.insert(Load);
925 continue;
926 }
927
Tobias Grosser1eedb672014-09-24 21:04:29 +0000928 CanBuildRunTimeCheck = false;
929 break;
930 }
931 }
932
933 if (CanBuildRunTimeCheck)
934 return true;
935 }
Michael Kruse70131d32016-01-27 17:09:17 +0000936 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000937 }
Tobias Grosser75805372011-04-29 06:27:02 +0000938
939 return true;
940}
941
Johannes Doerfertcea61932016-02-21 19:13:19 +0000942bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
943 DetectionContext &Context) const {
944 Value *Ptr = Inst.getPointerOperand();
945 Loop *L = LI->getLoopFor(Inst.getParent());
946 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
947 const SCEVUnknown *BasePointer;
948
949 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
950
951 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
952}
953
Tobias Grosser75805372011-04-29 06:27:02 +0000954bool ScopDetection::isValidInstruction(Instruction &Inst,
955 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000956 for (auto &Op : Inst.operands()) {
957 auto *OpInst = dyn_cast<Instruction>(&Op);
958
959 if (!OpInst)
960 continue;
961
962 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
963 return false;
964 }
965
Tobias Grosser75805372011-04-29 06:27:02 +0000966 // We only check the call instruction but not invoke instruction.
967 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000968 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000969 return true;
970
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000971 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000972 }
973
974 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000975 if (!isa<AllocaInst>(Inst))
976 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000977
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000978 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000979 }
980
981 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +0000982 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
983 Context.hasStores |= MemInst.isLoad();
984 Context.hasLoads |= MemInst.isStore();
985 if (!MemInst.isSimple())
986 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
987 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +0000988
Michael Kruse70131d32016-01-27 17:09:17 +0000989 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000990 }
Tobias Grosser75805372011-04-29 06:27:02 +0000991
992 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000993 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000994}
995
Johannes Doerfertd020b772015-08-27 06:53:52 +0000996bool ScopDetection::canUseISLTripCount(Loop *L,
997 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000998 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
999 // need to overapproximate it as a boxed loop.
1000 SmallVector<BasicBlock *, 4> LoopControlBlocks;
1001 L->getLoopLatches(LoopControlBlocks);
1002 L->getExitingBlocks(LoopControlBlocks);
1003 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001004 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001005 return false;
1006 }
1007
Johannes Doerfertd020b772015-08-27 06:53:52 +00001008 // We can use ISL to compute the trip count of L.
1009 return true;
1010}
1011
Tobias Grosser75805372011-04-29 06:27:02 +00001012bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001013 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001014 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001015
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001016 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001017 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001018 while (R != &Context.CurRegion && !R->contains(L))
1019 R = R->getParent();
1020
1021 if (addOverApproximatedRegion(R, Context))
1022 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001023 }
Tobias Grosser75805372011-04-29 06:27:02 +00001024
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001025 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001026 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001027}
1028
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001029/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +00001030/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +00001031static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001032 auto *TripCount = SE.getBackedgeTakenCount(L);
1033
Johannes Doerfertf61df692015-10-04 14:56:08 +00001034 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001035 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001036 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1037 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1038 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001039
1040 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001041 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001042
1043 return count;
1044}
1045
Johannes Doerfertf61df692015-10-04 14:56:08 +00001046int ScopDetection::countBeneficialLoops(Region *R) const {
1047 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001048
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001049 auto L = LI->getLoopFor(R->getEntry());
1050 L = L ? R->outermostLoopInRegion(L) : nullptr;
1051 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001052
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001053 auto SubLoops =
1054 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1055
1056 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001057 if (R->contains(SubLoop))
1058 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001059
Johannes Doerfertf61df692015-10-04 14:56:08 +00001060 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001061}
1062
Tobias Grosser75805372011-04-29 06:27:02 +00001063Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001064 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001065 std::unique_ptr<Region> LastValidRegion;
1066 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001067
1068 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1069
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001070 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001071 const auto &It = DetectionContextMap.insert(std::make_pair(
1072 ExpandedRegion.get(),
1073 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1074 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001075 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001076 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001077
Johannes Doerfert717b8662015-09-08 21:44:27 +00001078 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001079 // If the exit is valid check all blocks
1080 // - if true, a valid region was found => store it + keep expanding
1081 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001082 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1083 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001084 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001085 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001086
Tobias Grosserd7e58642013-04-10 06:55:45 +00001087 // Store this region, because it is the greatest valid (encountered so
1088 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001089 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001090 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001091
1092 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001093 ExpandedRegion =
1094 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001095
1096 } else {
1097 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001098 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001099 ExpandedRegion =
1100 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001101 }
Tobias Grosser75805372011-04-29 06:27:02 +00001102 }
1103
Tobias Grosser378a9f22013-11-16 19:34:11 +00001104 DEBUG({
1105 if (LastValidRegion)
1106 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1107 else
1108 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1109 });
Tobias Grosser75805372011-04-29 06:27:02 +00001110
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001111 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001112}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001113static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001114 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001115 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001116 return false;
1117
1118 return true;
1119}
Tobias Grosser75805372011-04-29 06:27:02 +00001120
Johannes Doerferte46925f2015-10-01 10:59:14 +00001121unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001122 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001123 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001124 if (ValidRegions.count(SubRegion.get())) {
1125 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001126 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001127 } else
1128 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001129 }
1130 return Count;
1131}
1132
Johannes Doerferte46925f2015-10-01 10:59:14 +00001133void ScopDetection::removeCachedResults(const Region &R) {
1134 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001135 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001136}
1137
Tobias Grosser75805372011-04-29 06:27:02 +00001138void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001139 const auto &It = DetectionContextMap.insert(
1140 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1141 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001142
1143 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +00001144 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001145 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001146 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001147 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001148 RegionIsValid = isValidRegion(Context);
1149
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001150 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001151
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001152 if (PollyTrackFailures && HasErrors)
1153 RejectLogs.insert(std::make_pair(&R, Context.Log));
1154
Johannes Doerferte46925f2015-10-01 10:59:14 +00001155 if (HasErrors) {
1156 removeCachedResults(R);
1157 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001158 ++ValidRegion;
1159 ValidRegions.insert(&R);
1160 return;
1161 }
1162
David Blaikieb035f6d2014-04-15 18:45:27 +00001163 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001164 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001165
1166 // Try to expand regions.
1167 //
1168 // As the region tree normally only contains canonical regions, non canonical
1169 // regions that form a Scop are not found. Therefore, those non canonical
1170 // regions are checked by expanding the canonical ones.
1171
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001172 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001173
David Blaikieb035f6d2014-04-15 18:45:27 +00001174 for (auto &SubRegion : R)
1175 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001176
Tobias Grosser26108892014-04-02 20:18:19 +00001177 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001178 // Skip regions that had errors.
1179 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1180 if (HadErrors)
1181 continue;
1182
Tobias Grosser75805372011-04-29 06:27:02 +00001183 // Skip invalid regions. Regions may become invalid, if they are element of
1184 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001185 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001186 continue;
1187
1188 Region *ExpandedR = expandRegion(*CurrentRegion);
1189
1190 if (!ExpandedR)
1191 continue;
1192
1193 R.addSubRegion(ExpandedR, true);
1194 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001195 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001196
Tobias Grosser28a70c52014-01-29 19:05:30 +00001197 // Erase all (direct and indirect) children of ExpandedR from the valid
1198 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001199 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001200 }
1201}
1202
1203bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001204 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001205
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001206 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001207 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001208 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001209 return false;
1210 }
1211
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001212 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001213 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1214
1215 // Also check exception blocks (and possibly register them as non-affine
1216 // regions). Even though exception blocks are not modeled, we use them
1217 // to forward-propagate domain constraints during ScopInfo construction.
1218 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1219 return false;
1220
1221 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001222 continue;
1223
Tobias Grosser1d191902014-03-03 13:13:55 +00001224 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001225 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001226 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001227 }
Tobias Grosser75805372011-04-29 06:27:02 +00001228
Sebastian Pope8863b82014-05-12 19:02:02 +00001229 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001230 return false;
1231
Tobias Grosser75805372011-04-29 06:27:02 +00001232 return true;
1233}
1234
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001235bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1236 int NumLoops) const {
1237 int InstCount = 0;
1238
1239 for (auto *BB : Context.CurRegion.blocks())
1240 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001241 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001242
1243 InstCount = InstCount / NumLoops;
1244
1245 return InstCount >= ProfitabilityMinPerLoopInstructions;
1246}
1247
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001248bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1249 Region &CurRegion = Context.CurRegion;
1250
1251 if (PollyProcessUnprofitable)
1252 return true;
1253
1254 // We can probably not do a lot on scops that only write or only read
1255 // data.
1256 if (!Context.hasStores || !Context.hasLoads)
1257 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1258
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001259 int NumLoops = countBeneficialLoops(&CurRegion);
1260 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001261
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001262 // Scops with at least two loops may allow either loop fusion or tiling and
1263 // are consequently interesting to look at.
1264 if (NumAffineLoops >= 2)
1265 return true;
1266
1267 // Scops that contain a loop with a non-trivial amount of computation per
1268 // loop-iteration are interesting as we may be able to parallelize such
1269 // loops. Individual loops that have only a small amount of computation
1270 // per-iteration are performance-wise very fragile as any change to the
1271 // loop induction variables may affect performance. To not cause spurious
1272 // performance regressions, we do not consider such loops.
1273 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1274 return true;
1275
1276 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001277}
1278
Tobias Grosser75805372011-04-29 06:27:02 +00001279bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001280 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001281
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001282 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001283
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001284 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001285 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001286 return false;
1287 }
1288
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001289 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001290 DEBUG({
1291 dbgs() << "Region entry does not match -polly-region-only";
1292 dbgs() << "\n";
1293 });
1294 return false;
1295 }
1296
Tobias Grosserd654c252012-04-10 18:12:19 +00001297 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001298 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001299 if (CurRegion.getEntry() ==
1300 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1301 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001302
Hongbin Zheng94868e62012-04-07 12:29:17 +00001303 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001304 return false;
1305
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001306 DebugLoc DbgLoc;
1307 if (!isReducibleRegion(CurRegion, DbgLoc))
1308 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1309 &CurRegion, DbgLoc);
1310
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001311 if (!isProfitableRegion(Context))
1312 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001313
Tobias Grosser75805372011-04-29 06:27:02 +00001314 DEBUG(dbgs() << "OK\n");
1315 return true;
1316}
1317
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001318void ScopDetection::markFunctionAsInvalid(Function *F) const {
1319 F->addFnAttr(PollySkipFnAttr);
1320}
1321
Tobias Grosser75805372011-04-29 06:27:02 +00001322bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001323 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001324}
1325
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001326void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001327 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001328 unsigned LineEntry, LineExit;
1329 std::string FileName;
1330
Tobias Grosser00dc3092014-03-02 12:02:46 +00001331 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001332 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1333 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001334 }
1335}
1336
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001337void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001338 for (const Region *R : ValidRegions) {
1339 const Region *Parent = R->getParent();
1340 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1341 emitRejectionRemarks(F, RejectLogs.at(Parent));
1342 }
1343}
1344
1345void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1346 const Region *R) {
1347 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001348 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001349 if (IsValid)
1350 continue;
1351
1352 bool IsLeaf = Child->begin() == Child->end();
1353 if (!IsLeaf)
1354 emitMissedRemarksForLeaves(F, Child.get());
1355 else {
1356 if (RejectLogs.count(Child.get())) {
1357 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1358 }
1359 }
1360 }
1361}
1362
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001363bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1364 BasicBlock *REntry = R.getEntry();
1365 BasicBlock *RExit = R.getExit();
1366 // Map to match the color of a BasicBlock during the DFS walk.
1367 DenseMap<const BasicBlock *, Color> BBColorMap;
1368 // Stack keeping track of current BB and index of next child to be processed.
1369 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1370
1371 unsigned AdjacentBlockIndex = 0;
1372 BasicBlock *CurrBB, *SuccBB;
1373 CurrBB = REntry;
1374
1375 // Initialize the map for all BB with WHITE color.
1376 for (auto *BB : R.blocks())
1377 BBColorMap[BB] = ScopDetection::WHITE;
1378
1379 // Process the entry block of the Region.
1380 BBColorMap[CurrBB] = ScopDetection::GREY;
1381 DFSStack.push(std::make_pair(CurrBB, 0));
1382
1383 while (!DFSStack.empty()) {
1384 // Get next BB on stack to be processed.
1385 CurrBB = DFSStack.top().first;
1386 AdjacentBlockIndex = DFSStack.top().second;
1387 DFSStack.pop();
1388
1389 // Loop to iterate over the successors of current BB.
1390 const TerminatorInst *TInst = CurrBB->getTerminator();
1391 unsigned NSucc = TInst->getNumSuccessors();
1392 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1393 ++I, ++AdjacentBlockIndex) {
1394 SuccBB = TInst->getSuccessor(I);
1395
1396 // Checks for region exit block and self-loops in BB.
1397 if (SuccBB == RExit || SuccBB == CurrBB)
1398 continue;
1399
1400 // WHITE indicates an unvisited BB in DFS walk.
1401 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1402 // Push the current BB and the index of the next child to be visited.
1403 DFSStack.push(std::make_pair(CurrBB, I + 1));
1404 // Push the next BB to be processed.
1405 DFSStack.push(std::make_pair(SuccBB, 0));
1406 // First time the BB is being processed.
1407 BBColorMap[SuccBB] = ScopDetection::GREY;
1408 break;
1409 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1410 // GREY indicates a loop in the control flow.
1411 // If the destination dominates the source, it is a natural loop
1412 // else, an irreducible control flow in the region is detected.
1413 if (!DT->dominates(SuccBB, CurrBB)) {
1414 // Get debug info of instruction which causes irregular control flow.
1415 DbgLoc = TInst->getDebugLoc();
1416 return false;
1417 }
1418 }
1419 }
1420
1421 // If all children of current BB have been processed,
1422 // then mark that BB as fully processed.
1423 if (AdjacentBlockIndex == NSucc)
1424 BBColorMap[CurrBB] = ScopDetection::BLACK;
1425 }
1426
1427 return true;
1428}
1429
Tobias Grosser75805372011-04-29 06:27:02 +00001430bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001431 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001432 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001433 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001434 return false;
1435
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001436 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001437 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001438 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001439 Region *TopRegion = RI->getTopLevelRegion();
1440
Tobias Grosser2ff87232011-10-23 11:17:06 +00001441 releaseMemory();
1442
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001443 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001444 return false;
1445
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001446 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001447 return false;
1448
1449 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001450
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001451 // Only makes sense when we tracked errors.
1452 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001453 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001454 emitMissedRemarksForLeaves(F, TopRegion);
1455 }
1456
Johannes Doerferta05214f2014-10-15 23:24:28 +00001457 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001458 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001459
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001460 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001461 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001462 return false;
1463}
1464
Johannes Doerfertba65c162015-02-24 11:45:21 +00001465bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1466 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001467 const DetectionContext *DC = getDetectionContext(ScopR);
1468 assert(DC && "ScopR is no valid region!");
1469 return DC->NonAffineSubRegionSet.count(SubR);
1470}
1471
1472const ScopDetection::DetectionContext *
1473ScopDetection::getDetectionContext(const Region *R) const {
1474 auto DCMIt = DetectionContextMap.find(R);
1475 if (DCMIt == DetectionContextMap.end())
1476 return nullptr;
1477 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001478}
1479
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001480const ScopDetection::BoxedLoopsSetTy *
1481ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001482 const DetectionContext *DC = getDetectionContext(R);
1483 assert(DC && "ScopR is no valid region!");
1484 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001485}
1486
Hongbin Zheng22623202016-02-15 00:20:58 +00001487const MapInsnToMemAcc *
1488ScopDetection::getInsnToMemAccMap(const Region *R) const {
1489 const DetectionContext *DC = getDetectionContext(R);
1490 assert(DC && "ScopR is no valid region!");
1491 return &DC->InsnToMemAcc;
1492}
1493
Johannes Doerfert09e36972015-10-07 20:17:36 +00001494const InvariantLoadsSetTy *
1495ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001496 const DetectionContext *DC = getDetectionContext(R);
1497 assert(DC && "ScopR is no valid region!");
1498 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001499}
1500
Tobias Grosser75805372011-04-29 06:27:02 +00001501void polly::ScopDetection::verifyRegion(const Region &R) const {
1502 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001503
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001504 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001505 isValidRegion(Context);
1506}
1507
1508void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001509 if (!VerifyScops)
1510 return;
1511
Tobias Grosser26108892014-04-02 20:18:19 +00001512 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001513 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001514}
1515
1516void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001517 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001518 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001519 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001520 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001521 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001522 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001523 AU.setPreservesAll();
1524}
1525
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001526void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001527 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001528 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001529
1530 OS << "\n";
1531}
1532
1533void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001534 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001535 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001536 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001537
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001538 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001539}
1540
1541char ScopDetection::ID = 0;
1542
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001543Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1544
Tobias Grosser73600b82011-10-08 00:30:40 +00001545INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1546 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001547 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001548INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001549INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001550INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001551INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001552INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001553INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1554 "Polly - Detect static control parts (SCoPs)", false, false)