blob: 11edd13bf1a11cc7fe51d31242f20af3c0753cb2 [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"
Tobias Grosser8519f892013-12-18 10:49:53 +000063#include "llvm/IR/DiagnosticInfo.h"
64#include "llvm/IR/DiagnosticPrinter.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>
68
Tobias Grosser75805372011-04-29 06:27:02 +000069using namespace llvm;
70using namespace polly;
71
Chandler Carruth95fef942014-04-22 03:30:19 +000072#define DEBUG_TYPE "polly-detect"
73
Sebastian Pop8fe6d112013-05-30 17:47:32 +000074static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000075 DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
76 cl::desc("Detect scops in functions without loops"),
77 cl::Hidden, cl::init(false), cl::ZeroOrMore,
78 cl::cat(PollyCategory));
Sebastian Pop8fe6d112013-05-30 17:47:32 +000079
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000080static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000081 DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
82 cl::desc("Detect scops in regions without loops"),
83 cl::Hidden, cl::init(false), cl::ZeroOrMore,
84 cl::cat(PollyCategory));
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000085
Tobias Grosser483a90d2014-07-09 10:50:10 +000086static cl::opt<std::string> OnlyFunction(
87 "polly-only-func",
88 cl::desc("Only run on functions that contain a certain string"),
89 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
90 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000091
Tobias Grosser483a90d2014-07-09 10:50:10 +000092static cl::opt<std::string> OnlyRegion(
93 "polly-only-region",
94 cl::desc("Only run on certain regions (The provided identifier must "
95 "appear in the name of the region's entry block"),
96 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +000098
Tobias Grosser60cd9322011-11-10 12:47:26 +000099static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000100 IgnoreAliasing("polly-ignore-aliasing",
101 cl::desc("Ignore possible aliasing of the array bases"),
102 cl::Hidden, cl::init(false), cl::ZeroOrMore,
103 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000104
Johannes Doerfertb164c792014-09-18 11:17:17 +0000105bool polly::PollyUseRuntimeAliasChecks;
106static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
107 "polly-use-runtime-alias-checks",
108 cl::desc("Use runtime alias checks to resolve possible aliasing."),
109 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
110 cl::init(true), cl::cat(PollyCategory));
111
Tobias Grosser637bd632013-05-07 07:31:10 +0000112static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000113 ReportLevel("polly-report",
114 cl::desc("Print information about the activities of Polly"),
115 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000116
117static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000118 AllowNonAffine("polly-allow-nonaffine",
119 cl::desc("Allow non affine access functions in arrays"),
120 cl::Hidden, cl::init(false), cl::ZeroOrMore,
121 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000122
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000123static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000124 TrackFailures("polly-detect-track-failures",
125 cl::desc("Track failure strings in detecting scop regions"),
126 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000127 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000128
Andreas Simbuerger04472402014-05-24 09:25:10 +0000129static cl::opt<bool> KeepGoing("polly-detect-keep-going",
130 cl::desc("Do not fail on the first error."),
131 cl::Hidden, cl::ZeroOrMore, cl::init(false),
132 cl::cat(PollyCategory));
133
Sebastian Pop18016682014-04-08 21:20:44 +0000134static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000135 PollyDelinearizeX("polly-delinearize",
136 cl::desc("Delinearize array access functions"),
137 cl::location(PollyDelinearize), cl::Hidden,
138 cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000139
Tobias Grossera1689932014-02-18 18:49:49 +0000140static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000141 VerifyScops("polly-detect-verify",
142 cl::desc("Verify the detected SCoPs after each transformation"),
143 cl::Hidden, cl::init(false), cl::ZeroOrMore,
144 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000145
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000146bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000147bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000148StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000149
Tobias Grosser75805372011-04-29 06:27:02 +0000150//===----------------------------------------------------------------------===//
151// Statistics.
152
153STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
154
Tobias Grosser8519f892013-12-18 10:49:53 +0000155class DiagnosticScopFound : public DiagnosticInfo {
156private:
157 static int PluginDiagnosticKind;
158
159 Function &F;
160 std::string FileName;
161 unsigned EntryLine, ExitLine;
162
163public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000164 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
165 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000166 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000167 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000168
169 virtual void print(DiagnosticPrinter &DP) const;
170
171 static bool classof(const DiagnosticInfo *DI) {
172 return DI->getKind() == PluginDiagnosticKind;
173 }
174};
175
176int DiagnosticScopFound::PluginDiagnosticKind = 10;
177
Tobias Grosser8519f892013-12-18 10:49:53 +0000178void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000179 DP << "Polly detected an optimizable loop region (scop) in function '" << F
180 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000181
182 if (FileName.empty()) {
183 DP << "Scop location is unknown. Compile with debug info "
184 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000185 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000186 }
187
188 DP << FileName << ":" << EntryLine << ": Start of scop\n";
189 DP << FileName << ":" << ExitLine << ": End of scop";
190}
191
Tobias Grosser75805372011-04-29 06:27:02 +0000192//===----------------------------------------------------------------------===//
193// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000194
Johannes Doerfertb164c792014-09-18 11:17:17 +0000195ScopDetection::ScopDetection() : FunctionPass(ID) {
196 if (!PollyUseRuntimeAliasChecks)
197 return;
198
199 if (PollyDelinearize) {
200 DEBUG(errs() << "WARNING: We disable runtime alias checks as "
201 "delinearization is enabled.\n");
202 PollyUseRuntimeAliasChecks = false;
203 }
204
205 if (AllowNonAffine) {
206 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
207 "accesses are enabled.\n");
208 PollyUseRuntimeAliasChecks = false;
209 }
210
211#ifdef CLOOG_FOUND
212 if (PollyCodeGenChoice == CODEGEN_CLOOG) {
213 DEBUG(errs() << "WARNING: We disable runtime alias checks as the cloog "
214 "code generation cannot emit them.\n");
215 PollyUseRuntimeAliasChecks = false;
216 }
217#endif
218}
219
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000220template <class RR, typename... Args>
221inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
222 Args &&... Arguments) const {
223
224 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000225 RejectLog &Log = Context.Log;
226 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000227
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000228 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000229 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000230
231 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000232 DEBUG(dbgs() << "\n");
233 } else {
234 assert(!Assert && "Verification of detected scop failed");
235 }
236
237 return false;
238}
239
Tobias Grossera1689932014-02-18 18:49:49 +0000240bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
241 if (!ValidRegions.count(&R))
242 return false;
243
244 if (Verify)
245 return isValidRegion(const_cast<Region &>(R));
246
247 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000248}
249
Tobias Grosser4f129a62011-10-08 00:30:55 +0000250std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000251 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000252 return "";
253
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000254 // Get the first error we found. Even in keep-going mode, this is the first
255 // reason that caused the candidate to be rejected.
256 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000257
258 // This can happen when we marked a region invalid, but didn't track
259 // an error for it.
260 if (Errors.size() == 0)
261 return "";
262
263 RejectReasonPtr RR = *Errors.begin();
264 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000265}
266
Tobias Grossere602a072013-05-07 07:30:56 +0000267bool ScopDetection::isValidCFG(BasicBlock &BB,
268 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000269 Region &RefRegion = Context.CurRegion;
270 TerminatorInst *TI = BB.getTerminator();
271
272 // Return instructions are only valid if the region is the top level region.
273 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
274 return true;
275
276 BranchInst *Br = dyn_cast<BranchInst>(TI);
277
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000278 if (!Br)
279 return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000280
Tobias Grosser74394f02013-01-14 22:40:23 +0000281 if (Br->isUnconditional())
282 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000283
284 Value *Condition = Br->getCondition();
285
286 // UndefValue is not allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000287 if (isa<UndefValue>(Condition))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000288 return invalid<ReportUndefCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000289
290 // Only Constant and ICmpInst are allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000291 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000292 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000293
294 // Allow perfectly nested conditions.
295 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
296
297 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
298 // Unsigned comparisons are not allowed. They trigger overflow problems
299 // in the code generation.
300 //
301 // TODO: This is not sufficient and just hides bugs. However it does pretty
302 // well.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000303 if (ICmp->isUnsigned())
Tobias Grosser75805372011-04-29 06:27:02 +0000304 return false;
305
306 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000307 if (isa<UndefValue>(ICmp->getOperand(0)) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000308 isa<UndefValue>(ICmp->getOperand(1)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000309 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000310
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000311 Loop *L = LI->getLoopFor(ICmp->getParent());
312 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
313 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000314
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000315 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000316 !isAffineExpr(&Context.CurRegion, RHS, *SE))
317 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000318 RHS, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000319 }
320
321 // Allow loop exit conditions.
322 Loop *L = LI->getLoopFor(&BB);
323 if (L && L->getExitingBlock() == &BB)
324 return true;
325
326 // Allow perfectly nested conditions.
327 Region *R = RI->getRegionFor(&BB);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000328 if (R->getEntry() != &BB)
329 return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000330
331 return true;
332}
333
334bool ScopDetection::isValidCallInst(CallInst &CI) {
335 if (CI.mayHaveSideEffects() || CI.doesNotReturn())
336 return false;
337
338 if (CI.doesNotAccessMemory())
339 return true;
340
341 Function *CalledFunction = CI.getCalledFunction();
342
343 // Indirect calls are not supported.
344 if (CalledFunction == 0)
345 return false;
346
347 // TODO: Intrinsics.
348 return false;
349}
350
Tobias Grosser458fb782014-01-28 12:58:58 +0000351bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
352 // A reference to function argument or constant value is invariant.
353 if (isa<Argument>(Val) || isa<Constant>(Val))
354 return true;
355
356 const Instruction *I = dyn_cast<Instruction>(&Val);
357 if (!I)
358 return false;
359
360 if (!Reg.contains(I))
361 return true;
362
363 if (I->mayHaveSideEffects())
364 return false;
365
366 // When Val is a Phi node, it is likely not invariant. We do not check whether
367 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
368 // invariant. Recursively checking the operators of Phi nodes would lead to
369 // infinite recursion.
370 if (isa<PHINode>(*I))
371 return false;
372
Tobias Grosser26108892014-04-02 20:18:19 +0000373 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000374 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000375 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000376
377 // When the instruction is a load instruction, check that no write to memory
378 // in the region aliases with the load.
379 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
380 AliasAnalysis::Location Loc = AA->getLocation(LI);
381 const Region::const_block_iterator BE = Reg.block_end();
382 // Check if any basic block in the region can modify the location pointed to
383 // by 'Loc'. If so, 'Val' is (likely) not invariant in the region.
Tobias Grosser26108892014-04-02 20:18:19 +0000384 for (const BasicBlock *BB : Reg.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000385 if (AA->canBasicBlockModify(*BB, Loc))
Tobias Grosser458fb782014-01-28 12:58:58 +0000386 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000387 }
388
389 return true;
390}
391
Sebastian Pop422e33f2014-06-03 18:16:31 +0000392MapInsnToMemAcc InsnToMemAcc;
393
Sebastian Popb57c0992014-05-12 20:24:26 +0000394bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Tobias Grosser230acc42014-09-13 14:47:55 +0000395 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000396 Value *BaseValue = BasePointer->getValue();
Sebastian Pop422e33f2014-06-03 18:16:31 +0000397 ArrayShape *Shape = new ArrayShape(BasePointer);
Tobias Grosser230acc42014-09-13 14:47:55 +0000398 bool BasePtrHasNonAffine = false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000399
400 // First step: collect parametric terms in all array references.
401 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser230acc42014-09-13 14:47:55 +0000402 for (const auto &Pair : Context.Accesses[BasePointer]) {
403 const SCEVAddRecExpr *AccessFunction =
404 dyn_cast<SCEVAddRecExpr>(Pair.second);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000405
Tobias Grosser230acc42014-09-13 14:47:55 +0000406 if (AccessFunction)
407 AccessFunction->collectParametricTerms(*SE, Terms);
408 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000409
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000410 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000411 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
412 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000413
Tobias Grosser230acc42014-09-13 14:47:55 +0000414 // No array shape derived.
415 if (Shape->DelinearizedSizes.empty()) {
416 if (AllowNonAffine)
417 continue;
Sebastian Pope8863b82014-05-12 19:02:02 +0000418
Tobias Grosser230acc42014-09-13 14:47:55 +0000419 for (const auto &Pair : Context.Accesses[BasePointer]) {
420 const Instruction *Insn = Pair.first;
421 const SCEV *AF = Pair.second;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000422
Tobias Grosser230acc42014-09-13 14:47:55 +0000423 if (!isAffineExpr(&Context.CurRegion, AF, *SE, BaseValue)) {
424 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
425 BaseValue);
426 if (!KeepGoing)
427 return false;
428 }
429 }
430 continue;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000431 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000432
433 // Third step: compute the access functions for each subscript.
434 //
435 // We first store the resulting memory accesses in TempMemoryAccesses. Only
436 // if the access functions for all memory accesses have been successfully
437 // delinearized we continue. Otherwise, we either report a failure or, if
438 // non-affine accesses are allowed, we drop the information. In case the
439 // information is dropped the memory accesses need to be overapproximated
440 // when translated to a polyhedral representation.
441 MapInsnToMemAcc TempMemoryAccesses;
442 for (const auto &Pair : Context.Accesses[BasePointer]) {
443 const Instruction *Insn = Pair.first;
444 const SCEVAddRecExpr *AF = dyn_cast<SCEVAddRecExpr>(Pair.second);
445 bool IsNonAffine = false;
446 MemAcc *Acc = new MemAcc(Insn, Shape);
447 TempMemoryAccesses.insert({Insn, Acc});
448
449 if (!AF) {
450 if (isAffineExpr(&Context.CurRegion, Pair.second, *SE, BaseValue))
451 Acc->DelinearizedSubscripts.push_back(Pair.second);
452 else
453 IsNonAffine = true;
454 } else {
455 AF->computeAccessFunctions(*SE, Acc->DelinearizedSubscripts,
456 Shape->DelinearizedSizes);
457 if (Acc->DelinearizedSubscripts.size() == 0)
458 IsNonAffine = true;
459 for (const SCEV *S : Acc->DelinearizedSubscripts)
460 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseValue))
461 IsNonAffine = true;
462 }
463
464 // (Possibly) report non affine access
465 if (IsNonAffine) {
466 BasePtrHasNonAffine = true;
467 if (!AllowNonAffine)
468 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
469 BaseValue);
470 if (!KeepGoing && !AllowNonAffine)
471 return false;
472 }
473 }
474
475 if (!BasePtrHasNonAffine)
476 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000477 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000478 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000479}
480
Tobias Grosser75805372011-04-29 06:27:02 +0000481bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
482 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000483 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000484 Loop *L = LI->getLoopFor(Inst.getParent());
485 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000486 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000487 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000488
Tobias Grosserb8710b52011-11-10 12:44:50 +0000489 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
490
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000491 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000492 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000493
494 BaseValue = BasePointer->getValue();
495
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000496 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000497 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000498
Tobias Grosser458fb782014-01-28 12:58:58 +0000499 // Check that the base address of the access is invariant in the current
500 // region.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000501 if (!isInvariant(*BaseValue, Context.CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000502 // Verification of this property is difficult as the independent blocks
503 // pass may introduce aliasing that we did not have when running the
504 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000505 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
506 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000507
Tobias Grosserb8710b52011-11-10 12:44:50 +0000508 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
509
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000510 const SCEV *Size = SE->getElementSize(&Inst);
511 if (Context.ElementSize.count(BasePointer)) {
512 if (Context.ElementSize[BasePointer] != Size)
513 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
514 &Inst, BaseValue);
515 } else {
516 Context.ElementSize[BasePointer] = Size;
517 }
518
Tobias Grosser230acc42014-09-13 14:47:55 +0000519 if (PollyDelinearize) {
520 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000521
Tobias Grosser230acc42014-09-13 14:47:55 +0000522 if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue))
523 Context.NonAffineAccesses.insert(BasePointer);
524 } else if (!AllowNonAffine) {
525 if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000526 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000527 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000528 }
Tobias Grosser75805372011-04-29 06:27:02 +0000529
530 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
531 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000532 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
533 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000534
Johannes Doerfertb164c792014-09-18 11:17:17 +0000535 if (PollyUseRuntimeAliasChecks || IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000536 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000537
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000538 // Check if the base pointer of the memory access does alias with
539 // any other pointer. This cannot be handled at the moment.
Tobias Grosser298a7642013-07-14 18:09:43 +0000540 AliasSet &AS =
541 Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
542 Inst.getMetadata(LLVMContext::MD_tbaa));
Tobias Grosser428b3e42013-02-04 15:46:25 +0000543
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000544 // INVALID triggers an assertion in verifying mode, if it detects that a
545 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
546 // a pass that stated it would preserve the SCoPs. We disable this check as
547 // the independent blocks pass may create memory references which seem to
548 // alias, if -basicaa is not available. They actually do not, but as we can
549 // not proof this without -basicaa we would fail. We disable this check to
550 // not cause irrelevant verification failures.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000551 if (!AS.isMustAlias())
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000552 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser75805372011-04-29 06:27:02 +0000553
554 return true;
555}
556
Tobias Grosser75805372011-04-29 06:27:02 +0000557bool ScopDetection::isValidInstruction(Instruction &Inst,
558 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000559 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000560 if (!canSynthesize(PN, LI, SE, &Context.CurRegion)) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000561 if (SCEVCodegen)
562 return invalid<ReportPhiNodeRefInRegion>(Context, /*Assert=*/true,
563 &Inst);
564 else
565 return invalid<ReportNonCanonicalPhiNode>(Context, /*Assert=*/true,
566 &Inst);
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000567 }
Tobias Grosser75805372011-04-29 06:27:02 +0000568
Tobias Grosser75805372011-04-29 06:27:02 +0000569 // We only check the call instruction but not invoke instruction.
570 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
571 if (isValidCallInst(*CI))
572 return true;
573
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000574 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000575 }
576
577 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000578 if (!isa<AllocaInst>(Inst))
579 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000580
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000581 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000582 }
583
584 // Check the access function.
585 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
586 return isValidMemoryAccess(Inst, Context);
587
588 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000589 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000590}
591
Tobias Grosser75805372011-04-29 06:27:02 +0000592bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000593 if (!SCEVCodegen) {
594 // If code generation is not in scev based mode, we need to ensure that
595 // each loop has a canonical induction variable.
596 PHINode *IndVar = L->getCanonicalInductionVariable();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000597 if (!IndVar)
598 return invalid<ReportLoopHeader>(Context, /*Assert=*/true, L);
Tobias Grosser826b2af2013-03-21 16:14:50 +0000599 }
Tobias Grosser75805372011-04-29 06:27:02 +0000600
601 // Is the loop count affine?
602 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000603 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
604 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000605
606 return true;
607}
608
609Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000610 // Initial no valid region was found (greater than R)
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000611 Region *LastValidRegion = nullptr;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000612 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000613
614 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
615
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000616 while (ExpandedRegion) {
617 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
618 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000619 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000620
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000621 // Check the exit first (cheap)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000622 if (isValidExit(Context) && !Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000623 // If the exit is valid check all blocks
624 // - if true, a valid region was found => store it + keep expanding
625 // - if false, .tbd. => stop (should this really end the loop?)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000626 if (!allBlocksValid(Context) || Context.Log.hasErrors())
627 break;
628
629 if (Context.Log.hasErrors())
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000630 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000631
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000632 // Delete unnecessary regions (allocated by getExpandedRegion)
633 if (LastValidRegion)
634 delete LastValidRegion;
635
Tobias Grosserd7e58642013-04-10 06:55:45 +0000636 // Store this region, because it is the greatest valid (encountered so
637 // far).
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000638 LastValidRegion = ExpandedRegion;
639
640 // Create and test the next greater region (if any)
641 ExpandedRegion = ExpandedRegion->getExpandedRegion();
642
643 } else {
644 // Create and test the next greater region (if any)
645 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
646
647 // Delete unnecessary regions (allocated by getExpandedRegion)
648 delete ExpandedRegion;
649
650 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000651 }
Tobias Grosser75805372011-04-29 06:27:02 +0000652 }
653
Tobias Grosser378a9f22013-11-16 19:34:11 +0000654 DEBUG({
655 if (LastValidRegion)
656 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
657 else
658 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
659 });
Tobias Grosser75805372011-04-29 06:27:02 +0000660
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000661 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000662}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000663static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000664 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000665 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000666 return false;
667
668 return true;
669}
Tobias Grosser75805372011-04-29 06:27:02 +0000670
Tobias Grosser28a70c52014-01-29 19:05:30 +0000671// Remove all direct and indirect children of region R from the region set Regs,
672// but do not recurse further if the first child has been found.
673//
674// Return the number of regions erased from Regs.
675static unsigned eraseAllChildren(std::set<const Region *> &Regs,
David Blaikieb035f6d2014-04-15 18:45:27 +0000676 const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000677 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000678 for (auto &SubRegion : R) {
679 if (Regs.find(SubRegion.get()) != Regs.end()) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000680 ++Count;
David Blaikieb035f6d2014-04-15 18:45:27 +0000681 Regs.erase(SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000682 } else {
David Blaikieb035f6d2014-04-15 18:45:27 +0000683 Count += eraseAllChildren(Regs, *SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000684 }
685 }
686 return Count;
687}
688
Tobias Grosser75805372011-04-29 06:27:02 +0000689void ScopDetection::findScops(Region &R) {
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000690 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
691 return;
692
Andreas Simbuerger04472402014-05-24 09:25:10 +0000693 bool IsValidRegion = isValidRegion(R);
694 bool HasErrors = RejectLogs.count(&R) > 0;
695
696 if (IsValidRegion && !HasErrors) {
Tobias Grosser75805372011-04-29 06:27:02 +0000697 ++ValidRegion;
698 ValidRegions.insert(&R);
699 return;
700 }
701
David Blaikieb035f6d2014-04-15 18:45:27 +0000702 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000703 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000704
705 // Try to expand regions.
706 //
707 // As the region tree normally only contains canonical regions, non canonical
708 // regions that form a Scop are not found. Therefore, those non canonical
709 // regions are checked by expanding the canonical ones.
710
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000711 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000712
David Blaikieb035f6d2014-04-15 18:45:27 +0000713 for (auto &SubRegion : R)
714 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000715
Tobias Grosser26108892014-04-02 20:18:19 +0000716 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000717 // Skip regions that had errors.
718 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
719 if (HadErrors)
720 continue;
721
Tobias Grosser75805372011-04-29 06:27:02 +0000722 // Skip invalid regions. Regions may become invalid, if they are element of
723 // an already expanded region.
724 if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
725 continue;
726
727 Region *ExpandedR = expandRegion(*CurrentRegion);
728
729 if (!ExpandedR)
730 continue;
731
732 R.addSubRegion(ExpandedR, true);
733 ValidRegions.insert(ExpandedR);
734 ValidRegions.erase(CurrentRegion);
735
Tobias Grosser28a70c52014-01-29 19:05:30 +0000736 // Erase all (direct and indirect) children of ExpandedR from the valid
737 // regions and update the number of valid regions.
David Blaikieb035f6d2014-04-15 18:45:27 +0000738 ValidRegion -= eraseAllChildren(ValidRegions, *ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000739 }
740}
741
742bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
743 Region &R = Context.CurRegion;
744
Tobias Grosser26108892014-04-02 20:18:19 +0000745 for (const BasicBlock *BB : R.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000746 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000747 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000748 return false;
749 }
750
Tobias Grosser26108892014-04-02 20:18:19 +0000751 for (BasicBlock *BB : R.blocks())
Andreas Simbuerger04472402014-05-24 09:25:10 +0000752 if (!isValidCFG(*BB, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000753 return false;
754
Tobias Grosser26108892014-04-02 20:18:19 +0000755 for (BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000756 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000757 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000758 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000759
Sebastian Pope8863b82014-05-12 19:02:02 +0000760 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000761 return false;
762
Tobias Grosser75805372011-04-29 06:27:02 +0000763 return true;
764}
765
766bool ScopDetection::isValidExit(DetectionContext &Context) const {
767 Region &R = Context.CurRegion;
768
769 // PHI nodes are not allowed in the exit basic block.
770 if (BasicBlock *Exit = R.getExit()) {
771 BasicBlock::iterator I = Exit->begin();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000772 if (I != Exit->end() && isa<PHINode>(*I))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000773 return invalid<ReportPHIinExit>(Context, /*Assert=*/true, I);
Tobias Grosser75805372011-04-29 06:27:02 +0000774 }
775
776 return true;
777}
778
Tobias Grosser9b1100b2014-02-18 18:49:46 +0000779bool ScopDetection::isValidRegion(Region &R) const {
780 DetectionContext Context(R, *AA, false /*verifying*/);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000781
782 bool RegionIsValid = isValidRegion(Context);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000783 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
784
Andreas Simbuerger5bf774c2014-06-26 13:36:52 +0000785 if (PollyTrackFailures && HasErrors)
786 RejectLogs.insert(std::make_pair(&R, Context.Log));
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000787
788 return RegionIsValid;
Tobias Grosser9b1100b2014-02-18 18:49:46 +0000789}
790
Tobias Grosser75805372011-04-29 06:27:02 +0000791bool ScopDetection::isValidRegion(DetectionContext &Context) const {
792 Region &R = Context.CurRegion;
793
794 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
795
Tobias Grosseraeabcf22013-04-02 06:41:48 +0000796 if (R.isTopLevelRegion()) {
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000797 DEBUG(dbgs() << "Top level region is invalid"; dbgs() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000798 return false;
799 }
800
Tobias Grosser4449e522014-01-27 14:24:53 +0000801 if (!R.getEntry()->getName().count(OnlyRegion)) {
802 DEBUG({
803 dbgs() << "Region entry does not match -polly-region-only";
804 dbgs() << "\n";
805 });
806 return false;
807 }
808
Tobias Grossere602a072013-05-07 07:30:56 +0000809 if (!R.getEnteringBlock()) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000810 BasicBlock *entry = R.getEntry();
811 Loop *L = LI->getLoopFor(entry);
812
813 if (L) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000814 if (!L->isLoopSimplifyForm())
815 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Sebastian Pop9d632342013-06-11 22:20:40 +0000816
817 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
818 ++PI) {
819 // Region entering edges come from the same loop but outside the region
820 // are not allowed.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000821 if (L->contains(*PI) && !R.contains(*PI))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000822 return invalid<ReportIndEdge>(Context, /*Assert=*/true, *PI);
Sebastian Pop9d632342013-06-11 22:20:40 +0000823 }
824 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000825 }
826
Tobias Grosserd654c252012-04-10 18:12:19 +0000827 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000828 // to insert alloca instruction there when translate scalar to array.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000829 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000830 return invalid<ReportEntry>(Context, /*Assert=*/true, R.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +0000831
Hongbin Zheng94868e62012-04-07 12:29:17 +0000832 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000833 return false;
834
Hongbin Zheng94868e62012-04-07 12:29:17 +0000835 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000836 return false;
837
838 DEBUG(dbgs() << "OK\n");
839 return true;
840}
841
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000842void ScopDetection::markFunctionAsInvalid(Function *F) const {
843 F->addFnAttr(PollySkipFnAttr);
844}
845
Tobias Grosser75805372011-04-29 06:27:02 +0000846bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000847 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +0000848}
849
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000850void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +0000851 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +0000852 unsigned LineEntry, LineExit;
853 std::string FileName;
854
Tobias Grosser00dc3092014-03-02 12:02:46 +0000855 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +0000856 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
857 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +0000858 }
859}
860
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000861void
862ScopDetection::emitMissedRemarksForValidRegions(const Function &F,
863 const RegionSet &ValidRegions) {
864 for (const Region *R : ValidRegions) {
865 const Region *Parent = R->getParent();
866 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
867 emitRejectionRemarks(F, RejectLogs.at(Parent));
868 }
869}
870
871void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
872 const Region *R) {
873 for (const std::unique_ptr<Region> &Child : *R) {
874 bool IsValid = ValidRegions.count(Child.get());
875 if (IsValid)
876 continue;
877
878 bool IsLeaf = Child->begin() == Child->end();
879 if (!IsLeaf)
880 emitMissedRemarksForLeaves(F, Child.get());
881 else {
882 if (RejectLogs.count(Child.get())) {
883 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
884 }
885 }
886 }
887}
888
Tobias Grosser75805372011-04-29 06:27:02 +0000889bool ScopDetection::runOnFunction(llvm::Function &F) {
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000890 LI = &getAnalysis<LoopInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000891 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000892 if (!DetectScopsWithoutLoops && LI->empty())
893 return false;
894
Tobias Grosser75805372011-04-29 06:27:02 +0000895 AA = &getAnalysis<AliasAnalysis>();
896 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000897 Region *TopRegion = RI->getTopLevelRegion();
898
Tobias Grosser2ff87232011-10-23 11:17:06 +0000899 releaseMemory();
900
Tobias Grossera3ab27e2014-05-07 11:23:32 +0000901 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +0000902 return false;
903
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000904 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000905 return false;
906
907 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000908
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000909 // Only makes sense when we tracked errors.
910 if (PollyTrackFailures) {
911 emitMissedRemarksForValidRegions(F, ValidRegions);
912 emitMissedRemarksForLeaves(F, TopRegion);
913 }
914
915 for (const Region *R : ValidRegions)
916 emitValidRemarks(F, R);
917
Tobias Grosser531891e2012-11-01 16:45:20 +0000918 if (ReportLevel >= 1)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000919 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000920
Tobias Grosser75805372011-04-29 06:27:02 +0000921 return false;
922}
923
Tobias Grosser75805372011-04-29 06:27:02 +0000924void polly::ScopDetection::verifyRegion(const Region &R) const {
925 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000926 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +0000927 isValidRegion(Context);
928}
929
930void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +0000931 if (!VerifyScops)
932 return;
933
Tobias Grosser26108892014-04-02 20:18:19 +0000934 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000935 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +0000936}
937
938void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser42aff302014-01-13 22:29:56 +0000939 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +0000940 AU.addRequired<PostDominatorTree>();
941 AU.addRequired<LoopInfo>();
942 AU.addRequired<ScalarEvolution>();
943 // We also need AA and RegionInfo when we are verifying analysis.
944 AU.addRequiredTransitive<AliasAnalysis>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000945 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +0000946 AU.setPreservesAll();
947}
948
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000949void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +0000950 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000951 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +0000952
953 OS << "\n";
954}
955
956void ScopDetection::releaseMemory() {
957 ValidRegions.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000958 RejectLogs.clear();
959
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000960 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +0000961}
962
963char ScopDetection::ID = 0;
964
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000965Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
966
Tobias Grosser73600b82011-10-08 00:30:40 +0000967INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
968 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000969 false);
970INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Tobias Grosser42aff302014-01-13 22:29:56 +0000971INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000972INITIALIZE_PASS_DEPENDENCY(LoopInfo);
973INITIALIZE_PASS_DEPENDENCY(PostDominatorTree);
Matt Arsenault8ca36812014-07-19 18:40:17 +0000974INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000975INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +0000976INITIALIZE_PASS_END(ScopDetection, "polly-detect",
977 "Polly - Detect static control parts (SCoPs)", false, false)