blob: 661efab7fc588733c2fa053001c14b45ae028019 [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 Grosserba0d0922015-05-09 09:13:42 +000048#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000050#include "polly/Options.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000051#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000052#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000053#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000054#include "polly/Support/ScopHelper.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000055#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000056#include "llvm/ADT/Statistic.h"
57#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000058#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000059#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000060#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000061#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000063#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000064#include "llvm/IR/DiagnosticInfo.h"
65#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000066#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000067#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000068#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000069#include <set>
70
Tobias Grosser75805372011-04-29 06:27:02 +000071using namespace llvm;
72using namespace polly;
73
Chandler Carruth95fef942014-04-22 03:30:19 +000074#define DEBUG_TYPE "polly-detect"
75
Sebastian Pop8fe6d112013-05-30 17:47:32 +000076static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000077 DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
78 cl::desc("Detect scops in functions without loops"),
79 cl::Hidden, cl::init(false), cl::ZeroOrMore,
80 cl::cat(PollyCategory));
Sebastian Pop8fe6d112013-05-30 17:47:32 +000081
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000082static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000083 DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
84 cl::desc("Detect scops in regions without loops"),
85 cl::Hidden, cl::init(false), cl::ZeroOrMore,
86 cl::cat(PollyCategory));
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000087
Tobias Grosserd1e33e72015-02-19 05:31:07 +000088static cl::opt<bool> DetectUnprofitable("polly-detect-unprofitable",
89 cl::desc("Detect unprofitable scops"),
90 cl::Hidden, cl::init(false),
91 cl::ZeroOrMore, cl::cat(PollyCategory));
92
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyFunction(
94 "polly-only-func",
95 cl::desc("Only run on functions that contain a certain string"),
96 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000098
Tobias Grosser483a90d2014-07-09 10:50:10 +000099static cl::opt<std::string> OnlyRegion(
100 "polly-only-region",
101 cl::desc("Only run on certain regions (The provided identifier must "
102 "appear in the name of the region's entry block"),
103 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
104 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000105
Tobias Grosser60cd9322011-11-10 12:47:26 +0000106static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 IgnoreAliasing("polly-ignore-aliasing",
108 cl::desc("Ignore possible aliasing of the array bases"),
109 cl::Hidden, cl::init(false), cl::ZeroOrMore,
110 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000111
Johannes Doerfertb164c792014-09-18 11:17:17 +0000112bool polly::PollyUseRuntimeAliasChecks;
113static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
114 "polly-use-runtime-alias-checks",
115 cl::desc("Use runtime alias checks to resolve possible aliasing."),
116 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Tobias Grosser637bd632013-05-07 07:31:10 +0000119static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000120 ReportLevel("polly-report",
121 cl::desc("Print information about the activities of Polly"),
122 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000123
124static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000125 AllowNonAffine("polly-allow-nonaffine",
126 cl::desc("Allow non affine access functions in arrays"),
127 cl::Hidden, cl::init(false), cl::ZeroOrMore,
128 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000129
Johannes Doerfertba65c162015-02-24 11:45:21 +0000130static cl::opt<bool> AllowNonAffineSubRegions(
131 "polly-allow-nonaffine-branches",
132 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000133 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000134
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000135static cl::opt<bool>
136 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
137 cl::desc("Allow non affine conditions for loops"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
140
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000141static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
142 cl::desc("Allow unsigned expressions"),
143 cl::Hidden, cl::init(false), cl::ZeroOrMore,
144 cl::cat(PollyCategory));
145
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000146static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000147 TrackFailures("polly-detect-track-failures",
148 cl::desc("Track failure strings in detecting scop regions"),
149 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000150 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000151
Andreas Simbuerger04472402014-05-24 09:25:10 +0000152static cl::opt<bool> KeepGoing("polly-detect-keep-going",
153 cl::desc("Do not fail on the first error."),
154 cl::Hidden, cl::ZeroOrMore, cl::init(false),
155 cl::cat(PollyCategory));
156
Sebastian Pop18016682014-04-08 21:20:44 +0000157static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000158 PollyDelinearizeX("polly-delinearize",
159 cl::desc("Delinearize array access functions"),
160 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000161 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000162
Tobias Grossera1689932014-02-18 18:49:49 +0000163static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000164 VerifyScops("polly-detect-verify",
165 cl::desc("Verify the detected SCoPs after each transformation"),
166 cl::Hidden, cl::init(false), cl::ZeroOrMore,
167 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000168
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000169static cl::opt<bool, true> XPollyModelPHINodes(
170 "polly-model-phi-nodes",
171 cl::desc("Allow PHI nodes in the input [Unsafe with code-generation!]."),
172 cl::location(PollyModelPHINodes), cl::Hidden, cl::ZeroOrMore,
Tobias Grosserac60f452015-05-23 03:34:41 +0000173 cl::init(true), cl::cat(PollyCategory));
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000174
175bool polly::PollyModelPHINodes = false;
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000176bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000177bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000178StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000179
Tobias Grosser75805372011-04-29 06:27:02 +0000180//===----------------------------------------------------------------------===//
181// Statistics.
182
183STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
184
Tobias Grosser8519f892013-12-18 10:49:53 +0000185class DiagnosticScopFound : public DiagnosticInfo {
186private:
187 static int PluginDiagnosticKind;
188
189 Function &F;
190 std::string FileName;
191 unsigned EntryLine, ExitLine;
192
193public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000194 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
195 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000196 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000197 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000198
199 virtual void print(DiagnosticPrinter &DP) const;
200
201 static bool classof(const DiagnosticInfo *DI) {
202 return DI->getKind() == PluginDiagnosticKind;
203 }
204};
205
206int DiagnosticScopFound::PluginDiagnosticKind = 10;
207
Tobias Grosser8519f892013-12-18 10:49:53 +0000208void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000209 DP << "Polly detected an optimizable loop region (scop) in function '" << F
210 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000211
212 if (FileName.empty()) {
213 DP << "Scop location is unknown. Compile with debug info "
214 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000215 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000216 }
217
218 DP << FileName << ":" << EntryLine << ": Start of scop\n";
219 DP << FileName << ":" << ExitLine << ": End of scop";
220}
221
Tobias Grosser75805372011-04-29 06:27:02 +0000222//===----------------------------------------------------------------------===//
223// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000224
Johannes Doerfertb164c792014-09-18 11:17:17 +0000225ScopDetection::ScopDetection() : FunctionPass(ID) {
226 if (!PollyUseRuntimeAliasChecks)
227 return;
228
Johannes Doerfert928229f2014-09-29 17:06:29 +0000229 // Disable runtime alias checks if we ignore aliasing all together.
230 if (IgnoreAliasing) {
231 PollyUseRuntimeAliasChecks = false;
232 return;
233 }
234
Johannes Doerfertb164c792014-09-18 11:17:17 +0000235 if (AllowNonAffine) {
236 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
237 "accesses are enabled.\n");
238 PollyUseRuntimeAliasChecks = false;
239 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000240}
241
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000242template <class RR, typename... Args>
243inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
244 Args &&... Arguments) const {
245
246 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000247 RejectLog &Log = Context.Log;
248 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000249
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000250 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000251 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000252
253 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000254 DEBUG(dbgs() << "\n");
255 } else {
256 assert(!Assert && "Verification of detected scop failed");
257 }
258
259 return false;
260}
261
Tobias Grossera1689932014-02-18 18:49:49 +0000262bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
263 if (!ValidRegions.count(&R))
264 return false;
265
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000266 if (Verify) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000267 BoxedLoopsSetTy DummyBoxedLoopsSet;
Johannes Doerfertba65c162015-02-24 11:45:21 +0000268 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
269 DetectionContext Context(const_cast<Region &>(R), *AA,
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000270 DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
271 false /*verifying*/);
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000272 return isValidRegion(Context);
273 }
Tobias Grossera1689932014-02-18 18:49:49 +0000274
275 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000276}
277
Tobias Grosser4f129a62011-10-08 00:30:55 +0000278std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000279 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000280 return "";
281
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000282 // Get the first error we found. Even in keep-going mode, this is the first
283 // reason that caused the candidate to be rejected.
284 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000285
286 // This can happen when we marked a region invalid, but didn't track
287 // an error for it.
288 if (Errors.size() == 0)
289 return "";
290
291 RejectReasonPtr RR = *Errors.begin();
292 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000293}
294
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000295bool ScopDetection::addOverApproximatedRegion(Region *AR,
296 DetectionContext &Context) const {
297
298 // If we already know about Ar we can exit.
299 if (!Context.NonAffineSubRegionSet.insert(AR))
300 return true;
301
302 // All loops in the region have to be overapproximated too if there
303 // are accesses that depend on the iteration count.
304 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000305 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000306 if (AR->contains(L))
307 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000308 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000309
310 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000311}
312
Tobias Grossere602a072013-05-07 07:30:56 +0000313bool ScopDetection::isValidCFG(BasicBlock &BB,
314 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000315 Region &CurRegion = Context.CurRegion;
316
Tobias Grosser75805372011-04-29 06:27:02 +0000317 TerminatorInst *TI = BB.getTerminator();
318
319 // Return instructions are only valid if the region is the top level region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000320 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
Tobias Grosser75805372011-04-29 06:27:02 +0000321 return true;
322
323 BranchInst *Br = dyn_cast<BranchInst>(TI);
324
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000325 if (!Br)
326 return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000327
Tobias Grosser74394f02013-01-14 22:40:23 +0000328 if (Br->isUnconditional())
329 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000330
331 Value *Condition = Br->getCondition();
332
333 // UndefValue is not allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000334 if (isa<UndefValue>(Condition))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000335 return invalid<ReportUndefCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000336
337 // Only Constant and ICmpInst are allowed as condition.
Johannes Doerfertba65c162015-02-24 11:45:21 +0000338 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition))) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000339 if (!AllowNonAffineSubRegions ||
340 !addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000341 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, Br, &BB);
342 }
Tobias Grosser75805372011-04-29 06:27:02 +0000343
344 // Allow perfectly nested conditions.
345 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
346
347 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
348 // Unsigned comparisons are not allowed. They trigger overflow problems
349 // in the code generation.
350 //
351 // TODO: This is not sufficient and just hides bugs. However it does pretty
352 // well.
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000353 if (ICmp->isUnsigned() && !AllowUnsigned)
Tobias Grossera8512b12015-05-20 15:37:11 +0000354 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000355
356 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000357 if (isa<UndefValue>(ICmp->getOperand(0)) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000358 isa<UndefValue>(ICmp->getOperand(1)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000359 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000360
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000361 Loop *L = LI->getLoopFor(ICmp->getParent());
362 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
363 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000364
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000365 if (!isAffineExpr(&CurRegion, LHS, *SE) ||
Johannes Doerfertba65c162015-02-24 11:45:21 +0000366 !isAffineExpr(&CurRegion, RHS, *SE)) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000367 if (!AllowNonAffineSubRegions ||
368 !addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000369 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
370 RHS, ICmp);
371 }
Tobias Grosser75805372011-04-29 06:27:02 +0000372 }
373
374 // Allow loop exit conditions.
375 Loop *L = LI->getLoopFor(&BB);
376 if (L && L->getExitingBlock() == &BB)
377 return true;
378
379 // Allow perfectly nested conditions.
380 Region *R = RI->getRegionFor(&BB);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000381 if (R->getEntry() != &BB)
382 return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000383
384 return true;
385}
386
387bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000388 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000389 return false;
390
391 if (CI.doesNotAccessMemory())
392 return true;
393
394 Function *CalledFunction = CI.getCalledFunction();
395
396 // Indirect calls are not supported.
397 if (CalledFunction == 0)
398 return false;
399
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000400 // Check if we can handle the intrinsic call.
401 if (auto *IT = dyn_cast<IntrinsicInst>(&CI)) {
402 switch (IT->getIntrinsicID()) {
403 // Lifetime markers are supported/ignored.
404 case llvm::Intrinsic::lifetime_start:
405 case llvm::Intrinsic::lifetime_end:
406 // Invariant markers are supported/ignored.
407 case llvm::Intrinsic::invariant_start:
408 case llvm::Intrinsic::invariant_end:
409 // Some misc annotations are supported/ignored.
410 case llvm::Intrinsic::var_annotation:
411 case llvm::Intrinsic::ptr_annotation:
412 case llvm::Intrinsic::annotation:
413 case llvm::Intrinsic::donothing:
414 case llvm::Intrinsic::assume:
415 case llvm::Intrinsic::expect:
416 return true;
417 default:
418 // Other intrinsics which may access the memory are not yet supported.
419 break;
420 }
421 }
422
Tobias Grosser75805372011-04-29 06:27:02 +0000423 return false;
424}
425
Tobias Grosser458fb782014-01-28 12:58:58 +0000426bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
427 // A reference to function argument or constant value is invariant.
428 if (isa<Argument>(Val) || isa<Constant>(Val))
429 return true;
430
431 const Instruction *I = dyn_cast<Instruction>(&Val);
432 if (!I)
433 return false;
434
435 if (!Reg.contains(I))
436 return true;
437
438 if (I->mayHaveSideEffects())
439 return false;
440
441 // When Val is a Phi node, it is likely not invariant. We do not check whether
442 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
443 // invariant. Recursively checking the operators of Phi nodes would lead to
444 // infinite recursion.
445 if (isa<PHINode>(*I))
446 return false;
447
Tobias Grosser26108892014-04-02 20:18:19 +0000448 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000449 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000450 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000451
452 // When the instruction is a load instruction, check that no write to memory
453 // in the region aliases with the load.
454 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthbdb4a392015-06-04 03:49:46 +0000455 auto Loc = MemoryLocation::get(LI);
Johannes Doerfertca08c442015-02-21 16:18:28 +0000456
Tobias Grosser458fb782014-01-28 12:58:58 +0000457 // Check if any basic block in the region can modify the location pointed to
458 // by 'Loc'. If so, 'Val' is (likely) not invariant in the region.
Tobias Grosser26108892014-04-02 20:18:19 +0000459 for (const BasicBlock *BB : Reg.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000460 if (AA->canBasicBlockModify(*BB, Loc))
Tobias Grosser458fb782014-01-28 12:58:58 +0000461 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000462 }
463
464 return true;
465}
466
Sebastian Pop422e33f2014-06-03 18:16:31 +0000467MapInsnToMemAcc InsnToMemAcc;
468
Sebastian Popb57c0992014-05-12 20:24:26 +0000469bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000470 Region &CurRegion = Context.CurRegion;
471
Tobias Grosser230acc42014-09-13 14:47:55 +0000472 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000473 Value *BaseValue = BasePointer->getValue();
Tobias Grossera5c092d2015-06-04 16:03:16 +0000474 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
Tobias Grosser230acc42014-09-13 14:47:55 +0000475 bool BasePtrHasNonAffine = false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000476
477 // First step: collect parametric terms in all array references.
478 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser230acc42014-09-13 14:47:55 +0000479 for (const auto &Pair : Context.Accesses[BasePointer]) {
480 const SCEVAddRecExpr *AccessFunction =
481 dyn_cast<SCEVAddRecExpr>(Pair.second);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000482
Tobias Grosser230acc42014-09-13 14:47:55 +0000483 if (AccessFunction)
484 AccessFunction->collectParametricTerms(*SE, Terms);
485 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000486
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000487 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000488 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
489 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000490
Johannes Doerfert89830312015-05-03 16:03:01 +0000491 if (!AllowNonAffine)
492 for (const SCEV *DelinearizedSize : Shape->DelinearizedSizes)
493 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
494 invalid<ReportNonAffineAccess>(
495 Context, /*Assert=*/true, DelinearizedSize,
496 Context.Accesses[BasePointer].front().first, BaseValue);
497
Tobias Grosser230acc42014-09-13 14:47:55 +0000498 // No array shape derived.
499 if (Shape->DelinearizedSizes.empty()) {
500 if (AllowNonAffine)
501 continue;
Sebastian Pope8863b82014-05-12 19:02:02 +0000502
Tobias Grosser230acc42014-09-13 14:47:55 +0000503 for (const auto &Pair : Context.Accesses[BasePointer]) {
504 const Instruction *Insn = Pair.first;
505 const SCEV *AF = Pair.second;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000506
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000507 if (!isAffineExpr(&CurRegion, AF, *SE, BaseValue)) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000508 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
509 BaseValue);
510 if (!KeepGoing)
511 return false;
512 }
513 }
514 continue;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000515 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000516
517 // Third step: compute the access functions for each subscript.
518 //
519 // We first store the resulting memory accesses in TempMemoryAccesses. Only
520 // if the access functions for all memory accesses have been successfully
521 // delinearized we continue. Otherwise, we either report a failure or, if
522 // non-affine accesses are allowed, we drop the information. In case the
523 // information is dropped the memory accesses need to be overapproximated
524 // when translated to a polyhedral representation.
525 MapInsnToMemAcc TempMemoryAccesses;
526 for (const auto &Pair : Context.Accesses[BasePointer]) {
527 const Instruction *Insn = Pair.first;
528 const SCEVAddRecExpr *AF = dyn_cast<SCEVAddRecExpr>(Pair.second);
529 bool IsNonAffine = false;
Tobias Grossera5c092d2015-06-04 16:03:16 +0000530 TempMemoryAccesses.emplace(std::piecewise_construct,
531 std::forward_as_tuple(Insn),
532 std::forward_as_tuple(Insn, Shape));
533 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000534
535 if (!AF) {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000536 if (isAffineExpr(&CurRegion, Pair.second, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000537 Acc->DelinearizedSubscripts.push_back(Pair.second);
538 else
539 IsNonAffine = true;
540 } else {
541 AF->computeAccessFunctions(*SE, Acc->DelinearizedSubscripts,
542 Shape->DelinearizedSizes);
543 if (Acc->DelinearizedSubscripts.size() == 0)
544 IsNonAffine = true;
545 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000546 if (!isAffineExpr(&CurRegion, S, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000547 IsNonAffine = true;
548 }
549
550 // (Possibly) report non affine access
551 if (IsNonAffine) {
552 BasePtrHasNonAffine = true;
553 if (!AllowNonAffine)
Tobias Grosser021eaef2015-01-08 19:03:10 +0000554 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
555 Insn, BaseValue);
Tobias Grosser230acc42014-09-13 14:47:55 +0000556 if (!KeepGoing && !AllowNonAffine)
557 return false;
558 }
559 }
560
561 if (!BasePtrHasNonAffine)
562 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000563 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000564 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000565}
566
Tobias Grosser75805372011-04-29 06:27:02 +0000567bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
568 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000569 Region &CurRegion = Context.CurRegion;
570
Tobias Grossere5e171e2011-11-10 12:45:03 +0000571 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000572 Loop *L = LI->getLoopFor(Inst.getParent());
573 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000574 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000575 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000576
Tobias Grosserb8710b52011-11-10 12:44:50 +0000577 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
578
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000579 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000580 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000581
582 BaseValue = BasePointer->getValue();
583
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000584 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000585 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000586
Tobias Grosser458fb782014-01-28 12:58:58 +0000587 // Check that the base address of the access is invariant in the current
588 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000589 if (!isInvariant(*BaseValue, CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000590 // Verification of this property is difficult as the independent blocks
591 // pass may introduce aliasing that we did not have when running the
592 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000593 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
594 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000595
Tobias Grosserb8710b52011-11-10 12:44:50 +0000596 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
597
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000598 const SCEV *Size = SE->getElementSize(&Inst);
599 if (Context.ElementSize.count(BasePointer)) {
600 if (Context.ElementSize[BasePointer] != Size)
601 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
602 &Inst, BaseValue);
603 } else {
604 Context.ElementSize[BasePointer] = Size;
605 }
606
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000607 bool isVariantInNonAffineLoop = false;
608 SetVector<const Loop *> Loops;
609 findLoops(AccessFunction, Loops);
610 for (const Loop *L : Loops)
611 if (Context.BoxedLoopsSet.count(L))
612 isVariantInNonAffineLoop = true;
613
614 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000615 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000616
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000617 if (!isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000618 Context.NonAffineAccesses.insert(BasePointer);
619 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000620 if (isVariantInNonAffineLoop ||
621 !isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000622 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000623 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000624 }
Tobias Grosser75805372011-04-29 06:27:02 +0000625
626 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
627 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000628 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
629 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000630
Tobias Grosser1eedb672014-09-24 21:04:29 +0000631 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000632 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000633
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000634 // Check if the base pointer of the memory access does alias with
635 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000636 AAMDNodes AATags;
637 Inst.getAAMetadata(AATags);
638 AliasSet &AS = Context.AST.getAliasSetForPointer(
639 BaseValue, AliasAnalysis::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000640
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000641 // INVALID triggers an assertion in verifying mode, if it detects that a
642 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
643 // a pass that stated it would preserve the SCoPs. We disable this check as
644 // the independent blocks pass may create memory references which seem to
645 // alias, if -basicaa is not available. They actually do not, but as we can
646 // not proof this without -basicaa we would fail. We disable this check to
647 // not cause irrelevant verification failures.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000648 if (!AS.isMustAlias()) {
649 if (PollyUseRuntimeAliasChecks) {
650 bool CanBuildRunTimeCheck = true;
651 // The run-time alias check places code that involves the base pointer at
652 // the beginning of the SCoP. This breaks if the base pointer is defined
653 // inside the scop. Hence, we can only create a run-time check if we are
654 // sure the base pointer is not an instruction defined inside the scop.
655 for (const auto &Ptr : AS) {
656 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000657 if (Inst && CurRegion.contains(Inst)) {
Tobias Grosser1eedb672014-09-24 21:04:29 +0000658 CanBuildRunTimeCheck = false;
659 break;
660 }
661 }
662
663 if (CanBuildRunTimeCheck)
664 return true;
665 }
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000666 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000667 }
Tobias Grosser75805372011-04-29 06:27:02 +0000668
669 return true;
670}
671
Tobias Grosser75805372011-04-29 06:27:02 +0000672bool ScopDetection::isValidInstruction(Instruction &Inst,
673 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000674 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000675 if (!PollyModelPHINodes && !canSynthesize(PN, LI, SE, &Context.CurRegion)) {
Tobias Grosser683b8e42014-11-30 14:33:31 +0000676 return invalid<ReportPhiNodeRefInRegion>(Context, /*Assert=*/true, &Inst);
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000677 }
Tobias Grosser75805372011-04-29 06:27:02 +0000678
Tobias Grosser75805372011-04-29 06:27:02 +0000679 // We only check the call instruction but not invoke instruction.
680 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
681 if (isValidCallInst(*CI))
682 return true;
683
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000684 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000685 }
686
687 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000688 if (!isa<AllocaInst>(Inst))
689 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000690
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000691 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000692 }
693
694 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000695 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
696 Context.hasStores |= isa<StoreInst>(Inst);
697 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000698 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000699 }
Tobias Grosser75805372011-04-29 06:27:02 +0000700
701 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000702 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000703}
704
Tobias Grosser75805372011-04-29 06:27:02 +0000705bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000706 // Is the loop count affine?
707 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000708 if (isAffineExpr(&Context.CurRegion, LoopCount, *SE)) {
709 Context.hasAffineLoops = true;
Johannes Doerfertba65c162015-02-24 11:45:21 +0000710 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000711 }
712
713 if (AllowNonAffineSubRegions) {
714 Region *R = RI->getRegionFor(L->getHeader());
715 if (R->contains(L))
716 if (addOverApproximatedRegion(R, Context))
717 return true;
718 }
Tobias Grosser75805372011-04-29 06:27:02 +0000719
Johannes Doerfertba65c162015-02-24 11:45:21 +0000720 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000721}
722
723Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000724 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000725 std::unique_ptr<Region> LastValidRegion;
726 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000727
728 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
729
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000730 while (ExpandedRegion) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000731 DetectionContext Context(
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000732 *ExpandedRegion, *AA, NonAffineSubRegionMap[ExpandedRegion.get()],
733 BoxedLoopsMap[ExpandedRegion.get()], false /* verifying */);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000734 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000735 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000736
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000737 // Check the exit first (cheap)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000738 if (isValidExit(Context) && !Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000739 // If the exit is valid check all blocks
740 // - if true, a valid region was found => store it + keep expanding
741 // - if false, .tbd. => stop (should this really end the loop?)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000742 if (!allBlocksValid(Context) || Context.Log.hasErrors())
743 break;
744
Tobias Grosserd7e58642013-04-10 06:55:45 +0000745 // Store this region, because it is the greatest valid (encountered so
746 // far).
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000747 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000748
749 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000750 ExpandedRegion =
751 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000752
753 } else {
754 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000755 ExpandedRegion =
756 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000757 }
Tobias Grosser75805372011-04-29 06:27:02 +0000758 }
759
Tobias Grosser378a9f22013-11-16 19:34:11 +0000760 DEBUG({
761 if (LastValidRegion)
762 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
763 else
764 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
765 });
Tobias Grosser75805372011-04-29 06:27:02 +0000766
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000767 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +0000768}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000769static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000770 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000771 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000772 return false;
773
774 return true;
775}
Tobias Grosser75805372011-04-29 06:27:02 +0000776
Tobias Grosser28a70c52014-01-29 19:05:30 +0000777// Remove all direct and indirect children of region R from the region set Regs,
778// but do not recurse further if the first child has been found.
779//
780// Return the number of regions erased from Regs.
David Peixotto8da2b932014-10-22 20:39:07 +0000781static unsigned eraseAllChildren(ScopDetection::RegionSet &Regs,
David Blaikieb035f6d2014-04-15 18:45:27 +0000782 const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000783 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000784 for (auto &SubRegion : R) {
David Peixotto8da2b932014-10-22 20:39:07 +0000785 if (Regs.count(SubRegion.get())) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000786 ++Count;
David Peixotto8da2b932014-10-22 20:39:07 +0000787 Regs.remove(SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000788 } else {
David Blaikieb035f6d2014-04-15 18:45:27 +0000789 Count += eraseAllChildren(Regs, *SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000790 }
791 }
792 return Count;
793}
794
Tobias Grosser75805372011-04-29 06:27:02 +0000795void ScopDetection::findScops(Region &R) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000796 DetectionContext Context(R, *AA, NonAffineSubRegionMap[&R], BoxedLoopsMap[&R],
Johannes Doerfertba65c162015-02-24 11:45:21 +0000797 false /*verifying*/);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000798
799 bool RegionIsValid = false;
800 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
801 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
802 else
803 RegionIsValid = isValidRegion(Context);
804
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000805 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +0000806
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000807 if (PollyTrackFailures && HasErrors)
808 RejectLogs.insert(std::make_pair(&R, Context.Log));
809
810 if (!HasErrors) {
Tobias Grosser75805372011-04-29 06:27:02 +0000811 ++ValidRegion;
812 ValidRegions.insert(&R);
813 return;
814 }
815
David Blaikieb035f6d2014-04-15 18:45:27 +0000816 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000817 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000818
819 // Try to expand regions.
820 //
821 // As the region tree normally only contains canonical regions, non canonical
822 // regions that form a Scop are not found. Therefore, those non canonical
823 // regions are checked by expanding the canonical ones.
824
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000825 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000826
David Blaikieb035f6d2014-04-15 18:45:27 +0000827 for (auto &SubRegion : R)
828 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000829
Tobias Grosser26108892014-04-02 20:18:19 +0000830 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000831 // Skip regions that had errors.
832 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
833 if (HadErrors)
834 continue;
835
Tobias Grosser75805372011-04-29 06:27:02 +0000836 // Skip invalid regions. Regions may become invalid, if they are element of
837 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +0000838 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +0000839 continue;
840
841 Region *ExpandedR = expandRegion(*CurrentRegion);
842
843 if (!ExpandedR)
844 continue;
845
846 R.addSubRegion(ExpandedR, true);
847 ValidRegions.insert(ExpandedR);
David Peixotto8da2b932014-10-22 20:39:07 +0000848 ValidRegions.remove(CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000849
Tobias Grosser28a70c52014-01-29 19:05:30 +0000850 // Erase all (direct and indirect) children of ExpandedR from the valid
851 // regions and update the number of valid regions.
David Blaikieb035f6d2014-04-15 18:45:27 +0000852 ValidRegion -= eraseAllChildren(ValidRegions, *ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000853 }
854}
855
856bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000857 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000858
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000859 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000860 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000861 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000862 return false;
863 }
864
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000865 for (BasicBlock *BB : CurRegion.blocks())
Andreas Simbuerger04472402014-05-24 09:25:10 +0000866 if (!isValidCFG(*BB, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000867 return false;
868
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000869 for (BasicBlock *BB : CurRegion.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000870 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000871 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000872 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000873
Sebastian Pope8863b82014-05-12 19:02:02 +0000874 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000875 return false;
876
Tobias Grosser75805372011-04-29 06:27:02 +0000877 return true;
878}
879
880bool ScopDetection::isValidExit(DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000881
882 // PHI nodes are not allowed in the exit basic block.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000883 if (BasicBlock *Exit = Context.CurRegion.getExit()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000884 BasicBlock::iterator I = Exit->begin();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000885 if (I != Exit->end() && isa<PHINode>(*I))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000886 return invalid<ReportPHIinExit>(Context, /*Assert=*/true, I);
Tobias Grosser75805372011-04-29 06:27:02 +0000887 }
888
889 return true;
890}
891
892bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000893 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000894
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000895 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +0000896
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000897 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +0000898 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000899 return false;
900 }
901
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000902 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +0000903 DEBUG({
904 dbgs() << "Region entry does not match -polly-region-only";
905 dbgs() << "\n";
906 });
907 return false;
908 }
909
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000910 if (!CurRegion.getEnteringBlock()) {
911 BasicBlock *entry = CurRegion.getEntry();
Sebastian Pop9d632342013-06-11 22:20:40 +0000912 Loop *L = LI->getLoopFor(entry);
913
914 if (L) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000915 if (!L->isLoopSimplifyForm())
916 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Sebastian Pop9d632342013-06-11 22:20:40 +0000917
918 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
919 ++PI) {
920 // Region entering edges come from the same loop but outside the region
921 // are not allowed.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000922 if (L->contains(*PI) && !CurRegion.contains(*PI))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000923 return invalid<ReportIndEdge>(Context, /*Assert=*/true, *PI);
Sebastian Pop9d632342013-06-11 22:20:40 +0000924 }
925 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000926 }
927
Tobias Grosserd654c252012-04-10 18:12:19 +0000928 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000929 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000930 if (CurRegion.getEntry() ==
931 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
932 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +0000933
Hongbin Zheng94868e62012-04-07 12:29:17 +0000934 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000935 return false;
936
Hongbin Zheng94868e62012-04-07 12:29:17 +0000937 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000938 return false;
939
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000940 // We can probably not do a lot on scops that only write or only read
941 // data.
942 if (!DetectUnprofitable && (!Context.hasStores || !Context.hasLoads))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000943 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000944
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000945 // Check if there was at least one non-overapproximated loop in the region or
946 // we allow regions without loops.
947 if (!DetectRegionsWithoutLoops && !Context.hasAffineLoops)
948 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
949
Tobias Grosser75805372011-04-29 06:27:02 +0000950 DEBUG(dbgs() << "OK\n");
951 return true;
952}
953
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000954void ScopDetection::markFunctionAsInvalid(Function *F) const {
955 F->addFnAttr(PollySkipFnAttr);
956}
957
Tobias Grosser75805372011-04-29 06:27:02 +0000958bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000959 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +0000960}
961
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000962void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +0000963 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +0000964 unsigned LineEntry, LineExit;
965 std::string FileName;
966
Tobias Grosser00dc3092014-03-02 12:02:46 +0000967 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +0000968 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
969 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +0000970 }
971}
972
Daniel Jasper8a1dea02014-10-27 19:45:31 +0000973void ScopDetection::emitMissedRemarksForValidRegions(
974 const Function &F, const RegionSet &ValidRegions) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000975 for (const Region *R : ValidRegions) {
976 const Region *Parent = R->getParent();
977 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
978 emitRejectionRemarks(F, RejectLogs.at(Parent));
979 }
980}
981
982void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
983 const Region *R) {
984 for (const std::unique_ptr<Region> &Child : *R) {
985 bool IsValid = ValidRegions.count(Child.get());
986 if (IsValid)
987 continue;
988
989 bool IsLeaf = Child->begin() == Child->end();
990 if (!IsLeaf)
991 emitMissedRemarksForLeaves(F, Child.get());
992 else {
993 if (RejectLogs.count(Child.get())) {
994 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
995 }
996 }
997 }
998}
999
Tobias Grosser75805372011-04-29 06:27:02 +00001000bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001001 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001002 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001003 if (!DetectScopsWithoutLoops && LI->empty())
1004 return false;
1005
Tobias Grosser75805372011-04-29 06:27:02 +00001006 AA = &getAnalysis<AliasAnalysis>();
1007 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001008 Region *TopRegion = RI->getTopLevelRegion();
1009
Tobias Grosser2ff87232011-10-23 11:17:06 +00001010 releaseMemory();
1011
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001012 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001013 return false;
1014
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001015 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001016 return false;
1017
1018 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001019
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001020 // Only makes sense when we tracked errors.
1021 if (PollyTrackFailures) {
1022 emitMissedRemarksForValidRegions(F, ValidRegions);
1023 emitMissedRemarksForLeaves(F, TopRegion);
1024 }
1025
1026 for (const Region *R : ValidRegions)
1027 emitValidRemarks(F, R);
1028
Johannes Doerferta05214f2014-10-15 23:24:28 +00001029 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001030 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001031
Tobias Grosser75805372011-04-29 06:27:02 +00001032 return false;
1033}
1034
Johannes Doerfertba65c162015-02-24 11:45:21 +00001035bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1036 const Region *ScopR) const {
1037 return NonAffineSubRegionMap.lookup(ScopR).count(SubR);
1038}
1039
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001040const ScopDetection::BoxedLoopsSetTy *
1041ScopDetection::getBoxedLoops(const Region *R) const {
1042 auto BLMIt = BoxedLoopsMap.find(R);
1043 if (BLMIt == BoxedLoopsMap.end())
1044 return nullptr;
1045 return &BLMIt->second;
1046}
1047
Tobias Grosser75805372011-04-29 06:27:02 +00001048void polly::ScopDetection::verifyRegion(const Region &R) const {
1049 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001050
1051 BoxedLoopsSetTy DummyBoxedLoopsSet;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001052 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
1053 DetectionContext Context(const_cast<Region &>(R), *AA,
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001054 DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
1055 true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001056 isValidRegion(Context);
1057}
1058
1059void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001060 if (!VerifyScops)
1061 return;
1062
Tobias Grosser26108892014-04-02 20:18:19 +00001063 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001064 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001065}
1066
1067void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001068 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001069 AU.addRequired<ScalarEvolution>();
1070 // We also need AA and RegionInfo when we are verifying analysis.
1071 AU.addRequiredTransitive<AliasAnalysis>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001072 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001073 AU.setPreservesAll();
1074}
1075
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001076void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001077 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001078 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001079
1080 OS << "\n";
1081}
1082
1083void ScopDetection::releaseMemory() {
1084 ValidRegions.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001085 RejectLogs.clear();
Johannes Doerfertba65c162015-02-24 11:45:21 +00001086 NonAffineSubRegionMap.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001087 InsnToMemAcc.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001088
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001089 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001090}
1091
1092char ScopDetection::ID = 0;
1093
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001094Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1095
Tobias Grosser73600b82011-10-08 00:30:40 +00001096INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1097 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001098 false);
1099INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00001100INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001101INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001102INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +00001103INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1104 "Polly - Detect static control parts (SCoPs)", false, false)