blob: 6d16b9fc8ce00259f545a7ec6f7ddb0b55685d70 [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))
454 return isValidIntrinsicInst(*II, Context);
455
Tobias Grosser75805372011-04-29 06:27:02 +0000456 Function *CalledFunction = CI.getCalledFunction();
457
458 // Indirect calls are not supported.
459 if (CalledFunction == 0)
460 return false;
461
Johannes Doerfertcea61932016-02-21 19:13:19 +0000462 return false;
463}
464
465bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
466 DetectionContext &Context) const {
467 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000468 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000469
Johannes Doerfertcea61932016-02-21 19:13:19 +0000470 // The closest loop surrounding the call instruction.
471 Loop *L = LI->getLoopFor(II.getParent());
472
473 // The access function and base pointer for memory intrinsics.
474 const SCEV *AF;
475 const SCEVUnknown *BP;
476
477 switch (II.getIntrinsicID()) {
478 // Memory intrinsics that can be represented are supported.
479 case llvm::Intrinsic::memmove:
480 case llvm::Intrinsic::memcpy:
481 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
482 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
483 // Bail if the source pointer is not valid.
484 if (!isValidAccess(&II, AF, BP, Context))
485 return false;
486 // Fall through
487 case llvm::Intrinsic::memset:
488 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
489 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
490 // Bail if the destination pointer is not valid.
491 if (!isValidAccess(&II, AF, BP, Context))
492 return false;
493
494 // Bail if the length is not affine.
495 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L),
496 Context))
497 return false;
498
499 return true;
500 default:
501 break;
502 }
503
Tobias Grosser75805372011-04-29 06:27:02 +0000504 return false;
505}
506
Tobias Grosser458fb782014-01-28 12:58:58 +0000507bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
508 // A reference to function argument or constant value is invariant.
509 if (isa<Argument>(Val) || isa<Constant>(Val))
510 return true;
511
512 const Instruction *I = dyn_cast<Instruction>(&Val);
513 if (!I)
514 return false;
515
516 if (!Reg.contains(I))
517 return true;
518
519 if (I->mayHaveSideEffects())
520 return false;
521
522 // When Val is a Phi node, it is likely not invariant. We do not check whether
523 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
524 // invariant. Recursively checking the operators of Phi nodes would lead to
525 // infinite recursion.
526 if (isa<PHINode>(*I))
527 return false;
528
Tobias Grosser26108892014-04-02 20:18:19 +0000529 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000530 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000531 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000532
Tobias Grosser458fb782014-01-28 12:58:58 +0000533 return true;
534}
535
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000536/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
537/// register the '...' components.
538///
539/// Array access expressions as they are generated by gfortran contain smax(0,
540/// size) expressions that confuse the 'normal' delinearization algorithm.
541/// However, if we extract such expressions before the normal delinearization
542/// takes place they can actually help to identify array size expressions in
543/// fortran accesses. For the subsequently following delinearization the smax(0,
544/// size) component can be replaced by just 'size'. This is correct as we will
545/// always add and verify the assumption that for all subscript expressions
546/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
547/// that 0 <= size, which means smax(0, size) == size.
548struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
549public:
550 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
551 std::vector<const SCEV *> *Terms = nullptr) {
552
553 SCEVRemoveMax D(SE, Terms);
554 return D.visit(Expr);
555 }
556
557 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
558 : SE(SE), Terms(Terms) {}
559
560 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
561
562 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
563 return Expr;
564 }
565
566 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
567 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
568 }
569
570 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
571
572 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000573 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000574 auto Res = visit(Expr->getOperand(1));
575 if (Terms)
576 (*Terms).push_back(Res);
577 return Res;
578 }
579
580 return Expr;
581 }
582
Roman Gareev8aa43752015-12-17 20:37:17 +0000583 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000584
585 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
586
587 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
588 return Expr;
589 }
590
591 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
592
593 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
594 SmallVector<const SCEV *, 5> NewOps;
595 for (const SCEV *Op : Expr->operands())
596 NewOps.push_back(visit(Op));
597
598 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
599 }
600
601 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
602 SmallVector<const SCEV *, 5> NewOps;
603 for (const SCEV *Op : Expr->operands())
604 NewOps.push_back(visit(Op));
605
606 return SE.getAddExpr(NewOps);
607 }
608
609 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
610 SmallVector<const SCEV *, 5> NewOps;
611 for (const SCEV *Op : Expr->operands())
612 NewOps.push_back(visit(Op));
613
614 return SE.getMulExpr(NewOps);
615 }
616
617private:
618 ScalarEvolution &SE;
619 std::vector<const SCEV *> *Terms;
620};
621
Tobias Grosserd68ba422015-11-24 05:00:36 +0000622SmallVector<const SCEV *, 4>
623ScopDetection::getDelinearizationTerms(DetectionContext &Context,
624 const SCEVUnknown *BasePointer) const {
625 SmallVector<const SCEV *, 4> Terms;
626 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000627 std::vector<const SCEV *> MaxTerms;
628 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
629 if (MaxTerms.size() > 0) {
630 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
631 continue;
632 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000633 // In case the outermost expression is a plain add, we check if any of its
634 // terms has the form 4 * %inst * %param * %param ..., aka a term that
635 // contains a product between a parameter and an instruction that is
636 // inside the scop. Such instructions, if allowed at all, are instructions
637 // SCEV can not represent, but Polly is still looking through. As a
638 // result, these instructions can depend on induction variables and are
639 // most likely no array sizes. However, terms that are multiplied with
640 // them are likely candidates for array sizes.
641 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
642 for (auto Op : AF->operands()) {
643 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
644 SE->collectParametricTerms(AF2, Terms);
645 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
646 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000647
Tobias Grosserd68ba422015-11-24 05:00:36 +0000648 for (auto *MulOp : AF2->operands()) {
649 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
650 Operands.push_back(Const);
651 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
652 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
653 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000654 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000655
656 } else {
657 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000658 }
659 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000660 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000661 if (Operands.size())
662 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000663 }
664 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000665 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000666 if (Terms.empty())
667 SE->collectParametricTerms(Pair.second, Terms);
668 }
669 return Terms;
670}
Sebastian Pope8863b82014-05-12 19:02:02 +0000671
Tobias Grosserd68ba422015-11-24 05:00:36 +0000672bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
673 SmallVectorImpl<const SCEV *> &Sizes,
674 const SCEVUnknown *BasePointer) const {
675 Value *BaseValue = BasePointer->getValue();
676 Region &CurRegion = Context.CurRegion;
677 for (const SCEV *DelinearizedSize : Sizes) {
678 if (!isAffine(DelinearizedSize, Context, nullptr)) {
679 Sizes.clear();
680 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000681 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000682 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
683 auto *V = dyn_cast<Value>(Unknown->getValue());
684 if (auto *Load = dyn_cast<LoadInst>(V)) {
685 if (Context.CurRegion.contains(Load) &&
686 isHoistableLoad(Load, CurRegion, *LI, *SE))
687 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000688 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000689 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000690 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000691 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000692 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000693 Context, /*Assert=*/true, DelinearizedSize,
694 Context.Accesses[BasePointer].front().first, BaseValue);
695 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000696
Tobias Grosserd68ba422015-11-24 05:00:36 +0000697 // No array shape derived.
698 if (Sizes.empty()) {
699 if (AllowNonAffine)
700 return true;
701
Tobias Grosser230acc42014-09-13 14:47:55 +0000702 for (const auto &Pair : Context.Accesses[BasePointer]) {
703 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000704 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000705
Tobias Grosserd68ba422015-11-24 05:00:36 +0000706 if (!isAffine(AF, Context, BaseValue)) {
707 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
708 BaseValue);
709 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000710 return false;
711 }
712 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000713 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000714 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000715 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000716}
717
Tobias Grosserd68ba422015-11-24 05:00:36 +0000718// We first store the resulting memory accesses in TempMemoryAccesses. Only
719// if the access functions for all memory accesses have been successfully
720// delinearized we continue. Otherwise, we either report a failure or, if
721// non-affine accesses are allowed, we drop the information. In case the
722// information is dropped the memory accesses need to be overapproximated
723// when translated to a polyhedral representation.
724bool ScopDetection::computeAccessFunctions(
725 DetectionContext &Context, const SCEVUnknown *BasePointer,
726 std::shared_ptr<ArrayShape> Shape) const {
727 Value *BaseValue = BasePointer->getValue();
728 bool BasePtrHasNonAffine = false;
729 MapInsnToMemAcc TempMemoryAccesses;
730 for (const auto &Pair : Context.Accesses[BasePointer]) {
731 const Instruction *Insn = Pair.first;
732 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000733 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000734 bool IsNonAffine = false;
735 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
736 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
737
738 if (!AF) {
739 if (isAffine(Pair.second, Context, BaseValue))
740 Acc->DelinearizedSubscripts.push_back(Pair.second);
741 else
742 IsNonAffine = true;
743 } else {
744 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
745 Shape->DelinearizedSizes);
746 if (Acc->DelinearizedSubscripts.size() == 0)
747 IsNonAffine = true;
748 for (const SCEV *S : Acc->DelinearizedSubscripts)
749 if (!isAffine(S, Context, BaseValue))
750 IsNonAffine = true;
751 }
752
753 // (Possibly) report non affine access
754 if (IsNonAffine) {
755 BasePtrHasNonAffine = true;
756 if (!AllowNonAffine)
757 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
758 Insn, BaseValue);
759 if (!KeepGoing && !AllowNonAffine)
760 return false;
761 }
762 }
763
764 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000765 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
766 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000767
768 return true;
769}
770
771bool ScopDetection::hasBaseAffineAccesses(
772 DetectionContext &Context, const SCEVUnknown *BasePointer) const {
773 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
774
775 auto Terms = getDelinearizationTerms(Context, BasePointer);
776
777 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
778 Context.ElementSize[BasePointer]);
779
780 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer))
781 return false;
782
783 return computeAccessFunctions(Context, BasePointer, Shape);
784}
785
786bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
787 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses)
788 if (!hasBaseAffineAccesses(Context, BasePointer)) {
789 if (KeepGoing)
790 continue;
791 else
792 return false;
793 }
794 return true;
795}
796
Johannes Doerfertcea61932016-02-21 19:13:19 +0000797bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
798 const SCEVUnknown *BP,
799 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000800
Johannes Doerfertcea61932016-02-21 19:13:19 +0000801 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000802 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000803
Johannes Doerfertcea61932016-02-21 19:13:19 +0000804 auto *BV = BP->getValue();
805 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000806 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000807
Johannes Doerfertcea61932016-02-21 19:13:19 +0000808 // FIXME: Think about allowing IntToPtrInst
809 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
810 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
811
Tobias Grosser458fb782014-01-28 12:58:58 +0000812 // Check that the base address of the access is invariant in the current
813 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000814 if (!isInvariant(*BV, Context.CurRegion))
815 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000816
Johannes Doerfertcea61932016-02-21 19:13:19 +0000817 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000818
Johannes Doerfertcea61932016-02-21 19:13:19 +0000819 const SCEV *Size;
820 if (!isa<MemIntrinsic>(Inst)) {
821 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000822 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000823 auto *SizeTy =
824 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
825 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000826 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000827
Johannes Doerfertcea61932016-02-21 19:13:19 +0000828 if (Context.ElementSize[BP]) {
829 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
830 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
831 Inst, BV);
832
833 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
834 } else {
835 Context.ElementSize[BP] = Size;
836 }
837
838 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000839 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000840 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000841 for (const Loop *L : Loops)
842 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000843 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000844
Johannes Doerfertcea61932016-02-21 19:13:19 +0000845 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Context, BV);
846 // Do not try to delinearize memory intrinsics and force them to be affine.
847 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
848 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
849 BV);
850 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
851 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000852
Johannes Doerfertcea61932016-02-21 19:13:19 +0000853 if (!IsAffine)
854 Context.NonAffineAccesses.insert(BP);
855 } else if (!AllowNonAffine && !IsAffine) {
856 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
857 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000858 }
Tobias Grosser75805372011-04-29 06:27:02 +0000859
Tobias Grosser1eedb672014-09-24 21:04:29 +0000860 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000861 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000862
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000863 // Check if the base pointer of the memory access does alias with
864 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000865 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000866 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000867 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000868 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000869
Tobias Grosser1eedb672014-09-24 21:04:29 +0000870 if (!AS.isMustAlias()) {
871 if (PollyUseRuntimeAliasChecks) {
872 bool CanBuildRunTimeCheck = true;
873 // The run-time alias check places code that involves the base pointer at
874 // the beginning of the SCoP. This breaks if the base pointer is defined
875 // inside the scop. Hence, we can only create a run-time check if we are
876 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000877 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000878 for (const auto &Ptr : AS) {
879 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000880 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000881 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000882 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000883 Context.RequiredILS.insert(Load);
884 continue;
885 }
886
Tobias Grosser1eedb672014-09-24 21:04:29 +0000887 CanBuildRunTimeCheck = false;
888 break;
889 }
890 }
891
892 if (CanBuildRunTimeCheck)
893 return true;
894 }
Michael Kruse70131d32016-01-27 17:09:17 +0000895 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000896 }
Tobias Grosser75805372011-04-29 06:27:02 +0000897
898 return true;
899}
900
Johannes Doerfertcea61932016-02-21 19:13:19 +0000901bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
902 DetectionContext &Context) const {
903 Value *Ptr = Inst.getPointerOperand();
904 Loop *L = LI->getLoopFor(Inst.getParent());
905 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
906 const SCEVUnknown *BasePointer;
907
908 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
909
910 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
911}
912
Tobias Grosser75805372011-04-29 06:27:02 +0000913bool ScopDetection::isValidInstruction(Instruction &Inst,
914 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000915 for (auto &Op : Inst.operands()) {
916 auto *OpInst = dyn_cast<Instruction>(&Op);
917
918 if (!OpInst)
919 continue;
920
921 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
922 return false;
923 }
924
Tobias Grosser75805372011-04-29 06:27:02 +0000925 // We only check the call instruction but not invoke instruction.
926 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000927 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000928 return true;
929
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000930 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000931 }
932
933 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000934 if (!isa<AllocaInst>(Inst))
935 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000936
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000937 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000938 }
939
940 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +0000941 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
942 Context.hasStores |= MemInst.isLoad();
943 Context.hasLoads |= MemInst.isStore();
944 if (!MemInst.isSimple())
945 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
946 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +0000947
Michael Kruse70131d32016-01-27 17:09:17 +0000948 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000949 }
Tobias Grosser75805372011-04-29 06:27:02 +0000950
951 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000952 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000953}
954
Johannes Doerfertd020b772015-08-27 06:53:52 +0000955bool ScopDetection::canUseISLTripCount(Loop *L,
956 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000957 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
958 // need to overapproximate it as a boxed loop.
959 SmallVector<BasicBlock *, 4> LoopControlBlocks;
960 L->getLoopLatches(LoopControlBlocks);
961 L->getExitingBlocks(LoopControlBlocks);
962 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000963 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000964 return false;
965 }
966
Johannes Doerfertd020b772015-08-27 06:53:52 +0000967 // We can use ISL to compute the trip count of L.
968 return true;
969}
970
Tobias Grosser75805372011-04-29 06:27:02 +0000971bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000972 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000973 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000974
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000975 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000976 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000977 while (R != &Context.CurRegion && !R->contains(L))
978 R = R->getParent();
979
980 if (addOverApproximatedRegion(R, Context))
981 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000982 }
Tobias Grosser75805372011-04-29 06:27:02 +0000983
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000984 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000985 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000986}
987
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000988/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000989/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000990static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000991 auto *TripCount = SE.getBackedgeTakenCount(L);
992
Johannes Doerfertf61df692015-10-04 14:56:08 +0000993 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000994 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000995 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
996 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
997 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000998
999 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001000 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001001
1002 return count;
1003}
1004
Johannes Doerfertf61df692015-10-04 14:56:08 +00001005int ScopDetection::countBeneficialLoops(Region *R) const {
1006 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001007
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001008 auto L = LI->getLoopFor(R->getEntry());
1009 L = L ? R->outermostLoopInRegion(L) : nullptr;
1010 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001011
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001012 auto SubLoops =
1013 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1014
1015 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001016 if (R->contains(SubLoop))
1017 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001018
Johannes Doerfertf61df692015-10-04 14:56:08 +00001019 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001020}
1021
Tobias Grosser75805372011-04-29 06:27:02 +00001022Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001023 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001024 std::unique_ptr<Region> LastValidRegion;
1025 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001026
1027 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1028
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001029 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001030 const auto &It = DetectionContextMap.insert(std::make_pair(
1031 ExpandedRegion.get(),
1032 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1033 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001034 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001035 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001036
Johannes Doerfert717b8662015-09-08 21:44:27 +00001037 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001038 // If the exit is valid check all blocks
1039 // - if true, a valid region was found => store it + keep expanding
1040 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001041 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1042 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001043 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001044 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001045
Tobias Grosserd7e58642013-04-10 06:55:45 +00001046 // Store this region, because it is the greatest valid (encountered so
1047 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001048 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001049 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001050
1051 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001052 ExpandedRegion =
1053 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001054
1055 } else {
1056 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001057 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001058 ExpandedRegion =
1059 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001060 }
Tobias Grosser75805372011-04-29 06:27:02 +00001061 }
1062
Tobias Grosser378a9f22013-11-16 19:34:11 +00001063 DEBUG({
1064 if (LastValidRegion)
1065 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1066 else
1067 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1068 });
Tobias Grosser75805372011-04-29 06:27:02 +00001069
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001070 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001071}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001072static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001073 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001074 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001075 return false;
1076
1077 return true;
1078}
Tobias Grosser75805372011-04-29 06:27:02 +00001079
Johannes Doerferte46925f2015-10-01 10:59:14 +00001080unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001081 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001082 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001083 if (ValidRegions.count(SubRegion.get())) {
1084 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001085 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001086 } else
1087 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001088 }
1089 return Count;
1090}
1091
Johannes Doerferte46925f2015-10-01 10:59:14 +00001092void ScopDetection::removeCachedResults(const Region &R) {
1093 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001094 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001095}
1096
Tobias Grosser75805372011-04-29 06:27:02 +00001097void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001098 const auto &It = DetectionContextMap.insert(
1099 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1100 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001101
1102 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +00001103 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001104 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001105 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001106 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001107 RegionIsValid = isValidRegion(Context);
1108
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001109 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001110
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001111 if (PollyTrackFailures && HasErrors)
1112 RejectLogs.insert(std::make_pair(&R, Context.Log));
1113
Johannes Doerferte46925f2015-10-01 10:59:14 +00001114 if (HasErrors) {
1115 removeCachedResults(R);
1116 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001117 ++ValidRegion;
1118 ValidRegions.insert(&R);
1119 return;
1120 }
1121
David Blaikieb035f6d2014-04-15 18:45:27 +00001122 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001123 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001124
1125 // Try to expand regions.
1126 //
1127 // As the region tree normally only contains canonical regions, non canonical
1128 // regions that form a Scop are not found. Therefore, those non canonical
1129 // regions are checked by expanding the canonical ones.
1130
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001131 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001132
David Blaikieb035f6d2014-04-15 18:45:27 +00001133 for (auto &SubRegion : R)
1134 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001135
Tobias Grosser26108892014-04-02 20:18:19 +00001136 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001137 // Skip regions that had errors.
1138 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1139 if (HadErrors)
1140 continue;
1141
Tobias Grosser75805372011-04-29 06:27:02 +00001142 // Skip invalid regions. Regions may become invalid, if they are element of
1143 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001144 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001145 continue;
1146
1147 Region *ExpandedR = expandRegion(*CurrentRegion);
1148
1149 if (!ExpandedR)
1150 continue;
1151
1152 R.addSubRegion(ExpandedR, true);
1153 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001154 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001155
Tobias Grosser28a70c52014-01-29 19:05:30 +00001156 // Erase all (direct and indirect) children of ExpandedR from the valid
1157 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001158 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001159 }
1160}
1161
1162bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001163 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001164
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001165 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001166 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001167 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001168 return false;
1169 }
1170
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001171 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001172 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1173
1174 // Also check exception blocks (and possibly register them as non-affine
1175 // regions). Even though exception blocks are not modeled, we use them
1176 // to forward-propagate domain constraints during ScopInfo construction.
1177 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1178 return false;
1179
1180 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001181 continue;
1182
Tobias Grosser1d191902014-03-03 13:13:55 +00001183 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001184 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001185 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001186 }
Tobias Grosser75805372011-04-29 06:27:02 +00001187
Sebastian Pope8863b82014-05-12 19:02:02 +00001188 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001189 return false;
1190
Tobias Grosser75805372011-04-29 06:27:02 +00001191 return true;
1192}
1193
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001194bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1195 int NumLoops) const {
1196 int InstCount = 0;
1197
1198 for (auto *BB : Context.CurRegion.blocks())
1199 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001200 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001201
1202 InstCount = InstCount / NumLoops;
1203
1204 return InstCount >= ProfitabilityMinPerLoopInstructions;
1205}
1206
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001207bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1208 Region &CurRegion = Context.CurRegion;
1209
1210 if (PollyProcessUnprofitable)
1211 return true;
1212
1213 // We can probably not do a lot on scops that only write or only read
1214 // data.
1215 if (!Context.hasStores || !Context.hasLoads)
1216 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1217
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001218 int NumLoops = countBeneficialLoops(&CurRegion);
1219 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001220
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001221 // Scops with at least two loops may allow either loop fusion or tiling and
1222 // are consequently interesting to look at.
1223 if (NumAffineLoops >= 2)
1224 return true;
1225
1226 // Scops that contain a loop with a non-trivial amount of computation per
1227 // loop-iteration are interesting as we may be able to parallelize such
1228 // loops. Individual loops that have only a small amount of computation
1229 // per-iteration are performance-wise very fragile as any change to the
1230 // loop induction variables may affect performance. To not cause spurious
1231 // performance regressions, we do not consider such loops.
1232 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1233 return true;
1234
1235 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001236}
1237
Tobias Grosser75805372011-04-29 06:27:02 +00001238bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001239 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001240
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001241 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001242
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001243 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001244 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001245 return false;
1246 }
1247
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001248 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001249 DEBUG({
1250 dbgs() << "Region entry does not match -polly-region-only";
1251 dbgs() << "\n";
1252 });
1253 return false;
1254 }
1255
Tobias Grosserd654c252012-04-10 18:12:19 +00001256 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001257 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001258 if (CurRegion.getEntry() ==
1259 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1260 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001261
Hongbin Zheng94868e62012-04-07 12:29:17 +00001262 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001263 return false;
1264
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001265 DebugLoc DbgLoc;
1266 if (!isReducibleRegion(CurRegion, DbgLoc))
1267 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1268 &CurRegion, DbgLoc);
1269
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001270 if (!isProfitableRegion(Context))
1271 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001272
Tobias Grosser75805372011-04-29 06:27:02 +00001273 DEBUG(dbgs() << "OK\n");
1274 return true;
1275}
1276
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001277void ScopDetection::markFunctionAsInvalid(Function *F) const {
1278 F->addFnAttr(PollySkipFnAttr);
1279}
1280
Tobias Grosser75805372011-04-29 06:27:02 +00001281bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001282 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001283}
1284
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001285void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001286 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001287 unsigned LineEntry, LineExit;
1288 std::string FileName;
1289
Tobias Grosser00dc3092014-03-02 12:02:46 +00001290 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001291 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1292 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001293 }
1294}
1295
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001296void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001297 for (const Region *R : ValidRegions) {
1298 const Region *Parent = R->getParent();
1299 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1300 emitRejectionRemarks(F, RejectLogs.at(Parent));
1301 }
1302}
1303
1304void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1305 const Region *R) {
1306 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001307 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001308 if (IsValid)
1309 continue;
1310
1311 bool IsLeaf = Child->begin() == Child->end();
1312 if (!IsLeaf)
1313 emitMissedRemarksForLeaves(F, Child.get());
1314 else {
1315 if (RejectLogs.count(Child.get())) {
1316 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1317 }
1318 }
1319 }
1320}
1321
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001322bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1323 BasicBlock *REntry = R.getEntry();
1324 BasicBlock *RExit = R.getExit();
1325 // Map to match the color of a BasicBlock during the DFS walk.
1326 DenseMap<const BasicBlock *, Color> BBColorMap;
1327 // Stack keeping track of current BB and index of next child to be processed.
1328 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1329
1330 unsigned AdjacentBlockIndex = 0;
1331 BasicBlock *CurrBB, *SuccBB;
1332 CurrBB = REntry;
1333
1334 // Initialize the map for all BB with WHITE color.
1335 for (auto *BB : R.blocks())
1336 BBColorMap[BB] = ScopDetection::WHITE;
1337
1338 // Process the entry block of the Region.
1339 BBColorMap[CurrBB] = ScopDetection::GREY;
1340 DFSStack.push(std::make_pair(CurrBB, 0));
1341
1342 while (!DFSStack.empty()) {
1343 // Get next BB on stack to be processed.
1344 CurrBB = DFSStack.top().first;
1345 AdjacentBlockIndex = DFSStack.top().second;
1346 DFSStack.pop();
1347
1348 // Loop to iterate over the successors of current BB.
1349 const TerminatorInst *TInst = CurrBB->getTerminator();
1350 unsigned NSucc = TInst->getNumSuccessors();
1351 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1352 ++I, ++AdjacentBlockIndex) {
1353 SuccBB = TInst->getSuccessor(I);
1354
1355 // Checks for region exit block and self-loops in BB.
1356 if (SuccBB == RExit || SuccBB == CurrBB)
1357 continue;
1358
1359 // WHITE indicates an unvisited BB in DFS walk.
1360 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1361 // Push the current BB and the index of the next child to be visited.
1362 DFSStack.push(std::make_pair(CurrBB, I + 1));
1363 // Push the next BB to be processed.
1364 DFSStack.push(std::make_pair(SuccBB, 0));
1365 // First time the BB is being processed.
1366 BBColorMap[SuccBB] = ScopDetection::GREY;
1367 break;
1368 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1369 // GREY indicates a loop in the control flow.
1370 // If the destination dominates the source, it is a natural loop
1371 // else, an irreducible control flow in the region is detected.
1372 if (!DT->dominates(SuccBB, CurrBB)) {
1373 // Get debug info of instruction which causes irregular control flow.
1374 DbgLoc = TInst->getDebugLoc();
1375 return false;
1376 }
1377 }
1378 }
1379
1380 // If all children of current BB have been processed,
1381 // then mark that BB as fully processed.
1382 if (AdjacentBlockIndex == NSucc)
1383 BBColorMap[CurrBB] = ScopDetection::BLACK;
1384 }
1385
1386 return true;
1387}
1388
Tobias Grosser75805372011-04-29 06:27:02 +00001389bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001390 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001391 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001392 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001393 return false;
1394
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001395 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001396 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001397 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001398 Region *TopRegion = RI->getTopLevelRegion();
1399
Tobias Grosser2ff87232011-10-23 11:17:06 +00001400 releaseMemory();
1401
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001402 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001403 return false;
1404
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001405 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001406 return false;
1407
1408 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001409
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001410 // Only makes sense when we tracked errors.
1411 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001412 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001413 emitMissedRemarksForLeaves(F, TopRegion);
1414 }
1415
Johannes Doerferta05214f2014-10-15 23:24:28 +00001416 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001417 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001418
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001419 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001420 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001421 return false;
1422}
1423
Johannes Doerfertba65c162015-02-24 11:45:21 +00001424bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1425 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001426 const DetectionContext *DC = getDetectionContext(ScopR);
1427 assert(DC && "ScopR is no valid region!");
1428 return DC->NonAffineSubRegionSet.count(SubR);
1429}
1430
1431const ScopDetection::DetectionContext *
1432ScopDetection::getDetectionContext(const Region *R) const {
1433 auto DCMIt = DetectionContextMap.find(R);
1434 if (DCMIt == DetectionContextMap.end())
1435 return nullptr;
1436 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001437}
1438
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001439const ScopDetection::BoxedLoopsSetTy *
1440ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001441 const DetectionContext *DC = getDetectionContext(R);
1442 assert(DC && "ScopR is no valid region!");
1443 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001444}
1445
Hongbin Zheng22623202016-02-15 00:20:58 +00001446const MapInsnToMemAcc *
1447ScopDetection::getInsnToMemAccMap(const Region *R) const {
1448 const DetectionContext *DC = getDetectionContext(R);
1449 assert(DC && "ScopR is no valid region!");
1450 return &DC->InsnToMemAcc;
1451}
1452
Johannes Doerfert09e36972015-10-07 20:17:36 +00001453const InvariantLoadsSetTy *
1454ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001455 const DetectionContext *DC = getDetectionContext(R);
1456 assert(DC && "ScopR is no valid region!");
1457 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001458}
1459
Tobias Grosser75805372011-04-29 06:27:02 +00001460void polly::ScopDetection::verifyRegion(const Region &R) const {
1461 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001462
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001463 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001464 isValidRegion(Context);
1465}
1466
1467void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001468 if (!VerifyScops)
1469 return;
1470
Tobias Grosser26108892014-04-02 20:18:19 +00001471 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001472 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001473}
1474
1475void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001476 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001477 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001478 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001479 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001480 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001481 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001482 AU.setPreservesAll();
1483}
1484
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001485void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001486 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001487 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001488
1489 OS << "\n";
1490}
1491
1492void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001493 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001494 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001495 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001496
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001497 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001498}
1499
1500char ScopDetection::ID = 0;
1501
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001502Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1503
Tobias Grosser73600b82011-10-08 00:30:40 +00001504INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1505 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001506 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001507INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001508INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001509INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001510INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001511INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001512INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1513 "Polly - Detect static control parts (SCoPs)", false, false)