blob: 710375676b8ed842349a315af1bf2833af97ea37 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- ScopDetection.cpp - Detect Scops --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
16// Every Scop fullfills these restrictions:
17//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
37// Only function calls and intrinsics that do not have side effects are allowed
38// (readnone).
39//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000050#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000057#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000059#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000060#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000061#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000062#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000064#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000065#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000066#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000068#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000069
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosserc1a269b2015-12-21 21:00:43 +000075// This option is set to a very high value, as analyzing such loops increases
76// compile time on several cases. For experiments that enable this option,
77// a value of around 40 has been working to avoid run-time regressions with
78// Polly while still exposing interesting optimization opportunities.
79static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80 "polly-detect-profitability-min-per-loop-insts",
81 cl::desc("The minimal number of per-loop instructions before a single loop "
82 "region is considered profitable"),
83 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84
Tobias Grosser575aca82015-10-06 16:10:29 +000085bool polly::PollyProcessUnprofitable;
86static cl::opt<bool, true> XPollyProcessUnprofitable(
87 "polly-process-unprofitable",
88 cl::desc(
89 "Process scops that are unlikely to benefit from Polly optimizations."),
90 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000092
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyFunction(
94 "polly-only-func",
95 cl::desc("Only run on functions that contain a certain string"),
96 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000098
Tobias Grosser483a90d2014-07-09 10:50:10 +000099static cl::opt<std::string> OnlyRegion(
100 "polly-only-region",
101 cl::desc("Only run on certain regions (The provided identifier must "
102 "appear in the name of the region's entry block"),
103 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
104 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000105
Tobias Grosser60cd9322011-11-10 12:47:26 +0000106static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 IgnoreAliasing("polly-ignore-aliasing",
108 cl::desc("Ignore possible aliasing of the array bases"),
109 cl::Hidden, cl::init(false), cl::ZeroOrMore,
110 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000111
Johannes Doerfertb164c792014-09-18 11:17:17 +0000112bool polly::PollyUseRuntimeAliasChecks;
113static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
114 "polly-use-runtime-alias-checks",
115 cl::desc("Use runtime alias checks to resolve possible aliasing."),
116 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Tobias Grosser637bd632013-05-07 07:31:10 +0000119static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000120 ReportLevel("polly-report",
121 cl::desc("Print information about the activities of Polly"),
122 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000123
124static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000125 AllowNonAffine("polly-allow-nonaffine",
126 cl::desc("Allow non affine access functions in arrays"),
127 cl::Hidden, cl::init(false), cl::ZeroOrMore,
128 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000129
Johannes Doerfertba65c162015-02-24 11:45:21 +0000130static cl::opt<bool> AllowNonAffineSubRegions(
131 "polly-allow-nonaffine-branches",
132 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000133 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000134
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000135static cl::opt<bool>
136 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
137 cl::desc("Allow non affine conditions for loops"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
140
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000141static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
142 cl::desc("Allow unsigned expressions"),
143 cl::Hidden, cl::init(false), cl::ZeroOrMore,
144 cl::cat(PollyCategory));
145
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000146static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000147 TrackFailures("polly-detect-track-failures",
148 cl::desc("Track failure strings in detecting scop regions"),
149 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000150 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000151
Andreas Simbuerger04472402014-05-24 09:25:10 +0000152static cl::opt<bool> KeepGoing("polly-detect-keep-going",
153 cl::desc("Do not fail on the first error."),
154 cl::Hidden, cl::ZeroOrMore, cl::init(false),
155 cl::cat(PollyCategory));
156
Sebastian Pop18016682014-04-08 21:20:44 +0000157static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000158 PollyDelinearizeX("polly-delinearize",
159 cl::desc("Delinearize array access functions"),
160 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000161 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000162
Tobias Grossera1689932014-02-18 18:49:49 +0000163static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000164 VerifyScops("polly-detect-verify",
165 cl::desc("Verify the detected SCoPs after each transformation"),
166 cl::Hidden, cl::init(false), cl::ZeroOrMore,
167 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000168
Johannes Doerferte526de52015-09-21 19:10:11 +0000169/// @brief The minimal trip count under which loops are considered unprofitable.
170static const unsigned MIN_LOOP_TRIP_COUNT = 8;
171
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000172bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000173bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000174StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000175
Tobias Grosser75805372011-04-29 06:27:02 +0000176//===----------------------------------------------------------------------===//
177// Statistics.
178
179STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
180
Tobias Grosser8519f892013-12-18 10:49:53 +0000181class DiagnosticScopFound : public DiagnosticInfo {
182private:
183 static int PluginDiagnosticKind;
184
185 Function &F;
186 std::string FileName;
187 unsigned EntryLine, ExitLine;
188
189public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000190 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
191 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000192 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000193 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000194
195 virtual void print(DiagnosticPrinter &DP) const;
196
197 static bool classof(const DiagnosticInfo *DI) {
198 return DI->getKind() == PluginDiagnosticKind;
199 }
200};
201
202int DiagnosticScopFound::PluginDiagnosticKind = 10;
203
Tobias Grosser8519f892013-12-18 10:49:53 +0000204void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000205 DP << "Polly detected an optimizable loop region (scop) in function '" << F
206 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000207
208 if (FileName.empty()) {
209 DP << "Scop location is unknown. Compile with debug info "
210 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000211 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000212 }
213
214 DP << FileName << ":" << EntryLine << ": Start of scop\n";
215 DP << FileName << ":" << ExitLine << ": End of scop";
216}
217
Tobias Grosser75805372011-04-29 06:27:02 +0000218//===----------------------------------------------------------------------===//
219// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000220
Johannes Doerfertb164c792014-09-18 11:17:17 +0000221ScopDetection::ScopDetection() : FunctionPass(ID) {
222 if (!PollyUseRuntimeAliasChecks)
223 return;
224
Johannes Doerfert928229f2014-09-29 17:06:29 +0000225 // Disable runtime alias checks if we ignore aliasing all together.
226 if (IgnoreAliasing) {
227 PollyUseRuntimeAliasChecks = false;
228 return;
229 }
230
Johannes Doerfertb164c792014-09-18 11:17:17 +0000231 if (AllowNonAffine) {
232 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
233 "accesses are enabled.\n");
234 PollyUseRuntimeAliasChecks = false;
235 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000236}
237
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000238template <class RR, typename... Args>
239inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
240 Args &&... Arguments) const {
241
242 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000243 RejectLog &Log = Context.Log;
244 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000245
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000246 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000247 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000248
249 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000250 DEBUG(dbgs() << "\n");
251 } else {
252 assert(!Assert && "Verification of detected scop failed");
253 }
254
255 return false;
256}
257
Tobias Grossera1689932014-02-18 18:49:49 +0000258bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
259 if (!ValidRegions.count(&R))
260 return false;
261
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000262 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000263 DetectionContextMap.erase(&R);
264 const auto &It = DetectionContextMap.insert(
265 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
266 false /*verifying*/)));
267 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000268 return isValidRegion(Context);
269 }
Tobias Grossera1689932014-02-18 18:49:49 +0000270
271 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000272}
273
Tobias Grosser4f129a62011-10-08 00:30:55 +0000274std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000275 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000276 return "";
277
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000278 // Get the first error we found. Even in keep-going mode, this is the first
279 // reason that caused the candidate to be rejected.
280 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000281
282 // This can happen when we marked a region invalid, but didn't track
283 // an error for it.
284 if (Errors.size() == 0)
285 return "";
286
287 RejectReasonPtr RR = *Errors.begin();
288 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000289}
290
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000291bool ScopDetection::addOverApproximatedRegion(Region *AR,
292 DetectionContext &Context) const {
293
294 // If we already know about Ar we can exit.
295 if (!Context.NonAffineSubRegionSet.insert(AR))
296 return true;
297
298 // All loops in the region have to be overapproximated too if there
299 // are accesses that depend on the iteration count.
300 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000301 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000302 if (AR->contains(L))
303 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000304 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000305
306 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000307}
308
Johannes Doerfert09e36972015-10-07 20:17:36 +0000309bool ScopDetection::onlyValidRequiredInvariantLoads(
310 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
311 Region &CurRegion = Context.CurRegion;
312
313 for (LoadInst *Load : RequiredILS)
314 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
315 return false;
316
317 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
318
319 return true;
320}
321
322bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
323 Value *BaseAddress) const {
324
325 InvariantLoadsSetTy AccessILS;
326 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
327 return false;
328
329 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
330 return false;
331
332 return true;
333}
334
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000335bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000336 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000337 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000338 Loop *L = LI->getLoopFor(&BB);
339 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000340
Johannes Doerfert09e36972015-10-07 20:17:36 +0000341 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000342 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000343
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000344 if (!IsLoopBranch && AllowNonAffineSubRegions &&
345 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
346 return true;
347
348 if (IsLoopBranch)
349 return false;
350
351 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
352 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000353}
354
355bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000356 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000357 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000358
359 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
360 auto Opcode = BinOp->getOpcode();
361 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
362 Value *Op0 = BinOp->getOperand(0);
363 Value *Op1 = BinOp->getOperand(1);
364 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
365 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
366 }
367 }
368
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000369 // Non constant conditions of branches need to be ICmpInst.
370 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000371 if (!IsLoopBranch && AllowNonAffineSubRegions &&
372 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
373 return true;
374 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000375 }
Tobias Grosser75805372011-04-29 06:27:02 +0000376
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000377 ICmpInst *ICmp = cast<ICmpInst>(Condition);
378 // Unsigned comparisons are not allowed. They trigger overflow problems
379 // in the code generation.
380 //
381 // TODO: This is not sufficient and just hides bugs. However it does pretty
382 // well.
383 if (ICmp->isUnsigned() && !AllowUnsigned)
384 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000385
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000386 // Are both operands of the ICmp affine?
387 if (isa<UndefValue>(ICmp->getOperand(0)) ||
388 isa<UndefValue>(ICmp->getOperand(1)))
389 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000390
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000391 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
392 // for arbitrary pointer expressions at the moment. Until
393 // this is fixed we disallow pointer expressions completely.
394 if (ICmp->getOperand(0)->getType()->isPointerTy())
395 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000396
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000397 Loop *L = LI->getLoopFor(ICmp->getParent());
398 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
399 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000400
Johannes Doerfert09e36972015-10-07 20:17:36 +0000401 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000402 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000403
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000404 if (!IsLoopBranch && AllowNonAffineSubRegions &&
405 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
406 return true;
407
408 if (IsLoopBranch)
409 return false;
410
411 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
412 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000413}
414
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000415bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000416 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000417 DetectionContext &Context) const {
418 Region &CurRegion = Context.CurRegion;
419
420 TerminatorInst *TI = BB.getTerminator();
421
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000422 if (AllowUnreachable && isa<UnreachableInst>(TI))
423 return true;
424
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000425 // Return instructions are only valid if the region is the top level region.
426 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
427 return true;
428
429 Value *Condition = getConditionFromTerminator(TI);
430
431 if (!Condition)
432 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
433
434 // UndefValue is not allowed as condition.
435 if (isa<UndefValue>(Condition))
436 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
437
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000438 // Constant integer conditions are always affine.
439 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000440 return true;
441
442 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000443 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000444
445 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
446 assert(SI && "Terminator was neither branch nor switch");
447
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000448 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000449}
450
Tobias Grosser75805372011-04-29 06:27:02 +0000451bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000452 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000453 return false;
454
455 if (CI.doesNotAccessMemory())
456 return true;
457
458 Function *CalledFunction = CI.getCalledFunction();
459
460 // Indirect calls are not supported.
461 if (CalledFunction == 0)
462 return false;
463
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000464 if (isIgnoredIntrinsic(&CI))
465 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000466
Tobias Grosser75805372011-04-29 06:27:02 +0000467 return false;
468}
469
Tobias Grosser458fb782014-01-28 12:58:58 +0000470bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
471 // A reference to function argument or constant value is invariant.
472 if (isa<Argument>(Val) || isa<Constant>(Val))
473 return true;
474
475 const Instruction *I = dyn_cast<Instruction>(&Val);
476 if (!I)
477 return false;
478
479 if (!Reg.contains(I))
480 return true;
481
482 if (I->mayHaveSideEffects())
483 return false;
484
485 // When Val is a Phi node, it is likely not invariant. We do not check whether
486 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
487 // invariant. Recursively checking the operators of Phi nodes would lead to
488 // infinite recursion.
489 if (isa<PHINode>(*I))
490 return false;
491
Tobias Grosser26108892014-04-02 20:18:19 +0000492 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000493 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000494 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000495
Tobias Grosser458fb782014-01-28 12:58:58 +0000496 return true;
497}
498
Sebastian Pop422e33f2014-06-03 18:16:31 +0000499MapInsnToMemAcc InsnToMemAcc;
500
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000501/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
502/// register the '...' components.
503///
504/// Array access expressions as they are generated by gfortran contain smax(0,
505/// size) expressions that confuse the 'normal' delinearization algorithm.
506/// However, if we extract such expressions before the normal delinearization
507/// takes place they can actually help to identify array size expressions in
508/// fortran accesses. For the subsequently following delinearization the smax(0,
509/// size) component can be replaced by just 'size'. This is correct as we will
510/// always add and verify the assumption that for all subscript expressions
511/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
512/// that 0 <= size, which means smax(0, size) == size.
513struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
514public:
515 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
516 std::vector<const SCEV *> *Terms = nullptr) {
517
518 SCEVRemoveMax D(SE, Terms);
519 return D.visit(Expr);
520 }
521
522 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
523 : SE(SE), Terms(Terms) {}
524
525 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
526
527 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
528 return Expr;
529 }
530
531 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
532 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
533 }
534
535 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
536
537 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000538 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000539 auto Res = visit(Expr->getOperand(1));
540 if (Terms)
541 (*Terms).push_back(Res);
542 return Res;
543 }
544
545 return Expr;
546 }
547
Roman Gareev8aa43752015-12-17 20:37:17 +0000548 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000549
550 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
551
552 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
553 return Expr;
554 }
555
556 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
557
558 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
559 SmallVector<const SCEV *, 5> NewOps;
560 for (const SCEV *Op : Expr->operands())
561 NewOps.push_back(visit(Op));
562
563 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
564 }
565
566 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
567 SmallVector<const SCEV *, 5> NewOps;
568 for (const SCEV *Op : Expr->operands())
569 NewOps.push_back(visit(Op));
570
571 return SE.getAddExpr(NewOps);
572 }
573
574 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
575 SmallVector<const SCEV *, 5> NewOps;
576 for (const SCEV *Op : Expr->operands())
577 NewOps.push_back(visit(Op));
578
579 return SE.getMulExpr(NewOps);
580 }
581
582private:
583 ScalarEvolution &SE;
584 std::vector<const SCEV *> *Terms;
585};
586
Tobias Grosserd68ba422015-11-24 05:00:36 +0000587SmallVector<const SCEV *, 4>
588ScopDetection::getDelinearizationTerms(DetectionContext &Context,
589 const SCEVUnknown *BasePointer) const {
590 SmallVector<const SCEV *, 4> Terms;
591 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000592 std::vector<const SCEV *> MaxTerms;
593 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
594 if (MaxTerms.size() > 0) {
595 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
596 continue;
597 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000598 // In case the outermost expression is a plain add, we check if any of its
599 // terms has the form 4 * %inst * %param * %param ..., aka a term that
600 // contains a product between a parameter and an instruction that is
601 // inside the scop. Such instructions, if allowed at all, are instructions
602 // SCEV can not represent, but Polly is still looking through. As a
603 // result, these instructions can depend on induction variables and are
604 // most likely no array sizes. However, terms that are multiplied with
605 // them are likely candidates for array sizes.
606 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
607 for (auto Op : AF->operands()) {
608 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
609 SE->collectParametricTerms(AF2, Terms);
610 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
611 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000612
Tobias Grosserd68ba422015-11-24 05:00:36 +0000613 for (auto *MulOp : AF2->operands()) {
614 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
615 Operands.push_back(Const);
616 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
617 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
618 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000619 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000620
621 } else {
622 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000623 }
624 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000625 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000626 if (Operands.size())
627 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000628 }
629 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000630 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000631 if (Terms.empty())
632 SE->collectParametricTerms(Pair.second, Terms);
633 }
634 return Terms;
635}
Sebastian Pope8863b82014-05-12 19:02:02 +0000636
Tobias Grosserd68ba422015-11-24 05:00:36 +0000637bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
638 SmallVectorImpl<const SCEV *> &Sizes,
639 const SCEVUnknown *BasePointer) const {
640 Value *BaseValue = BasePointer->getValue();
641 Region &CurRegion = Context.CurRegion;
642 for (const SCEV *DelinearizedSize : Sizes) {
643 if (!isAffine(DelinearizedSize, Context, nullptr)) {
644 Sizes.clear();
645 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000646 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000647 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
648 auto *V = dyn_cast<Value>(Unknown->getValue());
649 if (auto *Load = dyn_cast<LoadInst>(V)) {
650 if (Context.CurRegion.contains(Load) &&
651 isHoistableLoad(Load, CurRegion, *LI, *SE))
652 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000653 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000654 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000655 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000656 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000657 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000658 Context, /*Assert=*/true, DelinearizedSize,
659 Context.Accesses[BasePointer].front().first, BaseValue);
660 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000661
Tobias Grosserd68ba422015-11-24 05:00:36 +0000662 // No array shape derived.
663 if (Sizes.empty()) {
664 if (AllowNonAffine)
665 return true;
666
Tobias Grosser230acc42014-09-13 14:47:55 +0000667 for (const auto &Pair : Context.Accesses[BasePointer]) {
668 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000669 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000670
Tobias Grosserd68ba422015-11-24 05:00:36 +0000671 if (!isAffine(AF, Context, BaseValue)) {
672 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
673 BaseValue);
674 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000675 return false;
676 }
677 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000678 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000679 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000680 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000681}
682
Tobias Grosserd68ba422015-11-24 05:00:36 +0000683// We first store the resulting memory accesses in TempMemoryAccesses. Only
684// if the access functions for all memory accesses have been successfully
685// delinearized we continue. Otherwise, we either report a failure or, if
686// non-affine accesses are allowed, we drop the information. In case the
687// information is dropped the memory accesses need to be overapproximated
688// when translated to a polyhedral representation.
689bool ScopDetection::computeAccessFunctions(
690 DetectionContext &Context, const SCEVUnknown *BasePointer,
691 std::shared_ptr<ArrayShape> Shape) const {
692 Value *BaseValue = BasePointer->getValue();
693 bool BasePtrHasNonAffine = false;
694 MapInsnToMemAcc TempMemoryAccesses;
695 for (const auto &Pair : Context.Accesses[BasePointer]) {
696 const Instruction *Insn = Pair.first;
697 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000698 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000699 bool IsNonAffine = false;
700 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
701 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
702
703 if (!AF) {
704 if (isAffine(Pair.second, Context, BaseValue))
705 Acc->DelinearizedSubscripts.push_back(Pair.second);
706 else
707 IsNonAffine = true;
708 } else {
709 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
710 Shape->DelinearizedSizes);
711 if (Acc->DelinearizedSubscripts.size() == 0)
712 IsNonAffine = true;
713 for (const SCEV *S : Acc->DelinearizedSubscripts)
714 if (!isAffine(S, Context, BaseValue))
715 IsNonAffine = true;
716 }
717
718 // (Possibly) report non affine access
719 if (IsNonAffine) {
720 BasePtrHasNonAffine = true;
721 if (!AllowNonAffine)
722 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
723 Insn, BaseValue);
724 if (!KeepGoing && !AllowNonAffine)
725 return false;
726 }
727 }
728
729 if (!BasePtrHasNonAffine)
730 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
731
732 return true;
733}
734
735bool ScopDetection::hasBaseAffineAccesses(
736 DetectionContext &Context, const SCEVUnknown *BasePointer) const {
737 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
738
739 auto Terms = getDelinearizationTerms(Context, BasePointer);
740
741 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
742 Context.ElementSize[BasePointer]);
743
744 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer))
745 return false;
746
747 return computeAccessFunctions(Context, BasePointer, Shape);
748}
749
750bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
751 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses)
752 if (!hasBaseAffineAccesses(Context, BasePointer)) {
753 if (KeepGoing)
754 continue;
755 else
756 return false;
757 }
758 return true;
759}
760
Michael Kruse70131d32016-01-27 17:09:17 +0000761bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
Tobias Grosser75805372011-04-29 06:27:02 +0000762 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000763 Region &CurRegion = Context.CurRegion;
764
Michael Kruse70131d32016-01-27 17:09:17 +0000765 Value *Ptr = Inst.getPointerOperand();
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000766 Loop *L = LI->getLoopFor(Inst.getParent());
767 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000768 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000769 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000770
Tobias Grosserb8710b52011-11-10 12:44:50 +0000771 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
772
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000773 if (!BasePointer)
Michael Kruse70131d32016-01-27 17:09:17 +0000774 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000775
776 BaseValue = BasePointer->getValue();
777
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000778 if (isa<UndefValue>(BaseValue))
Michael Kruse70131d32016-01-27 17:09:17 +0000779 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000780
Tobias Grosser458fb782014-01-28 12:58:58 +0000781 // Check that the base address of the access is invariant in the current
782 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000783 if (!isInvariant(*BaseValue, CurRegion))
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000784 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BaseValue,
Michael Kruse70131d32016-01-27 17:09:17 +0000785 Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000786
Tobias Grosserb8710b52011-11-10 12:44:50 +0000787 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
788
Michael Kruse70131d32016-01-27 17:09:17 +0000789 const SCEV *Size = SE->getElementSize(Inst);
Tobias Grossere2c31212016-02-03 05:53:27 +0000790 if (Context.ElementSize.count(BasePointer)) {
791 if (Context.ElementSize[BasePointer] != Size)
792 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
793 Inst, BaseValue);
794 } else {
795 Context.ElementSize[BasePointer] = Size;
796 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000797
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000798 bool isVariantInNonAffineLoop = false;
799 SetVector<const Loop *> Loops;
800 findLoops(AccessFunction, Loops);
801 for (const Loop *L : Loops)
802 if (Context.BoxedLoopsSet.count(L))
803 isVariantInNonAffineLoop = true;
804
805 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Michael Kruse70131d32016-01-27 17:09:17 +0000806 Context.Accesses[BasePointer].push_back({Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000807
Johannes Doerfert09e36972015-10-07 20:17:36 +0000808 if (!isAffine(AccessFunction, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000809 Context.NonAffineAccesses.insert(BasePointer);
810 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000811 if (isVariantInNonAffineLoop ||
Johannes Doerfert09e36972015-10-07 20:17:36 +0000812 !isAffine(AccessFunction, Context, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000813 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Michael Kruse70131d32016-01-27 17:09:17 +0000814 AccessFunction, Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000815 }
Tobias Grosser75805372011-04-29 06:27:02 +0000816
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000817 // FIXME: Think about allowing IntToPtrInst
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000818 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
819 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000820
Tobias Grosser1eedb672014-09-24 21:04:29 +0000821 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000822 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000823
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000824 // Check if the base pointer of the memory access does alias with
825 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000826 AAMDNodes AATags;
827 Inst.getAAMetadata(AATags);
828 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000829 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000830
Tobias Grosser1eedb672014-09-24 21:04:29 +0000831 if (!AS.isMustAlias()) {
832 if (PollyUseRuntimeAliasChecks) {
833 bool CanBuildRunTimeCheck = true;
834 // The run-time alias check places code that involves the base pointer at
835 // the beginning of the SCoP. This breaks if the base pointer is defined
836 // inside the scop. Hence, we can only create a run-time check if we are
837 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000838 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000839 for (const auto &Ptr : AS) {
840 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000841 if (Inst && CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000842 auto *Load = dyn_cast<LoadInst>(Inst);
843 if (Load && isHoistableLoad(Load, CurRegion, *LI, *SE)) {
844 Context.RequiredILS.insert(Load);
845 continue;
846 }
847
Tobias Grosser1eedb672014-09-24 21:04:29 +0000848 CanBuildRunTimeCheck = false;
849 break;
850 }
851 }
852
853 if (CanBuildRunTimeCheck)
854 return true;
855 }
Michael Kruse70131d32016-01-27 17:09:17 +0000856 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000857 }
Tobias Grosser75805372011-04-29 06:27:02 +0000858
859 return true;
860}
861
Tobias Grosser75805372011-04-29 06:27:02 +0000862bool ScopDetection::isValidInstruction(Instruction &Inst,
863 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000864 for (auto &Op : Inst.operands()) {
865 auto *OpInst = dyn_cast<Instruction>(&Op);
866
867 if (!OpInst)
868 continue;
869
870 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
871 return false;
872 }
873
Tobias Grosser75805372011-04-29 06:27:02 +0000874 // We only check the call instruction but not invoke instruction.
875 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
876 if (isValidCallInst(*CI))
877 return true;
878
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000879 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000880 }
881
882 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000883 if (!isa<AllocaInst>(Inst))
884 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000885
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000886 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000887 }
888
889 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +0000890 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
891 Context.hasStores |= MemInst.isLoad();
892 Context.hasLoads |= MemInst.isStore();
893 if (!MemInst.isSimple())
894 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
895 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +0000896
Michael Kruse70131d32016-01-27 17:09:17 +0000897 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000898 }
Tobias Grosser75805372011-04-29 06:27:02 +0000899
900 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000901 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000902}
903
Johannes Doerfertd020b772015-08-27 06:53:52 +0000904bool ScopDetection::canUseISLTripCount(Loop *L,
905 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000906 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
907 // need to overapproximate it as a boxed loop.
908 SmallVector<BasicBlock *, 4> LoopControlBlocks;
909 L->getLoopLatches(LoopControlBlocks);
910 L->getExitingBlocks(LoopControlBlocks);
911 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000912 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000913 return false;
914 }
915
Johannes Doerfertd020b772015-08-27 06:53:52 +0000916 // We can use ISL to compute the trip count of L.
917 return true;
918}
919
Tobias Grosser75805372011-04-29 06:27:02 +0000920bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000921 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000922 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000923
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000924 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000925 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000926 while (R != &Context.CurRegion && !R->contains(L))
927 R = R->getParent();
928
929 if (addOverApproximatedRegion(R, Context))
930 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000931 }
Tobias Grosser75805372011-04-29 06:27:02 +0000932
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000933 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000934 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000935}
936
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000937/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000938/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000939static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000940 auto *TripCount = SE.getBackedgeTakenCount(L);
941
Johannes Doerfertf61df692015-10-04 14:56:08 +0000942 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000943 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000944 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
945 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
946 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000947
948 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000949 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000950
951 return count;
952}
953
Johannes Doerfertf61df692015-10-04 14:56:08 +0000954int ScopDetection::countBeneficialLoops(Region *R) const {
955 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000956
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000957 auto L = LI->getLoopFor(R->getEntry());
958 L = L ? R->outermostLoopInRegion(L) : nullptr;
959 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000960
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000961 auto SubLoops =
962 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
963
964 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000965 if (R->contains(SubLoop))
966 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000967
Johannes Doerfertf61df692015-10-04 14:56:08 +0000968 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000969}
970
Tobias Grosser75805372011-04-29 06:27:02 +0000971Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000972 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000973 std::unique_ptr<Region> LastValidRegion;
974 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000975
976 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
977
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000978 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000979 const auto &It = DetectionContextMap.insert(std::make_pair(
980 ExpandedRegion.get(),
981 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
982 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000983 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000984 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000985
Johannes Doerfert717b8662015-09-08 21:44:27 +0000986 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000987 // If the exit is valid check all blocks
988 // - if true, a valid region was found => store it + keep expanding
989 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +0000990 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
991 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000992 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000993 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000994
Tobias Grosserd7e58642013-04-10 06:55:45 +0000995 // Store this region, because it is the greatest valid (encountered so
996 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +0000997 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000998 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000999
1000 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001001 ExpandedRegion =
1002 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001003
1004 } else {
1005 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001006 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001007 ExpandedRegion =
1008 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001009 }
Tobias Grosser75805372011-04-29 06:27:02 +00001010 }
1011
Tobias Grosser378a9f22013-11-16 19:34:11 +00001012 DEBUG({
1013 if (LastValidRegion)
1014 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1015 else
1016 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1017 });
Tobias Grosser75805372011-04-29 06:27:02 +00001018
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001019 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001020}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001021static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001022 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001023 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001024 return false;
1025
1026 return true;
1027}
Tobias Grosser75805372011-04-29 06:27:02 +00001028
Johannes Doerferte46925f2015-10-01 10:59:14 +00001029unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001030 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001031 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001032 if (ValidRegions.count(SubRegion.get())) {
1033 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001034 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001035 } else
1036 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001037 }
1038 return Count;
1039}
1040
Johannes Doerferte46925f2015-10-01 10:59:14 +00001041void ScopDetection::removeCachedResults(const Region &R) {
1042 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001043 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001044}
1045
Tobias Grosser75805372011-04-29 06:27:02 +00001046void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001047 const auto &It = DetectionContextMap.insert(
1048 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1049 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001050
1051 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +00001052 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001053 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001054 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001055 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001056 RegionIsValid = isValidRegion(Context);
1057
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001058 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001059
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001060 if (PollyTrackFailures && HasErrors)
1061 RejectLogs.insert(std::make_pair(&R, Context.Log));
1062
Johannes Doerferte46925f2015-10-01 10:59:14 +00001063 if (HasErrors) {
1064 removeCachedResults(R);
1065 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001066 ++ValidRegion;
1067 ValidRegions.insert(&R);
1068 return;
1069 }
1070
David Blaikieb035f6d2014-04-15 18:45:27 +00001071 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001072 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001073
1074 // Try to expand regions.
1075 //
1076 // As the region tree normally only contains canonical regions, non canonical
1077 // regions that form a Scop are not found. Therefore, those non canonical
1078 // regions are checked by expanding the canonical ones.
1079
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001080 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001081
David Blaikieb035f6d2014-04-15 18:45:27 +00001082 for (auto &SubRegion : R)
1083 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001084
Tobias Grosser26108892014-04-02 20:18:19 +00001085 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001086 // Skip regions that had errors.
1087 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1088 if (HadErrors)
1089 continue;
1090
Tobias Grosser75805372011-04-29 06:27:02 +00001091 // Skip invalid regions. Regions may become invalid, if they are element of
1092 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001093 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001094 continue;
1095
1096 Region *ExpandedR = expandRegion(*CurrentRegion);
1097
1098 if (!ExpandedR)
1099 continue;
1100
1101 R.addSubRegion(ExpandedR, true);
1102 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001103 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001104
Tobias Grosser28a70c52014-01-29 19:05:30 +00001105 // Erase all (direct and indirect) children of ExpandedR from the valid
1106 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001107 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001108 }
1109}
1110
1111bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001112 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001113
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001114 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001115 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001116 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001117 return false;
1118 }
1119
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001120 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001121 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1122
1123 // Also check exception blocks (and possibly register them as non-affine
1124 // regions). Even though exception blocks are not modeled, we use them
1125 // to forward-propagate domain constraints during ScopInfo construction.
1126 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1127 return false;
1128
1129 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001130 continue;
1131
Tobias Grosser1d191902014-03-03 13:13:55 +00001132 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001133 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001134 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001135 }
Tobias Grosser75805372011-04-29 06:27:02 +00001136
Sebastian Pope8863b82014-05-12 19:02:02 +00001137 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001138 return false;
1139
Tobias Grosser75805372011-04-29 06:27:02 +00001140 return true;
1141}
1142
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001143bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1144 int NumLoops) const {
1145 int InstCount = 0;
1146
1147 for (auto *BB : Context.CurRegion.blocks())
1148 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001149 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001150
1151 InstCount = InstCount / NumLoops;
1152
1153 return InstCount >= ProfitabilityMinPerLoopInstructions;
1154}
1155
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001156bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1157 Region &CurRegion = Context.CurRegion;
1158
1159 if (PollyProcessUnprofitable)
1160 return true;
1161
1162 // We can probably not do a lot on scops that only write or only read
1163 // data.
1164 if (!Context.hasStores || !Context.hasLoads)
1165 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1166
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001167 int NumLoops = countBeneficialLoops(&CurRegion);
1168 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001169
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001170 // Scops with at least two loops may allow either loop fusion or tiling and
1171 // are consequently interesting to look at.
1172 if (NumAffineLoops >= 2)
1173 return true;
1174
1175 // Scops that contain a loop with a non-trivial amount of computation per
1176 // loop-iteration are interesting as we may be able to parallelize such
1177 // loops. Individual loops that have only a small amount of computation
1178 // per-iteration are performance-wise very fragile as any change to the
1179 // loop induction variables may affect performance. To not cause spurious
1180 // performance regressions, we do not consider such loops.
1181 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1182 return true;
1183
1184 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001185}
1186
Tobias Grosser75805372011-04-29 06:27:02 +00001187bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001188 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001189
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001190 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001191
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001192 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001193 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001194 return false;
1195 }
1196
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001197 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001198 DEBUG({
1199 dbgs() << "Region entry does not match -polly-region-only";
1200 dbgs() << "\n";
1201 });
1202 return false;
1203 }
1204
Tobias Grosserd654c252012-04-10 18:12:19 +00001205 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001206 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001207 if (CurRegion.getEntry() ==
1208 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1209 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001210
Hongbin Zheng94868e62012-04-07 12:29:17 +00001211 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001212 return false;
1213
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001214 DebugLoc DbgLoc;
1215 if (!isReducibleRegion(CurRegion, DbgLoc))
1216 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1217 &CurRegion, DbgLoc);
1218
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001219 if (!isProfitableRegion(Context))
1220 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001221
Tobias Grosser75805372011-04-29 06:27:02 +00001222 DEBUG(dbgs() << "OK\n");
1223 return true;
1224}
1225
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001226void ScopDetection::markFunctionAsInvalid(Function *F) const {
1227 F->addFnAttr(PollySkipFnAttr);
1228}
1229
Tobias Grosser75805372011-04-29 06:27:02 +00001230bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001231 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001232}
1233
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001234void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001235 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001236 unsigned LineEntry, LineExit;
1237 std::string FileName;
1238
Tobias Grosser00dc3092014-03-02 12:02:46 +00001239 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001240 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1241 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001242 }
1243}
1244
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001245void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001246 for (const Region *R : ValidRegions) {
1247 const Region *Parent = R->getParent();
1248 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1249 emitRejectionRemarks(F, RejectLogs.at(Parent));
1250 }
1251}
1252
1253void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1254 const Region *R) {
1255 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001256 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001257 if (IsValid)
1258 continue;
1259
1260 bool IsLeaf = Child->begin() == Child->end();
1261 if (!IsLeaf)
1262 emitMissedRemarksForLeaves(F, Child.get());
1263 else {
1264 if (RejectLogs.count(Child.get())) {
1265 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1266 }
1267 }
1268 }
1269}
1270
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001271bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1272 BasicBlock *REntry = R.getEntry();
1273 BasicBlock *RExit = R.getExit();
1274 // Map to match the color of a BasicBlock during the DFS walk.
1275 DenseMap<const BasicBlock *, Color> BBColorMap;
1276 // Stack keeping track of current BB and index of next child to be processed.
1277 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1278
1279 unsigned AdjacentBlockIndex = 0;
1280 BasicBlock *CurrBB, *SuccBB;
1281 CurrBB = REntry;
1282
1283 // Initialize the map for all BB with WHITE color.
1284 for (auto *BB : R.blocks())
1285 BBColorMap[BB] = ScopDetection::WHITE;
1286
1287 // Process the entry block of the Region.
1288 BBColorMap[CurrBB] = ScopDetection::GREY;
1289 DFSStack.push(std::make_pair(CurrBB, 0));
1290
1291 while (!DFSStack.empty()) {
1292 // Get next BB on stack to be processed.
1293 CurrBB = DFSStack.top().first;
1294 AdjacentBlockIndex = DFSStack.top().second;
1295 DFSStack.pop();
1296
1297 // Loop to iterate over the successors of current BB.
1298 const TerminatorInst *TInst = CurrBB->getTerminator();
1299 unsigned NSucc = TInst->getNumSuccessors();
1300 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1301 ++I, ++AdjacentBlockIndex) {
1302 SuccBB = TInst->getSuccessor(I);
1303
1304 // Checks for region exit block and self-loops in BB.
1305 if (SuccBB == RExit || SuccBB == CurrBB)
1306 continue;
1307
1308 // WHITE indicates an unvisited BB in DFS walk.
1309 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1310 // Push the current BB and the index of the next child to be visited.
1311 DFSStack.push(std::make_pair(CurrBB, I + 1));
1312 // Push the next BB to be processed.
1313 DFSStack.push(std::make_pair(SuccBB, 0));
1314 // First time the BB is being processed.
1315 BBColorMap[SuccBB] = ScopDetection::GREY;
1316 break;
1317 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1318 // GREY indicates a loop in the control flow.
1319 // If the destination dominates the source, it is a natural loop
1320 // else, an irreducible control flow in the region is detected.
1321 if (!DT->dominates(SuccBB, CurrBB)) {
1322 // Get debug info of instruction which causes irregular control flow.
1323 DbgLoc = TInst->getDebugLoc();
1324 return false;
1325 }
1326 }
1327 }
1328
1329 // If all children of current BB have been processed,
1330 // then mark that BB as fully processed.
1331 if (AdjacentBlockIndex == NSucc)
1332 BBColorMap[CurrBB] = ScopDetection::BLACK;
1333 }
1334
1335 return true;
1336}
1337
Tobias Grosser75805372011-04-29 06:27:02 +00001338bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001339 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001340 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001341 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001342 return false;
1343
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001344 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001345 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001346 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001347 Region *TopRegion = RI->getTopLevelRegion();
1348
Tobias Grosser2ff87232011-10-23 11:17:06 +00001349 releaseMemory();
1350
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001351 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001352 return false;
1353
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001354 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001355 return false;
1356
1357 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001358
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001359 // Only makes sense when we tracked errors.
1360 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001361 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001362 emitMissedRemarksForLeaves(F, TopRegion);
1363 }
1364
Johannes Doerferta05214f2014-10-15 23:24:28 +00001365 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001366 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001367
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001368 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001369 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001370 return false;
1371}
1372
Johannes Doerfertba65c162015-02-24 11:45:21 +00001373bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1374 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001375 const DetectionContext *DC = getDetectionContext(ScopR);
1376 assert(DC && "ScopR is no valid region!");
1377 return DC->NonAffineSubRegionSet.count(SubR);
1378}
1379
1380const ScopDetection::DetectionContext *
1381ScopDetection::getDetectionContext(const Region *R) const {
1382 auto DCMIt = DetectionContextMap.find(R);
1383 if (DCMIt == DetectionContextMap.end())
1384 return nullptr;
1385 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001386}
1387
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001388const ScopDetection::BoxedLoopsSetTy *
1389ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001390 const DetectionContext *DC = getDetectionContext(R);
1391 assert(DC && "ScopR is no valid region!");
1392 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001393}
1394
Johannes Doerfert09e36972015-10-07 20:17:36 +00001395const InvariantLoadsSetTy *
1396ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001397 const DetectionContext *DC = getDetectionContext(R);
1398 assert(DC && "ScopR is no valid region!");
1399 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001400}
1401
Tobias Grosser75805372011-04-29 06:27:02 +00001402void polly::ScopDetection::verifyRegion(const Region &R) const {
1403 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001404
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001405 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001406 isValidRegion(Context);
1407}
1408
1409void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001410 if (!VerifyScops)
1411 return;
1412
Tobias Grosser26108892014-04-02 20:18:19 +00001413 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001414 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001415}
1416
1417void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001418 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001419 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001420 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001421 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001422 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001423 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001424 AU.setPreservesAll();
1425}
1426
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001427void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001428 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001429 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001430
1431 OS << "\n";
1432}
1433
1434void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001435 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001436 ValidRegions.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001437 InsnToMemAcc.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001438 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001439
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001440 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001441}
1442
1443char ScopDetection::ID = 0;
1444
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001445Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1446
Tobias Grosser73600b82011-10-08 00:30:40 +00001447INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1448 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001449 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001450INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001451INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001452INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001453INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001454INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001455INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1456 "Polly - Detect static control parts (SCoPs)", false, false)