blob: 2ceb3fa62dcc5e1280c0f9fd936dbd2650ea9c24 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- ScopDetection.cpp - Detect Scops --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
16// Every Scop fullfills these restrictions:
17//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000050#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000057#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000059#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000060#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000061#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000062#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000064#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000065#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000066#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000068#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000069
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosserc1a269b2015-12-21 21:00:43 +000075// This option is set to a very high value, as analyzing such loops increases
76// compile time on several cases. For experiments that enable this option,
77// a value of around 40 has been working to avoid run-time regressions with
78// Polly while still exposing interesting optimization opportunities.
79static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80 "polly-detect-profitability-min-per-loop-insts",
81 cl::desc("The minimal number of per-loop instructions before a single loop "
82 "region is considered profitable"),
83 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84
Tobias Grosser575aca82015-10-06 16:10:29 +000085bool polly::PollyProcessUnprofitable;
86static cl::opt<bool, true> XPollyProcessUnprofitable(
87 "polly-process-unprofitable",
88 cl::desc(
89 "Process scops that are unlikely to benefit from Polly optimizations."),
90 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000092
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyFunction(
94 "polly-only-func",
95 cl::desc("Only run on functions that contain a certain string"),
96 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000098
Tobias Grosser483a90d2014-07-09 10:50:10 +000099static cl::opt<std::string> OnlyRegion(
100 "polly-only-region",
101 cl::desc("Only run on certain regions (The provided identifier must "
102 "appear in the name of the region's entry block"),
103 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
104 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000105
Tobias Grosser60cd9322011-11-10 12:47:26 +0000106static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 IgnoreAliasing("polly-ignore-aliasing",
108 cl::desc("Ignore possible aliasing of the array bases"),
109 cl::Hidden, cl::init(false), cl::ZeroOrMore,
110 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000111
Johannes Doerfertb164c792014-09-18 11:17:17 +0000112bool polly::PollyUseRuntimeAliasChecks;
113static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
114 "polly-use-runtime-alias-checks",
115 cl::desc("Use runtime alias checks to resolve possible aliasing."),
116 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Tobias Grosser637bd632013-05-07 07:31:10 +0000119static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000120 ReportLevel("polly-report",
121 cl::desc("Print information about the activities of Polly"),
122 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000123
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000124static cl::opt<bool> AllowDifferentTypes(
125 "polly-allow-differing-element-types",
126 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000127 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000128
Tobias Grosser531891e2012-11-01 16:45:20 +0000129static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000130 AllowNonAffine("polly-allow-nonaffine",
131 cl::desc("Allow non affine access functions in arrays"),
132 cl::Hidden, cl::init(false), cl::ZeroOrMore,
133 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000134
Tobias Grosser898a6362016-03-23 06:40:15 +0000135static cl::opt<bool>
136 AllowModrefCall("polly-allow-modref-calls",
137 cl::desc("Allow functions with known modref behavior"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
140
Johannes Doerfertba65c162015-02-24 11:45:21 +0000141static cl::opt<bool> AllowNonAffineSubRegions(
142 "polly-allow-nonaffine-branches",
143 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000144 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000145
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000146static cl::opt<bool>
147 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
148 cl::desc("Allow non affine conditions for loops"),
149 cl::Hidden, cl::init(false), cl::ZeroOrMore,
150 cl::cat(PollyCategory));
151
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000152static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
153 cl::desc("Allow unsigned expressions"),
154 cl::Hidden, cl::init(false), cl::ZeroOrMore,
155 cl::cat(PollyCategory));
156
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000157static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000158 TrackFailures("polly-detect-track-failures",
159 cl::desc("Track failure strings in detecting scop regions"),
160 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000161 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000162
Andreas Simbuerger04472402014-05-24 09:25:10 +0000163static cl::opt<bool> KeepGoing("polly-detect-keep-going",
164 cl::desc("Do not fail on the first error."),
165 cl::Hidden, cl::ZeroOrMore, cl::init(false),
166 cl::cat(PollyCategory));
167
Sebastian Pop18016682014-04-08 21:20:44 +0000168static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000169 PollyDelinearizeX("polly-delinearize",
170 cl::desc("Delinearize array access functions"),
171 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000172 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000173
Tobias Grossera1689932014-02-18 18:49:49 +0000174static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000175 VerifyScops("polly-detect-verify",
176 cl::desc("Verify the detected SCoPs after each transformation"),
177 cl::Hidden, cl::init(false), cl::ZeroOrMore,
178 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000179
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000180bool polly::PollyInvariantLoadHoisting;
181static cl::opt<bool, true> XPollyInvariantLoadHoisting(
182 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
183 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
184 cl::init(true), cl::cat(PollyCategory));
185
Johannes Doerferte526de52015-09-21 19:10:11 +0000186/// @brief The minimal trip count under which loops are considered unprofitable.
187static const unsigned MIN_LOOP_TRIP_COUNT = 8;
188
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000189bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000190bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000191StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000192
Tobias Grosser75805372011-04-29 06:27:02 +0000193//===----------------------------------------------------------------------===//
194// Statistics.
195
196STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
197
Tobias Grosser8519f892013-12-18 10:49:53 +0000198class DiagnosticScopFound : public DiagnosticInfo {
199private:
200 static int PluginDiagnosticKind;
201
202 Function &F;
203 std::string FileName;
204 unsigned EntryLine, ExitLine;
205
206public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000207 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
208 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000209 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000210 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000211
212 virtual void print(DiagnosticPrinter &DP) const;
213
214 static bool classof(const DiagnosticInfo *DI) {
215 return DI->getKind() == PluginDiagnosticKind;
216 }
217};
218
219int DiagnosticScopFound::PluginDiagnosticKind = 10;
220
Tobias Grosser8519f892013-12-18 10:49:53 +0000221void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000222 DP << "Polly detected an optimizable loop region (scop) in function '" << F
223 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000224
225 if (FileName.empty()) {
226 DP << "Scop location is unknown. Compile with debug info "
227 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000228 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000229 }
230
231 DP << FileName << ":" << EntryLine << ": Start of scop\n";
232 DP << FileName << ":" << ExitLine << ": End of scop";
233}
234
Tobias Grosser75805372011-04-29 06:27:02 +0000235//===----------------------------------------------------------------------===//
236// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000237
Johannes Doerfertb164c792014-09-18 11:17:17 +0000238ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000239 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000240 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000241 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000242}
243
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000244template <class RR, typename... Args>
245inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
246 Args &&... Arguments) const {
247
248 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000249 RejectLog &Log = Context.Log;
250 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000251
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000252 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000253 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000254
255 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000256 DEBUG(dbgs() << "\n");
257 } else {
258 assert(!Assert && "Verification of detected scop failed");
259 }
260
261 return false;
262}
263
Tobias Grossera1689932014-02-18 18:49:49 +0000264bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
265 if (!ValidRegions.count(&R))
266 return false;
267
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000268 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000269 DetectionContextMap.erase(&R);
270 const auto &It = DetectionContextMap.insert(
271 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
272 false /*verifying*/)));
273 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000274 return isValidRegion(Context);
275 }
Tobias Grossera1689932014-02-18 18:49:49 +0000276
277 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000278}
279
Tobias Grosser4f129a62011-10-08 00:30:55 +0000280std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000281 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000282 return "";
283
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000284 // Get the first error we found. Even in keep-going mode, this is the first
285 // reason that caused the candidate to be rejected.
286 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000287
288 // This can happen when we marked a region invalid, but didn't track
289 // an error for it.
290 if (Errors.size() == 0)
291 return "";
292
293 RejectReasonPtr RR = *Errors.begin();
294 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000295}
296
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000297bool ScopDetection::addOverApproximatedRegion(Region *AR,
298 DetectionContext &Context) const {
299
300 // If we already know about Ar we can exit.
301 if (!Context.NonAffineSubRegionSet.insert(AR))
302 return true;
303
304 // All loops in the region have to be overapproximated too if there
305 // are accesses that depend on the iteration count.
306 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000307 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000308 if (AR->contains(L))
309 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000310 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000311
312 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000313}
314
Johannes Doerfert09e36972015-10-07 20:17:36 +0000315bool ScopDetection::onlyValidRequiredInvariantLoads(
316 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
317 Region &CurRegion = Context.CurRegion;
318
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000319 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
320 return false;
321
Johannes Doerfert09e36972015-10-07 20:17:36 +0000322 for (LoadInst *Load : RequiredILS)
323 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
324 return false;
325
326 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
327
328 return true;
329}
330
Michael Kruse09eb4452016-03-03 22:10:47 +0000331bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
332 DetectionContext &Context,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000333 Value *BaseAddress) const {
334
335 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +0000336 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, BaseAddress, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000337 return false;
338
339 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
340 return false;
341
342 return true;
343}
344
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000345bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000346 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000347 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000348 Loop *L = LI->getLoopFor(&BB);
349 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000350
Michael Kruse09eb4452016-03-03 22:10:47 +0000351 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000352 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000353
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000354 if (!IsLoopBranch && AllowNonAffineSubRegions &&
355 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
356 return true;
357
358 if (IsLoopBranch)
359 return false;
360
361 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
362 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000363}
364
365bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000366 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000367 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000368
369 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
370 auto Opcode = BinOp->getOpcode();
371 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
372 Value *Op0 = BinOp->getOperand(0);
373 Value *Op1 = BinOp->getOperand(1);
374 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
375 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
376 }
377 }
378
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000379 // Non constant conditions of branches need to be ICmpInst.
380 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000381 if (!IsLoopBranch && AllowNonAffineSubRegions &&
382 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
383 return true;
384 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000385 }
Tobias Grosser75805372011-04-29 06:27:02 +0000386
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000387 ICmpInst *ICmp = cast<ICmpInst>(Condition);
388 // Unsigned comparisons are not allowed. They trigger overflow problems
389 // in the code generation.
390 //
391 // TODO: This is not sufficient and just hides bugs. However it does pretty
392 // well.
393 if (ICmp->isUnsigned() && !AllowUnsigned)
394 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000395
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000396 // Are both operands of the ICmp affine?
397 if (isa<UndefValue>(ICmp->getOperand(0)) ||
398 isa<UndefValue>(ICmp->getOperand(1)))
399 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000400
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000401 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
402 // for arbitrary pointer expressions at the moment. Until
403 // this is fixed we disallow pointer expressions completely.
404 if (ICmp->getOperand(0)->getType()->isPointerTy())
405 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000406
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000407 Loop *L = LI->getLoopFor(ICmp->getParent());
408 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
409 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000410
Michael Kruse09eb4452016-03-03 22:10:47 +0000411 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000412 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000413
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000414 if (!IsLoopBranch && AllowNonAffineSubRegions &&
415 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
416 return true;
417
418 if (IsLoopBranch)
419 return false;
420
421 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
422 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000423}
424
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000425bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000426 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000427 DetectionContext &Context) const {
428 Region &CurRegion = Context.CurRegion;
429
430 TerminatorInst *TI = BB.getTerminator();
431
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000432 if (AllowUnreachable && isa<UnreachableInst>(TI))
433 return true;
434
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000435 // Return instructions are only valid if the region is the top level region.
436 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
437 return true;
438
439 Value *Condition = getConditionFromTerminator(TI);
440
441 if (!Condition)
442 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
443
444 // UndefValue is not allowed as condition.
445 if (isa<UndefValue>(Condition))
446 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
447
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000448 // Constant integer conditions are always affine.
449 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000450 return true;
451
452 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000453 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000454
455 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
456 assert(SI && "Terminator was neither branch nor switch");
457
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000458 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000459}
460
Johannes Doerfertcea61932016-02-21 19:13:19 +0000461bool ScopDetection::isValidCallInst(CallInst &CI,
462 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000463 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000464 return false;
465
466 if (CI.doesNotAccessMemory())
467 return true;
468
Johannes Doerfertcea61932016-02-21 19:13:19 +0000469 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000470 if (isValidIntrinsicInst(*II, Context))
471 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000472
Tobias Grosser75805372011-04-29 06:27:02 +0000473 Function *CalledFunction = CI.getCalledFunction();
474
475 // Indirect calls are not supported.
476 if (CalledFunction == 0)
477 return false;
478
Tobias Grosser898a6362016-03-23 06:40:15 +0000479 if (AllowModrefCall) {
480 switch (AA->getModRefBehavior(CalledFunction)) {
481 case llvm::FMRB_UnknownModRefBehavior:
482 return false;
483 case llvm::FMRB_DoesNotAccessMemory:
484 case llvm::FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000485 // Implicitly disable delinearization since we have an unknown
486 // accesses with an unknown access function.
487 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000488 Context.AST.add(&CI);
489 return true;
490 case llvm::FMRB_OnlyReadsArgumentPointees:
491 case llvm::FMRB_OnlyAccessesArgumentPointees:
492 for (const auto &Arg : CI.arg_operands()) {
493 if (!Arg->getType()->isPointerTy())
494 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000495
Tobias Grosser898a6362016-03-23 06:40:15 +0000496 // Bail if a pointer argument has a base address not known to
497 // ScalarEvolution. Note that a zero pointer is acceptable.
498 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
499 if (ArgSCEV->isZero())
500 continue;
501
502 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
503 if (!BP)
504 return false;
505
506 // Implicitly disable delinearization since we have an unknown
507 // accesses with an unknown access function.
508 Context.HasUnknownAccess = true;
509 }
510
511 Context.AST.add(&CI);
512 return true;
513 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000514 }
515
Johannes Doerfertcea61932016-02-21 19:13:19 +0000516 return false;
517}
518
519bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
520 DetectionContext &Context) const {
521 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000522 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000523
Johannes Doerfertcea61932016-02-21 19:13:19 +0000524 // The closest loop surrounding the call instruction.
525 Loop *L = LI->getLoopFor(II.getParent());
526
527 // The access function and base pointer for memory intrinsics.
528 const SCEV *AF;
529 const SCEVUnknown *BP;
530
531 switch (II.getIntrinsicID()) {
532 // Memory intrinsics that can be represented are supported.
533 case llvm::Intrinsic::memmove:
534 case llvm::Intrinsic::memcpy:
535 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
536 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
537 // Bail if the source pointer is not valid.
538 if (!isValidAccess(&II, AF, BP, Context))
539 return false;
540 // Fall through
541 case llvm::Intrinsic::memset:
542 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
543 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
544 // Bail if the destination pointer is not valid.
545 if (!isValidAccess(&II, AF, BP, Context))
546 return false;
547
548 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000549 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000550 Context))
551 return false;
552
553 return true;
554 default:
555 break;
556 }
557
Tobias Grosser75805372011-04-29 06:27:02 +0000558 return false;
559}
560
Tobias Grosser458fb782014-01-28 12:58:58 +0000561bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
562 // A reference to function argument or constant value is invariant.
563 if (isa<Argument>(Val) || isa<Constant>(Val))
564 return true;
565
566 const Instruction *I = dyn_cast<Instruction>(&Val);
567 if (!I)
568 return false;
569
570 if (!Reg.contains(I))
571 return true;
572
573 if (I->mayHaveSideEffects())
574 return false;
575
576 // When Val is a Phi node, it is likely not invariant. We do not check whether
577 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000578 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000579 if (isa<PHINode>(*I))
580 return false;
581
Tobias Grosser26108892014-04-02 20:18:19 +0000582 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000583 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000584 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000585
Tobias Grosser458fb782014-01-28 12:58:58 +0000586 return true;
587}
588
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000589/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
590/// register the '...' components.
591///
592/// Array access expressions as they are generated by gfortran contain smax(0,
593/// size) expressions that confuse the 'normal' delinearization algorithm.
594/// However, if we extract such expressions before the normal delinearization
595/// takes place they can actually help to identify array size expressions in
596/// fortran accesses. For the subsequently following delinearization the smax(0,
597/// size) component can be replaced by just 'size'. This is correct as we will
598/// always add and verify the assumption that for all subscript expressions
599/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
600/// that 0 <= size, which means smax(0, size) == size.
601struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
602public:
603 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
604 std::vector<const SCEV *> *Terms = nullptr) {
605
606 SCEVRemoveMax D(SE, Terms);
607 return D.visit(Expr);
608 }
609
610 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
611 : SE(SE), Terms(Terms) {}
612
613 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
614
615 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
616 return Expr;
617 }
618
619 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
620 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
621 }
622
623 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
624
625 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000626 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000627 auto Res = visit(Expr->getOperand(1));
628 if (Terms)
629 (*Terms).push_back(Res);
630 return Res;
631 }
632
633 return Expr;
634 }
635
Roman Gareev8aa43752015-12-17 20:37:17 +0000636 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000637
638 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
639
640 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
641 return Expr;
642 }
643
644 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
645
646 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
647 SmallVector<const SCEV *, 5> NewOps;
648 for (const SCEV *Op : Expr->operands())
649 NewOps.push_back(visit(Op));
650
651 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
652 }
653
654 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
655 SmallVector<const SCEV *, 5> NewOps;
656 for (const SCEV *Op : Expr->operands())
657 NewOps.push_back(visit(Op));
658
659 return SE.getAddExpr(NewOps);
660 }
661
662 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
663 SmallVector<const SCEV *, 5> NewOps;
664 for (const SCEV *Op : Expr->operands())
665 NewOps.push_back(visit(Op));
666
667 return SE.getMulExpr(NewOps);
668 }
669
670private:
671 ScalarEvolution &SE;
672 std::vector<const SCEV *> *Terms;
673};
674
Tobias Grosserd68ba422015-11-24 05:00:36 +0000675SmallVector<const SCEV *, 4>
676ScopDetection::getDelinearizationTerms(DetectionContext &Context,
677 const SCEVUnknown *BasePointer) const {
678 SmallVector<const SCEV *, 4> Terms;
679 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000680 std::vector<const SCEV *> MaxTerms;
681 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
682 if (MaxTerms.size() > 0) {
683 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
684 continue;
685 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000686 // In case the outermost expression is a plain add, we check if any of its
687 // terms has the form 4 * %inst * %param * %param ..., aka a term that
688 // contains a product between a parameter and an instruction that is
689 // inside the scop. Such instructions, if allowed at all, are instructions
690 // SCEV can not represent, but Polly is still looking through. As a
691 // result, these instructions can depend on induction variables and are
692 // most likely no array sizes. However, terms that are multiplied with
693 // them are likely candidates for array sizes.
694 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
695 for (auto Op : AF->operands()) {
696 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
697 SE->collectParametricTerms(AF2, Terms);
698 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
699 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000700
Tobias Grosserd68ba422015-11-24 05:00:36 +0000701 for (auto *MulOp : AF2->operands()) {
702 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
703 Operands.push_back(Const);
704 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
705 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
706 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000707 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000708
709 } else {
710 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000711 }
712 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000713 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000714 if (Operands.size())
715 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000716 }
717 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000718 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000719 if (Terms.empty())
720 SE->collectParametricTerms(Pair.second, Terms);
721 }
722 return Terms;
723}
Sebastian Pope8863b82014-05-12 19:02:02 +0000724
Tobias Grosserd68ba422015-11-24 05:00:36 +0000725bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
726 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000727 const SCEVUnknown *BasePointer,
728 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000729 Value *BaseValue = BasePointer->getValue();
730 Region &CurRegion = Context.CurRegion;
731 for (const SCEV *DelinearizedSize : Sizes) {
Michael Kruse09eb4452016-03-03 22:10:47 +0000732 if (!isAffine(DelinearizedSize, Scope, Context, nullptr)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000733 Sizes.clear();
734 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000735 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000736 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
737 auto *V = dyn_cast<Value>(Unknown->getValue());
738 if (auto *Load = dyn_cast<LoadInst>(V)) {
739 if (Context.CurRegion.contains(Load) &&
740 isHoistableLoad(Load, CurRegion, *LI, *SE))
741 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000742 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000743 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000744 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000745 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000746 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000747 Context, /*Assert=*/true, DelinearizedSize,
748 Context.Accesses[BasePointer].front().first, BaseValue);
749 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000750
Tobias Grosserd68ba422015-11-24 05:00:36 +0000751 // No array shape derived.
752 if (Sizes.empty()) {
753 if (AllowNonAffine)
754 return true;
755
Tobias Grosser230acc42014-09-13 14:47:55 +0000756 for (const auto &Pair : Context.Accesses[BasePointer]) {
757 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000758 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000759
Michael Kruse09eb4452016-03-03 22:10:47 +0000760 if (!isAffine(AF, Scope, Context, BaseValue)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000761 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
762 BaseValue);
763 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000764 return false;
765 }
766 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000767 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000768 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000769 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000770}
771
Tobias Grosserd68ba422015-11-24 05:00:36 +0000772// We first store the resulting memory accesses in TempMemoryAccesses. Only
773// if the access functions for all memory accesses have been successfully
774// delinearized we continue. Otherwise, we either report a failure or, if
775// non-affine accesses are allowed, we drop the information. In case the
776// information is dropped the memory accesses need to be overapproximated
777// when translated to a polyhedral representation.
778bool ScopDetection::computeAccessFunctions(
779 DetectionContext &Context, const SCEVUnknown *BasePointer,
780 std::shared_ptr<ArrayShape> Shape) const {
781 Value *BaseValue = BasePointer->getValue();
782 bool BasePtrHasNonAffine = false;
783 MapInsnToMemAcc TempMemoryAccesses;
784 for (const auto &Pair : Context.Accesses[BasePointer]) {
785 const Instruction *Insn = Pair.first;
786 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000787 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000788 bool IsNonAffine = false;
789 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
790 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000791 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000792
793 if (!AF) {
Michael Kruse09eb4452016-03-03 22:10:47 +0000794 if (isAffine(Pair.second, Scope, Context, BaseValue))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000795 Acc->DelinearizedSubscripts.push_back(Pair.second);
796 else
797 IsNonAffine = true;
798 } else {
799 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
800 Shape->DelinearizedSizes);
801 if (Acc->DelinearizedSubscripts.size() == 0)
802 IsNonAffine = true;
803 for (const SCEV *S : Acc->DelinearizedSubscripts)
Michael Kruse09eb4452016-03-03 22:10:47 +0000804 if (!isAffine(S, Scope, Context, BaseValue))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000805 IsNonAffine = true;
806 }
807
808 // (Possibly) report non affine access
809 if (IsNonAffine) {
810 BasePtrHasNonAffine = true;
811 if (!AllowNonAffine)
812 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
813 Insn, BaseValue);
814 if (!KeepGoing && !AllowNonAffine)
815 return false;
816 }
817 }
818
819 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000820 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
821 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000822
823 return true;
824}
825
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000826bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
827 const SCEVUnknown *BasePointer,
828 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000829 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
830
831 auto Terms = getDelinearizationTerms(Context, BasePointer);
832
833 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
834 Context.ElementSize[BasePointer]);
835
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000836 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
837 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000838 return false;
839
840 return computeAccessFunctions(Context, BasePointer, Shape);
841}
842
843bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000844 // TODO: If we have an unknown access and other non-affine accesses we do
845 // not try to delinearize them for now.
846 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
847 return AllowNonAffine;
848
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000849 for (auto &Pair : Context.NonAffineAccesses) {
850 auto *BasePointer = Pair.first;
851 auto *Scope = Pair.second;
852 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000853 if (KeepGoing)
854 continue;
855 else
856 return false;
857 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000858 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000859 return true;
860}
861
Johannes Doerfertcea61932016-02-21 19:13:19 +0000862bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
863 const SCEVUnknown *BP,
864 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000865
Johannes Doerfertcea61932016-02-21 19:13:19 +0000866 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000867 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000868
Johannes Doerfertcea61932016-02-21 19:13:19 +0000869 auto *BV = BP->getValue();
870 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000871 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000872
Johannes Doerfertcea61932016-02-21 19:13:19 +0000873 // FIXME: Think about allowing IntToPtrInst
874 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
875 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
876
Tobias Grosser458fb782014-01-28 12:58:58 +0000877 // Check that the base address of the access is invariant in the current
878 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000879 if (!isInvariant(*BV, Context.CurRegion))
880 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000881
Johannes Doerfertcea61932016-02-21 19:13:19 +0000882 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000883
Johannes Doerfertcea61932016-02-21 19:13:19 +0000884 const SCEV *Size;
885 if (!isa<MemIntrinsic>(Inst)) {
886 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000887 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000888 auto *SizeTy =
889 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
890 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000891 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000892
Johannes Doerfertcea61932016-02-21 19:13:19 +0000893 if (Context.ElementSize[BP]) {
894 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
895 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
896 Inst, BV);
897
898 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
899 } else {
900 Context.ElementSize[BP] = Size;
901 }
902
903 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000904 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000905 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000906 for (const Loop *L : Loops)
907 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000908 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000909
Michael Kruse09eb4452016-03-03 22:10:47 +0000910 auto *Scope = LI->getLoopFor(Inst->getParent());
911 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context, BV);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000912 // Do not try to delinearize memory intrinsics and force them to be affine.
913 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
914 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
915 BV);
916 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
917 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000918
Johannes Doerfertcea61932016-02-21 19:13:19 +0000919 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000920 Context.NonAffineAccesses.insert(
921 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000922 } else if (!AllowNonAffine && !IsAffine) {
923 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
924 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000925 }
Tobias Grosser75805372011-04-29 06:27:02 +0000926
Tobias Grosser1eedb672014-09-24 21:04:29 +0000927 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000928 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000929
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000930 // Check if the base pointer of the memory access does alias with
931 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000932 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000933 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000934 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000935 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000936
Tobias Grosser1eedb672014-09-24 21:04:29 +0000937 if (!AS.isMustAlias()) {
938 if (PollyUseRuntimeAliasChecks) {
939 bool CanBuildRunTimeCheck = true;
940 // The run-time alias check places code that involves the base pointer at
941 // the beginning of the SCoP. This breaks if the base pointer is defined
942 // inside the scop. Hence, we can only create a run-time check if we are
943 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000944 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000945 for (const auto &Ptr : AS) {
946 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000947 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000948 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000949 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000950 Context.RequiredILS.insert(Load);
951 continue;
952 }
953
Tobias Grosser1eedb672014-09-24 21:04:29 +0000954 CanBuildRunTimeCheck = false;
955 break;
956 }
957 }
958
959 if (CanBuildRunTimeCheck)
960 return true;
961 }
Michael Kruse70131d32016-01-27 17:09:17 +0000962 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000963 }
Tobias Grosser75805372011-04-29 06:27:02 +0000964
965 return true;
966}
967
Johannes Doerfertcea61932016-02-21 19:13:19 +0000968bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
969 DetectionContext &Context) const {
970 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000971 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000972 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
973 const SCEVUnknown *BasePointer;
974
975 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
976
977 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
978}
979
Tobias Grosser75805372011-04-29 06:27:02 +0000980bool ScopDetection::isValidInstruction(Instruction &Inst,
981 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000982 for (auto &Op : Inst.operands()) {
983 auto *OpInst = dyn_cast<Instruction>(&Op);
984
985 if (!OpInst)
986 continue;
987
988 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
989 return false;
990 }
991
Tobias Grosser75805372011-04-29 06:27:02 +0000992 // We only check the call instruction but not invoke instruction.
993 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000994 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000995 return true;
996
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000997 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000998 }
999
1000 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001001 if (!isa<AllocaInst>(Inst))
1002 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001003
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001004 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001005 }
1006
1007 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001008 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001009 Context.hasStores |= isa<StoreInst>(MemInst);
1010 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001011 if (!MemInst.isSimple())
1012 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1013 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001014
Michael Kruse70131d32016-01-27 17:09:17 +00001015 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001016 }
Tobias Grosser75805372011-04-29 06:27:02 +00001017
1018 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001019 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001020}
1021
Johannes Doerfertd020b772015-08-27 06:53:52 +00001022bool ScopDetection::canUseISLTripCount(Loop *L,
1023 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001024 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1025 // need to overapproximate it as a boxed loop.
1026 SmallVector<BasicBlock *, 4> LoopControlBlocks;
1027 L->getLoopLatches(LoopControlBlocks);
1028 L->getExitingBlocks(LoopControlBlocks);
1029 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001030 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001031 return false;
1032 }
1033
Johannes Doerfertd020b772015-08-27 06:53:52 +00001034 // We can use ISL to compute the trip count of L.
1035 return true;
1036}
1037
Tobias Grosser75805372011-04-29 06:27:02 +00001038bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001039 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001040 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001041
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001042 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001043 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001044 while (R != &Context.CurRegion && !R->contains(L))
1045 R = R->getParent();
1046
1047 if (addOverApproximatedRegion(R, Context))
1048 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001049 }
Tobias Grosser75805372011-04-29 06:27:02 +00001050
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001051 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001052 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001053}
1054
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001055/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +00001056/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +00001057static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001058 auto *TripCount = SE.getBackedgeTakenCount(L);
1059
Johannes Doerfertf61df692015-10-04 14:56:08 +00001060 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001061 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001062 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1063 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1064 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001065
1066 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001067 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001068
1069 return count;
1070}
1071
Johannes Doerfertf61df692015-10-04 14:56:08 +00001072int ScopDetection::countBeneficialLoops(Region *R) const {
1073 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001074
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001075 auto L = LI->getLoopFor(R->getEntry());
1076 L = L ? R->outermostLoopInRegion(L) : nullptr;
1077 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001078
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001079 auto SubLoops =
1080 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1081
1082 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001083 if (R->contains(SubLoop))
1084 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001085
Johannes Doerfertf61df692015-10-04 14:56:08 +00001086 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001087}
1088
Tobias Grosser75805372011-04-29 06:27:02 +00001089Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001090 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001091 std::unique_ptr<Region> LastValidRegion;
1092 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001093
1094 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1095
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001096 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001097 const auto &It = DetectionContextMap.insert(std::make_pair(
1098 ExpandedRegion.get(),
1099 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1100 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001101 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001102 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001103
Johannes Doerfert717b8662015-09-08 21:44:27 +00001104 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001105 // If the exit is valid check all blocks
1106 // - if true, a valid region was found => store it + keep expanding
1107 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001108 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1109 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001110 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001111 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001112
Tobias Grosserd7e58642013-04-10 06:55:45 +00001113 // Store this region, because it is the greatest valid (encountered so
1114 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001115 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001116 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001117
1118 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001119 ExpandedRegion =
1120 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001121
1122 } else {
1123 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001124 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001125 ExpandedRegion =
1126 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001127 }
Tobias Grosser75805372011-04-29 06:27:02 +00001128 }
1129
Tobias Grosser378a9f22013-11-16 19:34:11 +00001130 DEBUG({
1131 if (LastValidRegion)
1132 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1133 else
1134 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1135 });
Tobias Grosser75805372011-04-29 06:27:02 +00001136
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001137 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001138}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001139static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001140 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001141 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001142 return false;
1143
1144 return true;
1145}
Tobias Grosser75805372011-04-29 06:27:02 +00001146
Johannes Doerferte46925f2015-10-01 10:59:14 +00001147unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001148 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001149 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001150 if (ValidRegions.count(SubRegion.get())) {
1151 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001152 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001153 } else
1154 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001155 }
1156 return Count;
1157}
1158
Johannes Doerferte46925f2015-10-01 10:59:14 +00001159void ScopDetection::removeCachedResults(const Region &R) {
1160 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001161 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001162}
1163
Tobias Grosser75805372011-04-29 06:27:02 +00001164void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001165 const auto &It = DetectionContextMap.insert(
1166 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1167 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001168
1169 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001170 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001171 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001172 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001173 RegionIsValid = isValidRegion(Context);
1174
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001175 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001176
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001177 if (PollyTrackFailures && HasErrors)
1178 RejectLogs.insert(std::make_pair(&R, Context.Log));
1179
Johannes Doerferte46925f2015-10-01 10:59:14 +00001180 if (HasErrors) {
1181 removeCachedResults(R);
1182 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001183 ++ValidRegion;
1184 ValidRegions.insert(&R);
1185 return;
1186 }
1187
David Blaikieb035f6d2014-04-15 18:45:27 +00001188 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001189 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001190
1191 // Try to expand regions.
1192 //
1193 // As the region tree normally only contains canonical regions, non canonical
1194 // regions that form a Scop are not found. Therefore, those non canonical
1195 // regions are checked by expanding the canonical ones.
1196
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001197 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001198
David Blaikieb035f6d2014-04-15 18:45:27 +00001199 for (auto &SubRegion : R)
1200 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001201
Tobias Grosser26108892014-04-02 20:18:19 +00001202 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001203 // Skip regions that had errors.
1204 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1205 if (HadErrors)
1206 continue;
1207
Tobias Grosser75805372011-04-29 06:27:02 +00001208 // Skip invalid regions. Regions may become invalid, if they are element of
1209 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001210 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001211 continue;
1212
1213 Region *ExpandedR = expandRegion(*CurrentRegion);
1214
1215 if (!ExpandedR)
1216 continue;
1217
1218 R.addSubRegion(ExpandedR, true);
1219 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001220 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001221
Tobias Grosser28a70c52014-01-29 19:05:30 +00001222 // Erase all (direct and indirect) children of ExpandedR from the valid
1223 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001224 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001225 }
1226}
1227
1228bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001229 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001230
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001231 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001232 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001233 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001234 return false;
1235 }
1236
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001237 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001238 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1239
1240 // Also check exception blocks (and possibly register them as non-affine
1241 // regions). Even though exception blocks are not modeled, we use them
1242 // to forward-propagate domain constraints during ScopInfo construction.
1243 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1244 return false;
1245
1246 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001247 continue;
1248
Tobias Grosser1d191902014-03-03 13:13:55 +00001249 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001250 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001251 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001252 }
Tobias Grosser75805372011-04-29 06:27:02 +00001253
Sebastian Pope8863b82014-05-12 19:02:02 +00001254 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001255 return false;
1256
Tobias Grosser75805372011-04-29 06:27:02 +00001257 return true;
1258}
1259
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001260bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1261 int NumLoops) const {
1262 int InstCount = 0;
1263
1264 for (auto *BB : Context.CurRegion.blocks())
1265 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001266 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001267
1268 InstCount = InstCount / NumLoops;
1269
1270 return InstCount >= ProfitabilityMinPerLoopInstructions;
1271}
1272
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001273bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1274 Region &CurRegion = Context.CurRegion;
1275
1276 if (PollyProcessUnprofitable)
1277 return true;
1278
1279 // We can probably not do a lot on scops that only write or only read
1280 // data.
1281 if (!Context.hasStores || !Context.hasLoads)
1282 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1283
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001284 int NumLoops = countBeneficialLoops(&CurRegion);
1285 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001286
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001287 // Scops with at least two loops may allow either loop fusion or tiling and
1288 // are consequently interesting to look at.
1289 if (NumAffineLoops >= 2)
1290 return true;
1291
1292 // Scops that contain a loop with a non-trivial amount of computation per
1293 // loop-iteration are interesting as we may be able to parallelize such
1294 // loops. Individual loops that have only a small amount of computation
1295 // per-iteration are performance-wise very fragile as any change to the
1296 // loop induction variables may affect performance. To not cause spurious
1297 // performance regressions, we do not consider such loops.
1298 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1299 return true;
1300
1301 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001302}
1303
Tobias Grosser75805372011-04-29 06:27:02 +00001304bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001305 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001306
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001307 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001308
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001309 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001310 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001311 return false;
1312 }
1313
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001314 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001315 DEBUG({
1316 dbgs() << "Region entry does not match -polly-region-only";
1317 dbgs() << "\n";
1318 });
1319 return false;
1320 }
1321
Tobias Grosserd654c252012-04-10 18:12:19 +00001322 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001323 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001324 if (CurRegion.getEntry() ==
1325 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1326 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001327
Hongbin Zheng94868e62012-04-07 12:29:17 +00001328 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001329 return false;
1330
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001331 DebugLoc DbgLoc;
1332 if (!isReducibleRegion(CurRegion, DbgLoc))
1333 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1334 &CurRegion, DbgLoc);
1335
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001336 if (!isProfitableRegion(Context))
1337 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001338
Tobias Grosser75805372011-04-29 06:27:02 +00001339 DEBUG(dbgs() << "OK\n");
1340 return true;
1341}
1342
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001343void ScopDetection::markFunctionAsInvalid(Function *F) const {
1344 F->addFnAttr(PollySkipFnAttr);
1345}
1346
Tobias Grosser75805372011-04-29 06:27:02 +00001347bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001348 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001349}
1350
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001351void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001352 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001353 unsigned LineEntry, LineExit;
1354 std::string FileName;
1355
Tobias Grosser00dc3092014-03-02 12:02:46 +00001356 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001357 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1358 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001359 }
1360}
1361
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001362void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001363 for (const Region *R : ValidRegions) {
1364 const Region *Parent = R->getParent();
1365 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1366 emitRejectionRemarks(F, RejectLogs.at(Parent));
1367 }
1368}
1369
1370void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1371 const Region *R) {
1372 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001373 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001374 if (IsValid)
1375 continue;
1376
1377 bool IsLeaf = Child->begin() == Child->end();
1378 if (!IsLeaf)
1379 emitMissedRemarksForLeaves(F, Child.get());
1380 else {
1381 if (RejectLogs.count(Child.get())) {
1382 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1383 }
1384 }
1385 }
1386}
1387
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001388bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1389 BasicBlock *REntry = R.getEntry();
1390 BasicBlock *RExit = R.getExit();
1391 // Map to match the color of a BasicBlock during the DFS walk.
1392 DenseMap<const BasicBlock *, Color> BBColorMap;
1393 // Stack keeping track of current BB and index of next child to be processed.
1394 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1395
1396 unsigned AdjacentBlockIndex = 0;
1397 BasicBlock *CurrBB, *SuccBB;
1398 CurrBB = REntry;
1399
1400 // Initialize the map for all BB with WHITE color.
1401 for (auto *BB : R.blocks())
1402 BBColorMap[BB] = ScopDetection::WHITE;
1403
1404 // Process the entry block of the Region.
1405 BBColorMap[CurrBB] = ScopDetection::GREY;
1406 DFSStack.push(std::make_pair(CurrBB, 0));
1407
1408 while (!DFSStack.empty()) {
1409 // Get next BB on stack to be processed.
1410 CurrBB = DFSStack.top().first;
1411 AdjacentBlockIndex = DFSStack.top().second;
1412 DFSStack.pop();
1413
1414 // Loop to iterate over the successors of current BB.
1415 const TerminatorInst *TInst = CurrBB->getTerminator();
1416 unsigned NSucc = TInst->getNumSuccessors();
1417 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1418 ++I, ++AdjacentBlockIndex) {
1419 SuccBB = TInst->getSuccessor(I);
1420
1421 // Checks for region exit block and self-loops in BB.
1422 if (SuccBB == RExit || SuccBB == CurrBB)
1423 continue;
1424
1425 // WHITE indicates an unvisited BB in DFS walk.
1426 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1427 // Push the current BB and the index of the next child to be visited.
1428 DFSStack.push(std::make_pair(CurrBB, I + 1));
1429 // Push the next BB to be processed.
1430 DFSStack.push(std::make_pair(SuccBB, 0));
1431 // First time the BB is being processed.
1432 BBColorMap[SuccBB] = ScopDetection::GREY;
1433 break;
1434 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1435 // GREY indicates a loop in the control flow.
1436 // If the destination dominates the source, it is a natural loop
1437 // else, an irreducible control flow in the region is detected.
1438 if (!DT->dominates(SuccBB, CurrBB)) {
1439 // Get debug info of instruction which causes irregular control flow.
1440 DbgLoc = TInst->getDebugLoc();
1441 return false;
1442 }
1443 }
1444 }
1445
1446 // If all children of current BB have been processed,
1447 // then mark that BB as fully processed.
1448 if (AdjacentBlockIndex == NSucc)
1449 BBColorMap[CurrBB] = ScopDetection::BLACK;
1450 }
1451
1452 return true;
1453}
1454
Tobias Grosser75805372011-04-29 06:27:02 +00001455bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001456 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001457 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001458 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001459 return false;
1460
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001461 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001462 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001463 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001464 Region *TopRegion = RI->getTopLevelRegion();
1465
Tobias Grosser2ff87232011-10-23 11:17:06 +00001466 releaseMemory();
1467
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001468 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001469 return false;
1470
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001471 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001472 return false;
1473
1474 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001475
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001476 // Only makes sense when we tracked errors.
1477 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001478 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001479 emitMissedRemarksForLeaves(F, TopRegion);
1480 }
1481
Johannes Doerferta05214f2014-10-15 23:24:28 +00001482 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001483 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001484
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001485 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001486 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001487 return false;
1488}
1489
Johannes Doerfertba65c162015-02-24 11:45:21 +00001490bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1491 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001492 const DetectionContext *DC = getDetectionContext(ScopR);
1493 assert(DC && "ScopR is no valid region!");
1494 return DC->NonAffineSubRegionSet.count(SubR);
1495}
1496
1497const ScopDetection::DetectionContext *
1498ScopDetection::getDetectionContext(const Region *R) const {
1499 auto DCMIt = DetectionContextMap.find(R);
1500 if (DCMIt == DetectionContextMap.end())
1501 return nullptr;
1502 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001503}
1504
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001505const ScopDetection::BoxedLoopsSetTy *
1506ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001507 const DetectionContext *DC = getDetectionContext(R);
1508 assert(DC && "ScopR is no valid region!");
1509 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001510}
1511
Hongbin Zheng22623202016-02-15 00:20:58 +00001512const MapInsnToMemAcc *
1513ScopDetection::getInsnToMemAccMap(const Region *R) const {
1514 const DetectionContext *DC = getDetectionContext(R);
1515 assert(DC && "ScopR is no valid region!");
1516 return &DC->InsnToMemAcc;
1517}
1518
Johannes Doerfert09e36972015-10-07 20:17:36 +00001519const InvariantLoadsSetTy *
1520ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001521 const DetectionContext *DC = getDetectionContext(R);
1522 assert(DC && "ScopR is no valid region!");
1523 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001524}
1525
Tobias Grosser75805372011-04-29 06:27:02 +00001526void polly::ScopDetection::verifyRegion(const Region &R) const {
1527 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001528
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001529 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001530 isValidRegion(Context);
1531}
1532
1533void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001534 if (!VerifyScops)
1535 return;
1536
Tobias Grosser26108892014-04-02 20:18:19 +00001537 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001538 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001539}
1540
1541void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001542 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001543 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001544 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001545 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001546 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001547 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001548 AU.setPreservesAll();
1549}
1550
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001551void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001552 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001553 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001554
1555 OS << "\n";
1556}
1557
1558void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001559 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001560 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001561 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001562
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001563 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001564}
1565
1566char ScopDetection::ID = 0;
1567
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001568Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1569
Tobias Grosser73600b82011-10-08 00:30:40 +00001570INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1571 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001572 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001573INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001574INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001575INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001576INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001577INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001578INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1579 "Polly - Detect static control parts (SCoPs)", false, false)