blob: ebe175fdd490a8fc8a837735c9eb71c9545c29de [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 Grosserecfe21b2013-03-20 18:03:18 +000047#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000049#include "polly/Options.h"
Andreas Simbuerger01a37a02014-04-02 11:54:01 +000050#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000051#include "polly/ScopDetection.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000053#include "polly/Support/ScopHelper.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000054#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include "llvm/ADT/Statistic.h"
56#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000058#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000059#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000060#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000061#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000062#include "llvm/IR/DebugInfo.h"
Johannes Doerfert3f500fa2015-01-25 18:07:30 +000063#include "llvm/IR/IntrinsicInst.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000064#include "llvm/IR/DiagnosticInfo.h"
65#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000066#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000067#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000068#include <set>
69
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
Sebastian Pop8fe6d112013-05-30 17:47:32 +000075static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000076 DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
77 cl::desc("Detect scops in functions without loops"),
78 cl::Hidden, cl::init(false), cl::ZeroOrMore,
79 cl::cat(PollyCategory));
Sebastian Pop8fe6d112013-05-30 17:47:32 +000080
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000081static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000082 DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
83 cl::desc("Detect scops in regions without loops"),
84 cl::Hidden, cl::init(false), cl::ZeroOrMore,
85 cl::cat(PollyCategory));
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000086
Tobias Grosserd1e33e72015-02-19 05:31:07 +000087static cl::opt<bool> DetectUnprofitable("polly-detect-unprofitable",
88 cl::desc("Detect unprofitable scops"),
89 cl::Hidden, cl::init(false),
90 cl::ZeroOrMore, cl::cat(PollyCategory));
91
Tobias Grosser483a90d2014-07-09 10:50:10 +000092static cl::opt<std::string> OnlyFunction(
93 "polly-only-func",
94 cl::desc("Only run on functions that contain a certain string"),
95 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
96 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000097
Tobias Grosser483a90d2014-07-09 10:50:10 +000098static cl::opt<std::string> OnlyRegion(
99 "polly-only-region",
100 cl::desc("Only run on certain regions (The provided identifier must "
101 "appear in the name of the region's entry block"),
102 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
103 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000104
Tobias Grosser60cd9322011-11-10 12:47:26 +0000105static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000106 IgnoreAliasing("polly-ignore-aliasing",
107 cl::desc("Ignore possible aliasing of the array bases"),
108 cl::Hidden, cl::init(false), cl::ZeroOrMore,
109 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000110
Johannes Doerfertb164c792014-09-18 11:17:17 +0000111bool polly::PollyUseRuntimeAliasChecks;
112static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
113 "polly-use-runtime-alias-checks",
114 cl::desc("Use runtime alias checks to resolve possible aliasing."),
115 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
116 cl::init(true), cl::cat(PollyCategory));
117
Tobias Grosser637bd632013-05-07 07:31:10 +0000118static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000119 ReportLevel("polly-report",
120 cl::desc("Print information about the activities of Polly"),
121 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000122
123static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000124 AllowNonAffine("polly-allow-nonaffine",
125 cl::desc("Allow non affine access functions in arrays"),
126 cl::Hidden, cl::init(false), cl::ZeroOrMore,
127 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000128
Johannes Doerfertba65c162015-02-24 11:45:21 +0000129static cl::opt<bool> AllowNonAffineSubRegions(
130 "polly-allow-nonaffine-branches",
131 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000132 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000133
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000134static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
135 cl::desc("Allow unsigned expressions"),
136 cl::Hidden, cl::init(false), cl::ZeroOrMore,
137 cl::cat(PollyCategory));
138
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000139static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000140 TrackFailures("polly-detect-track-failures",
141 cl::desc("Track failure strings in detecting scop regions"),
142 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000143 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000144
Andreas Simbuerger04472402014-05-24 09:25:10 +0000145static cl::opt<bool> KeepGoing("polly-detect-keep-going",
146 cl::desc("Do not fail on the first error."),
147 cl::Hidden, cl::ZeroOrMore, cl::init(false),
148 cl::cat(PollyCategory));
149
Sebastian Pop18016682014-04-08 21:20:44 +0000150static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000151 PollyDelinearizeX("polly-delinearize",
152 cl::desc("Delinearize array access functions"),
153 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser9d3c0b62015-03-08 12:57:31 +0000154 cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000155
Tobias Grossera1689932014-02-18 18:49:49 +0000156static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000157 VerifyScops("polly-detect-verify",
158 cl::desc("Verify the detected SCoPs after each transformation"),
159 cl::Hidden, cl::init(false), cl::ZeroOrMore,
160 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000161
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000162static cl::opt<bool, true> XPollyModelPHINodes(
163 "polly-model-phi-nodes",
164 cl::desc("Allow PHI nodes in the input [Unsafe with code-generation!]."),
165 cl::location(PollyModelPHINodes), cl::Hidden, cl::ZeroOrMore,
166 cl::init(false), cl::cat(PollyCategory));
167
168bool polly::PollyModelPHINodes = false;
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000169bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000170bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000171StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000172
Tobias Grosser75805372011-04-29 06:27:02 +0000173//===----------------------------------------------------------------------===//
174// Statistics.
175
176STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
177
Tobias Grosser8519f892013-12-18 10:49:53 +0000178class DiagnosticScopFound : public DiagnosticInfo {
179private:
180 static int PluginDiagnosticKind;
181
182 Function &F;
183 std::string FileName;
184 unsigned EntryLine, ExitLine;
185
186public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000187 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
188 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000189 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000190 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000191
192 virtual void print(DiagnosticPrinter &DP) const;
193
194 static bool classof(const DiagnosticInfo *DI) {
195 return DI->getKind() == PluginDiagnosticKind;
196 }
197};
198
199int DiagnosticScopFound::PluginDiagnosticKind = 10;
200
Tobias Grosser8519f892013-12-18 10:49:53 +0000201void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000202 DP << "Polly detected an optimizable loop region (scop) in function '" << F
203 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000204
205 if (FileName.empty()) {
206 DP << "Scop location is unknown. Compile with debug info "
207 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000208 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000209 }
210
211 DP << FileName << ":" << EntryLine << ": Start of scop\n";
212 DP << FileName << ":" << ExitLine << ": End of scop";
213}
214
Tobias Grosser75805372011-04-29 06:27:02 +0000215//===----------------------------------------------------------------------===//
216// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000217
Johannes Doerfertb164c792014-09-18 11:17:17 +0000218ScopDetection::ScopDetection() : FunctionPass(ID) {
219 if (!PollyUseRuntimeAliasChecks)
220 return;
221
Johannes Doerfert928229f2014-09-29 17:06:29 +0000222 // Disable runtime alias checks if we ignore aliasing all together.
223 if (IgnoreAliasing) {
224 PollyUseRuntimeAliasChecks = false;
225 return;
226 }
227
Johannes Doerfertb164c792014-09-18 11:17:17 +0000228 if (AllowNonAffine) {
229 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
230 "accesses are enabled.\n");
231 PollyUseRuntimeAliasChecks = false;
232 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000233}
234
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000235template <class RR, typename... Args>
236inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
237 Args &&... Arguments) const {
238
239 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000240 RejectLog &Log = Context.Log;
241 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000242
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000243 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000244 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000245
246 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000247 DEBUG(dbgs() << "\n");
248 } else {
249 assert(!Assert && "Verification of detected scop failed");
250 }
251
252 return false;
253}
254
Tobias Grossera1689932014-02-18 18:49:49 +0000255bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
256 if (!ValidRegions.count(&R))
257 return false;
258
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000259 if (Verify) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000260 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
261 DetectionContext Context(const_cast<Region &>(R), *AA,
262 DummyNonAffineSubRegionSet, false /*verifying*/);
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000263 return isValidRegion(Context);
264 }
Tobias Grossera1689932014-02-18 18:49:49 +0000265
266 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000267}
268
Tobias Grosser4f129a62011-10-08 00:30:55 +0000269std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000270 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000271 return "";
272
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000273 // Get the first error we found. Even in keep-going mode, this is the first
274 // reason that caused the candidate to be rejected.
275 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000276
277 // This can happen when we marked a region invalid, but didn't track
278 // an error for it.
279 if (Errors.size() == 0)
280 return "";
281
282 RejectReasonPtr RR = *Errors.begin();
283 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000284}
285
Johannes Doerfertba65c162015-02-24 11:45:21 +0000286static bool containsLoop(Region *R, LoopInfo *LI) {
287 for (BasicBlock *BB : R->blocks()) {
288 Loop *L = LI->getLoopFor(BB);
289 if (R->contains(L))
290 return true;
291 }
292 return false;
293}
294
Tobias Grossere602a072013-05-07 07:30:56 +0000295bool ScopDetection::isValidCFG(BasicBlock &BB,
296 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000297 Region &CurRegion = Context.CurRegion;
298
Tobias Grosser75805372011-04-29 06:27:02 +0000299 TerminatorInst *TI = BB.getTerminator();
300
301 // Return instructions are only valid if the region is the top level region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000302 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
Tobias Grosser75805372011-04-29 06:27:02 +0000303 return true;
304
305 BranchInst *Br = dyn_cast<BranchInst>(TI);
306
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000307 if (!Br)
308 return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000309
Tobias Grosser74394f02013-01-14 22:40:23 +0000310 if (Br->isUnconditional())
311 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000312
313 Value *Condition = Br->getCondition();
314
315 // UndefValue is not allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000316 if (isa<UndefValue>(Condition))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000317 return invalid<ReportUndefCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000318
319 // Only Constant and ICmpInst are allowed as condition.
Johannes Doerfertba65c162015-02-24 11:45:21 +0000320 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition))) {
321 if (AllowNonAffineSubRegions && !containsLoop(RI->getRegionFor(&BB), LI))
322 Context.NonAffineSubRegionSet.insert(RI->getRegionFor(&BB));
323 else
324 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, Br, &BB);
325 }
Tobias Grosser75805372011-04-29 06:27:02 +0000326
327 // Allow perfectly nested conditions.
328 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
329
330 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
331 // Unsigned comparisons are not allowed. They trigger overflow problems
332 // in the code generation.
333 //
334 // TODO: This is not sufficient and just hides bugs. However it does pretty
335 // well.
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000336 if (ICmp->isUnsigned() && !AllowUnsigned)
Tobias Grosser75805372011-04-29 06:27:02 +0000337 return false;
338
339 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000340 if (isa<UndefValue>(ICmp->getOperand(0)) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000341 isa<UndefValue>(ICmp->getOperand(1)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000342 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000343
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000344 Loop *L = LI->getLoopFor(ICmp->getParent());
345 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
346 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000347
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000348 if (!isAffineExpr(&CurRegion, LHS, *SE) ||
Johannes Doerfertba65c162015-02-24 11:45:21 +0000349 !isAffineExpr(&CurRegion, RHS, *SE)) {
350 if (AllowNonAffineSubRegions && !containsLoop(RI->getRegionFor(&BB), LI))
351 Context.NonAffineSubRegionSet.insert(RI->getRegionFor(&BB));
352 else
353 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
354 RHS, ICmp);
355 }
Tobias Grosser75805372011-04-29 06:27:02 +0000356 }
357
358 // Allow loop exit conditions.
359 Loop *L = LI->getLoopFor(&BB);
360 if (L && L->getExitingBlock() == &BB)
361 return true;
362
363 // Allow perfectly nested conditions.
364 Region *R = RI->getRegionFor(&BB);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000365 if (R->getEntry() != &BB)
366 return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000367
368 return true;
369}
370
371bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000372 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000373 return false;
374
375 if (CI.doesNotAccessMemory())
376 return true;
377
378 Function *CalledFunction = CI.getCalledFunction();
379
380 // Indirect calls are not supported.
381 if (CalledFunction == 0)
382 return false;
383
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000384 // Check if we can handle the intrinsic call.
385 if (auto *IT = dyn_cast<IntrinsicInst>(&CI)) {
386 switch (IT->getIntrinsicID()) {
387 // Lifetime markers are supported/ignored.
388 case llvm::Intrinsic::lifetime_start:
389 case llvm::Intrinsic::lifetime_end:
390 // Invariant markers are supported/ignored.
391 case llvm::Intrinsic::invariant_start:
392 case llvm::Intrinsic::invariant_end:
393 // Some misc annotations are supported/ignored.
394 case llvm::Intrinsic::var_annotation:
395 case llvm::Intrinsic::ptr_annotation:
396 case llvm::Intrinsic::annotation:
397 case llvm::Intrinsic::donothing:
398 case llvm::Intrinsic::assume:
399 case llvm::Intrinsic::expect:
400 return true;
401 default:
402 // Other intrinsics which may access the memory are not yet supported.
403 break;
404 }
405 }
406
Tobias Grosser75805372011-04-29 06:27:02 +0000407 return false;
408}
409
Tobias Grosser458fb782014-01-28 12:58:58 +0000410bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
411 // A reference to function argument or constant value is invariant.
412 if (isa<Argument>(Val) || isa<Constant>(Val))
413 return true;
414
415 const Instruction *I = dyn_cast<Instruction>(&Val);
416 if (!I)
417 return false;
418
419 if (!Reg.contains(I))
420 return true;
421
422 if (I->mayHaveSideEffects())
423 return false;
424
425 // When Val is a Phi node, it is likely not invariant. We do not check whether
426 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
427 // invariant. Recursively checking the operators of Phi nodes would lead to
428 // infinite recursion.
429 if (isa<PHINode>(*I))
430 return false;
431
Tobias Grosser26108892014-04-02 20:18:19 +0000432 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000433 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000434 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000435
436 // When the instruction is a load instruction, check that no write to memory
437 // in the region aliases with the load.
438 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
439 AliasAnalysis::Location Loc = AA->getLocation(LI);
Johannes Doerfertca08c442015-02-21 16:18:28 +0000440
Tobias Grosser458fb782014-01-28 12:58:58 +0000441 // Check if any basic block in the region can modify the location pointed to
442 // by 'Loc'. If so, 'Val' is (likely) not invariant in the region.
Tobias Grosser26108892014-04-02 20:18:19 +0000443 for (const BasicBlock *BB : Reg.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000444 if (AA->canBasicBlockModify(*BB, Loc))
Tobias Grosser458fb782014-01-28 12:58:58 +0000445 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000446 }
447
448 return true;
449}
450
Sebastian Pop422e33f2014-06-03 18:16:31 +0000451MapInsnToMemAcc InsnToMemAcc;
452
Sebastian Popb57c0992014-05-12 20:24:26 +0000453bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000454 Region &CurRegion = Context.CurRegion;
455
Tobias Grosser230acc42014-09-13 14:47:55 +0000456 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000457 Value *BaseValue = BasePointer->getValue();
Sebastian Pop422e33f2014-06-03 18:16:31 +0000458 ArrayShape *Shape = new ArrayShape(BasePointer);
Tobias Grosser230acc42014-09-13 14:47:55 +0000459 bool BasePtrHasNonAffine = false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000460
461 // First step: collect parametric terms in all array references.
462 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser230acc42014-09-13 14:47:55 +0000463 for (const auto &Pair : Context.Accesses[BasePointer]) {
464 const SCEVAddRecExpr *AccessFunction =
465 dyn_cast<SCEVAddRecExpr>(Pair.second);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000466
Tobias Grosser230acc42014-09-13 14:47:55 +0000467 if (AccessFunction)
468 AccessFunction->collectParametricTerms(*SE, Terms);
469 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000470
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000471 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000472 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
473 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000474
Tobias Grosser230acc42014-09-13 14:47:55 +0000475 // No array shape derived.
476 if (Shape->DelinearizedSizes.empty()) {
477 if (AllowNonAffine)
478 continue;
Sebastian Pope8863b82014-05-12 19:02:02 +0000479
Tobias Grosser230acc42014-09-13 14:47:55 +0000480 for (const auto &Pair : Context.Accesses[BasePointer]) {
481 const Instruction *Insn = Pair.first;
482 const SCEV *AF = Pair.second;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000483
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000484 if (!isAffineExpr(&CurRegion, AF, *SE, BaseValue)) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000485 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
486 BaseValue);
487 if (!KeepGoing)
488 return false;
489 }
490 }
491 continue;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000492 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000493
494 // Third step: compute the access functions for each subscript.
495 //
496 // We first store the resulting memory accesses in TempMemoryAccesses. Only
497 // if the access functions for all memory accesses have been successfully
498 // delinearized we continue. Otherwise, we either report a failure or, if
499 // non-affine accesses are allowed, we drop the information. In case the
500 // information is dropped the memory accesses need to be overapproximated
501 // when translated to a polyhedral representation.
502 MapInsnToMemAcc TempMemoryAccesses;
503 for (const auto &Pair : Context.Accesses[BasePointer]) {
504 const Instruction *Insn = Pair.first;
505 const SCEVAddRecExpr *AF = dyn_cast<SCEVAddRecExpr>(Pair.second);
506 bool IsNonAffine = false;
507 MemAcc *Acc = new MemAcc(Insn, Shape);
508 TempMemoryAccesses.insert({Insn, Acc});
509
510 if (!AF) {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000511 if (isAffineExpr(&CurRegion, Pair.second, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000512 Acc->DelinearizedSubscripts.push_back(Pair.second);
513 else
514 IsNonAffine = true;
515 } else {
516 AF->computeAccessFunctions(*SE, Acc->DelinearizedSubscripts,
517 Shape->DelinearizedSizes);
518 if (Acc->DelinearizedSubscripts.size() == 0)
519 IsNonAffine = true;
520 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000521 if (!isAffineExpr(&CurRegion, S, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000522 IsNonAffine = true;
523 }
524
525 // (Possibly) report non affine access
526 if (IsNonAffine) {
527 BasePtrHasNonAffine = true;
528 if (!AllowNonAffine)
Tobias Grosser021eaef2015-01-08 19:03:10 +0000529 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
530 Insn, BaseValue);
Tobias Grosser230acc42014-09-13 14:47:55 +0000531 if (!KeepGoing && !AllowNonAffine)
532 return false;
533 }
534 }
535
536 if (!BasePtrHasNonAffine)
537 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000538 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000539 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000540}
541
Tobias Grosser75805372011-04-29 06:27:02 +0000542bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
543 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000544 Region &CurRegion = Context.CurRegion;
545
Tobias Grossere5e171e2011-11-10 12:45:03 +0000546 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000547 Loop *L = LI->getLoopFor(Inst.getParent());
548 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000549 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000550 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000551
Tobias Grosserb8710b52011-11-10 12:44:50 +0000552 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
553
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000554 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000555 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000556
557 BaseValue = BasePointer->getValue();
558
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000559 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000560 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000561
Tobias Grosser458fb782014-01-28 12:58:58 +0000562 // Check that the base address of the access is invariant in the current
563 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000564 if (!isInvariant(*BaseValue, CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000565 // Verification of this property is difficult as the independent blocks
566 // pass may introduce aliasing that we did not have when running the
567 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000568 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
569 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000570
Tobias Grosserb8710b52011-11-10 12:44:50 +0000571 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
572
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000573 const SCEV *Size = SE->getElementSize(&Inst);
574 if (Context.ElementSize.count(BasePointer)) {
575 if (Context.ElementSize[BasePointer] != Size)
576 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
577 &Inst, BaseValue);
578 } else {
579 Context.ElementSize[BasePointer] = Size;
580 }
581
Tobias Grosser230acc42014-09-13 14:47:55 +0000582 if (PollyDelinearize) {
583 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000584
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000585 if (!isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000586 Context.NonAffineAccesses.insert(BasePointer);
587 } else if (!AllowNonAffine) {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000588 if (!isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000589 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000590 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000591 }
Tobias Grosser75805372011-04-29 06:27:02 +0000592
593 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
594 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000595 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
596 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000597
Tobias Grosser1eedb672014-09-24 21:04:29 +0000598 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000599 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000600
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000601 // Check if the base pointer of the memory access does alias with
602 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000603 AAMDNodes AATags;
604 Inst.getAAMetadata(AATags);
605 AliasSet &AS = Context.AST.getAliasSetForPointer(
606 BaseValue, AliasAnalysis::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000607
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000608 // INVALID triggers an assertion in verifying mode, if it detects that a
609 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
610 // a pass that stated it would preserve the SCoPs. We disable this check as
611 // the independent blocks pass may create memory references which seem to
612 // alias, if -basicaa is not available. They actually do not, but as we can
613 // not proof this without -basicaa we would fail. We disable this check to
614 // not cause irrelevant verification failures.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000615 if (!AS.isMustAlias()) {
616 if (PollyUseRuntimeAliasChecks) {
617 bool CanBuildRunTimeCheck = true;
618 // The run-time alias check places code that involves the base pointer at
619 // the beginning of the SCoP. This breaks if the base pointer is defined
620 // inside the scop. Hence, we can only create a run-time check if we are
621 // sure the base pointer is not an instruction defined inside the scop.
622 for (const auto &Ptr : AS) {
623 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000624 if (Inst && CurRegion.contains(Inst)) {
Tobias Grosser1eedb672014-09-24 21:04:29 +0000625 CanBuildRunTimeCheck = false;
626 break;
627 }
628 }
629
630 if (CanBuildRunTimeCheck)
631 return true;
632 }
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000633 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000634 }
Tobias Grosser75805372011-04-29 06:27:02 +0000635
636 return true;
637}
638
Tobias Grosser75805372011-04-29 06:27:02 +0000639bool ScopDetection::isValidInstruction(Instruction &Inst,
640 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000641 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000642 if (!PollyModelPHINodes && !canSynthesize(PN, LI, SE, &Context.CurRegion)) {
Tobias Grosser683b8e42014-11-30 14:33:31 +0000643 return invalid<ReportPhiNodeRefInRegion>(Context, /*Assert=*/true, &Inst);
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000644 }
Tobias Grosser75805372011-04-29 06:27:02 +0000645
Tobias Grosser75805372011-04-29 06:27:02 +0000646 // We only check the call instruction but not invoke instruction.
647 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
648 if (isValidCallInst(*CI))
649 return true;
650
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000651 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000652 }
653
654 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000655 if (!isa<AllocaInst>(Inst))
656 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000657
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000658 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000659 }
660
661 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000662 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
663 Context.hasStores |= isa<StoreInst>(Inst);
664 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000665 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000666 }
Tobias Grosser75805372011-04-29 06:27:02 +0000667
668 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000669 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000670}
671
Tobias Grosser75805372011-04-29 06:27:02 +0000672bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000673 // Is the loop count affine?
674 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000675 if (isAffineExpr(&Context.CurRegion, LoopCount, *SE))
676 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000677
Johannes Doerfertba65c162015-02-24 11:45:21 +0000678 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000679}
680
681Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000682 // Initial no valid region was found (greater than R)
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000683 Region *LastValidRegion = nullptr;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000684 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000685
686 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
687
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000688 while (ExpandedRegion) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000689 DetectionContext Context(*ExpandedRegion, *AA,
690 NonAffineSubRegionMap[ExpandedRegion],
691 false /* verifying */);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000692 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000693 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000694
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000695 // Check the exit first (cheap)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000696 if (isValidExit(Context) && !Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000697 // If the exit is valid check all blocks
698 // - if true, a valid region was found => store it + keep expanding
699 // - if false, .tbd. => stop (should this really end the loop?)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000700 if (!allBlocksValid(Context) || Context.Log.hasErrors())
701 break;
702
703 if (Context.Log.hasErrors())
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000704 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000705
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000706 // Delete unnecessary regions (allocated by getExpandedRegion)
707 if (LastValidRegion)
708 delete LastValidRegion;
709
Tobias Grosserd7e58642013-04-10 06:55:45 +0000710 // Store this region, because it is the greatest valid (encountered so
711 // far).
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000712 LastValidRegion = ExpandedRegion;
713
714 // Create and test the next greater region (if any)
715 ExpandedRegion = ExpandedRegion->getExpandedRegion();
716
717 } else {
718 // Create and test the next greater region (if any)
719 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
720
721 // Delete unnecessary regions (allocated by getExpandedRegion)
722 delete ExpandedRegion;
723
724 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000725 }
Tobias Grosser75805372011-04-29 06:27:02 +0000726 }
727
Tobias Grosser378a9f22013-11-16 19:34:11 +0000728 DEBUG({
729 if (LastValidRegion)
730 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
731 else
732 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
733 });
Tobias Grosser75805372011-04-29 06:27:02 +0000734
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000735 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000736}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000737static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000738 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000739 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000740 return false;
741
742 return true;
743}
Tobias Grosser75805372011-04-29 06:27:02 +0000744
Tobias Grosser28a70c52014-01-29 19:05:30 +0000745// Remove all direct and indirect children of region R from the region set Regs,
746// but do not recurse further if the first child has been found.
747//
748// Return the number of regions erased from Regs.
David Peixotto8da2b932014-10-22 20:39:07 +0000749static unsigned eraseAllChildren(ScopDetection::RegionSet &Regs,
David Blaikieb035f6d2014-04-15 18:45:27 +0000750 const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000751 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000752 for (auto &SubRegion : R) {
David Peixotto8da2b932014-10-22 20:39:07 +0000753 if (Regs.count(SubRegion.get())) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000754 ++Count;
David Peixotto8da2b932014-10-22 20:39:07 +0000755 Regs.remove(SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000756 } else {
David Blaikieb035f6d2014-04-15 18:45:27 +0000757 Count += eraseAllChildren(Regs, *SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000758 }
759 }
760 return Count;
761}
762
Tobias Grosser75805372011-04-29 06:27:02 +0000763void ScopDetection::findScops(Region &R) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000764 DetectionContext Context(R, *AA, NonAffineSubRegionMap[&R],
765 false /*verifying*/);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000766
767 bool RegionIsValid = false;
768 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
769 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
770 else
771 RegionIsValid = isValidRegion(Context);
772
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000773 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +0000774
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000775 if (PollyTrackFailures && HasErrors)
776 RejectLogs.insert(std::make_pair(&R, Context.Log));
777
778 if (!HasErrors) {
Tobias Grosser75805372011-04-29 06:27:02 +0000779 ++ValidRegion;
780 ValidRegions.insert(&R);
781 return;
782 }
783
David Blaikieb035f6d2014-04-15 18:45:27 +0000784 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000785 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000786
787 // Try to expand regions.
788 //
789 // As the region tree normally only contains canonical regions, non canonical
790 // regions that form a Scop are not found. Therefore, those non canonical
791 // regions are checked by expanding the canonical ones.
792
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000793 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000794
David Blaikieb035f6d2014-04-15 18:45:27 +0000795 for (auto &SubRegion : R)
796 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000797
Tobias Grosser26108892014-04-02 20:18:19 +0000798 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000799 // Skip regions that had errors.
800 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
801 if (HadErrors)
802 continue;
803
Tobias Grosser75805372011-04-29 06:27:02 +0000804 // Skip invalid regions. Regions may become invalid, if they are element of
805 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +0000806 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +0000807 continue;
808
809 Region *ExpandedR = expandRegion(*CurrentRegion);
810
811 if (!ExpandedR)
812 continue;
813
814 R.addSubRegion(ExpandedR, true);
815 ValidRegions.insert(ExpandedR);
David Peixotto8da2b932014-10-22 20:39:07 +0000816 ValidRegions.remove(CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000817
Tobias Grosser28a70c52014-01-29 19:05:30 +0000818 // Erase all (direct and indirect) children of ExpandedR from the valid
819 // regions and update the number of valid regions.
David Blaikieb035f6d2014-04-15 18:45:27 +0000820 ValidRegion -= eraseAllChildren(ValidRegions, *ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000821 }
822}
823
824bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000825 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000826
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000827 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000828 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000829 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000830 return false;
831 }
832
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000833 for (BasicBlock *BB : CurRegion.blocks())
Andreas Simbuerger04472402014-05-24 09:25:10 +0000834 if (!isValidCFG(*BB, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000835 return false;
836
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000837 for (BasicBlock *BB : CurRegion.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000838 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000839 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000840 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000841
Sebastian Pope8863b82014-05-12 19:02:02 +0000842 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000843 return false;
844
Tobias Grosser75805372011-04-29 06:27:02 +0000845 return true;
846}
847
848bool ScopDetection::isValidExit(DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000849
850 // PHI nodes are not allowed in the exit basic block.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000851 if (BasicBlock *Exit = Context.CurRegion.getExit()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000852 BasicBlock::iterator I = Exit->begin();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000853 if (I != Exit->end() && isa<PHINode>(*I))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000854 return invalid<ReportPHIinExit>(Context, /*Assert=*/true, I);
Tobias Grosser75805372011-04-29 06:27:02 +0000855 }
856
857 return true;
858}
859
860bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000861 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000862
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000863 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +0000864
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000865 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +0000866 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000867 return false;
868 }
869
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000870 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +0000871 DEBUG({
872 dbgs() << "Region entry does not match -polly-region-only";
873 dbgs() << "\n";
874 });
875 return false;
876 }
877
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000878 if (!CurRegion.getEnteringBlock()) {
879 BasicBlock *entry = CurRegion.getEntry();
Sebastian Pop9d632342013-06-11 22:20:40 +0000880 Loop *L = LI->getLoopFor(entry);
881
882 if (L) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000883 if (!L->isLoopSimplifyForm())
884 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Sebastian Pop9d632342013-06-11 22:20:40 +0000885
886 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
887 ++PI) {
888 // Region entering edges come from the same loop but outside the region
889 // are not allowed.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000890 if (L->contains(*PI) && !CurRegion.contains(*PI))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000891 return invalid<ReportIndEdge>(Context, /*Assert=*/true, *PI);
Sebastian Pop9d632342013-06-11 22:20:40 +0000892 }
893 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000894 }
895
Tobias Grosserd654c252012-04-10 18:12:19 +0000896 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000897 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000898 if (CurRegion.getEntry() ==
899 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
900 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +0000901
Hongbin Zheng94868e62012-04-07 12:29:17 +0000902 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000903 return false;
904
Hongbin Zheng94868e62012-04-07 12:29:17 +0000905 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000906 return false;
907
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000908 // We can probably not do a lot on scops that only write or only read
909 // data.
910 if (!DetectUnprofitable && (!Context.hasStores || !Context.hasLoads))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000911 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000912
Tobias Grosser75805372011-04-29 06:27:02 +0000913 DEBUG(dbgs() << "OK\n");
914 return true;
915}
916
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000917void ScopDetection::markFunctionAsInvalid(Function *F) const {
918 F->addFnAttr(PollySkipFnAttr);
919}
920
Tobias Grosser75805372011-04-29 06:27:02 +0000921bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000922 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +0000923}
924
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000925void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +0000926 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +0000927 unsigned LineEntry, LineExit;
928 std::string FileName;
929
Tobias Grosser00dc3092014-03-02 12:02:46 +0000930 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +0000931 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
932 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +0000933 }
934}
935
Daniel Jasper8a1dea02014-10-27 19:45:31 +0000936void ScopDetection::emitMissedRemarksForValidRegions(
937 const Function &F, const RegionSet &ValidRegions) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000938 for (const Region *R : ValidRegions) {
939 const Region *Parent = R->getParent();
940 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
941 emitRejectionRemarks(F, RejectLogs.at(Parent));
942 }
943}
944
945void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
946 const Region *R) {
947 for (const std::unique_ptr<Region> &Child : *R) {
948 bool IsValid = ValidRegions.count(Child.get());
949 if (IsValid)
950 continue;
951
952 bool IsLeaf = Child->begin() == Child->end();
953 if (!IsLeaf)
954 emitMissedRemarksForLeaves(F, Child.get());
955 else {
956 if (RejectLogs.count(Child.get())) {
957 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
958 }
959 }
960 }
961}
962
Tobias Grosser75805372011-04-29 06:27:02 +0000963bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +0000964 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000965 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000966 if (!DetectScopsWithoutLoops && LI->empty())
967 return false;
968
Tobias Grosser75805372011-04-29 06:27:02 +0000969 AA = &getAnalysis<AliasAnalysis>();
970 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000971 Region *TopRegion = RI->getTopLevelRegion();
972
Tobias Grosser2ff87232011-10-23 11:17:06 +0000973 releaseMemory();
974
Tobias Grossera3ab27e2014-05-07 11:23:32 +0000975 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +0000976 return false;
977
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000978 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000979 return false;
980
981 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000982
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000983 // Only makes sense when we tracked errors.
984 if (PollyTrackFailures) {
985 emitMissedRemarksForValidRegions(F, ValidRegions);
986 emitMissedRemarksForLeaves(F, TopRegion);
987 }
988
989 for (const Region *R : ValidRegions)
990 emitValidRemarks(F, R);
991
Johannes Doerferta05214f2014-10-15 23:24:28 +0000992 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000993 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000994
Tobias Grosser75805372011-04-29 06:27:02 +0000995 return false;
996}
997
Johannes Doerfertba65c162015-02-24 11:45:21 +0000998bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
999 const Region *ScopR) const {
1000 return NonAffineSubRegionMap.lookup(ScopR).count(SubR);
1001}
1002
Tobias Grosser75805372011-04-29 06:27:02 +00001003void polly::ScopDetection::verifyRegion(const Region &R) const {
1004 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertba65c162015-02-24 11:45:21 +00001005 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
1006 DetectionContext Context(const_cast<Region &>(R), *AA,
1007 DummyNonAffineSubRegionSet, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001008 isValidRegion(Context);
1009}
1010
1011void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001012 if (!VerifyScops)
1013 return;
1014
Tobias Grosser26108892014-04-02 20:18:19 +00001015 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001016 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001017}
1018
1019void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001020 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001021 AU.addRequired<ScalarEvolution>();
1022 // We also need AA and RegionInfo when we are verifying analysis.
1023 AU.addRequiredTransitive<AliasAnalysis>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001024 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001025 AU.setPreservesAll();
1026}
1027
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001028void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001029 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001030 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001031
1032 OS << "\n";
1033}
1034
1035void ScopDetection::releaseMemory() {
1036 ValidRegions.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001037 RejectLogs.clear();
Johannes Doerfertba65c162015-02-24 11:45:21 +00001038 NonAffineSubRegionMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001039
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001040 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001041}
1042
1043char ScopDetection::ID = 0;
1044
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001045Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1046
Tobias Grosser73600b82011-10-08 00:30:40 +00001047INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1048 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001049 false);
1050INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00001051INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001052INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001053INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +00001054INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1055 "Polly - Detect static control parts (SCoPs)", false, false)