blob: 34f439bae0bbed984e97a37b4df995cc0875730c [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 Grosserc7d3fc52013-07-25 03:02:29 +0000152static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000153 TrackFailures("polly-detect-track-failures",
154 cl::desc("Track failure strings in detecting scop regions"),
155 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000156 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000157
Andreas Simbuerger04472402014-05-24 09:25:10 +0000158static cl::opt<bool> KeepGoing("polly-detect-keep-going",
159 cl::desc("Do not fail on the first error."),
160 cl::Hidden, cl::ZeroOrMore, cl::init(false),
161 cl::cat(PollyCategory));
162
Sebastian Pop18016682014-04-08 21:20:44 +0000163static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000164 PollyDelinearizeX("polly-delinearize",
165 cl::desc("Delinearize array access functions"),
166 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000167 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000168
Tobias Grossera1689932014-02-18 18:49:49 +0000169static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000170 VerifyScops("polly-detect-verify",
171 cl::desc("Verify the detected SCoPs after each transformation"),
172 cl::Hidden, cl::init(false), cl::ZeroOrMore,
173 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000174
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000175bool polly::PollyInvariantLoadHoisting;
176static cl::opt<bool, true> XPollyInvariantLoadHoisting(
177 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
178 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
179 cl::init(true), cl::cat(PollyCategory));
180
Johannes Doerferte526de52015-09-21 19:10:11 +0000181/// @brief The minimal trip count under which loops are considered unprofitable.
182static const unsigned MIN_LOOP_TRIP_COUNT = 8;
183
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000184bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000185bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000186StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000187
Tobias Grosser75805372011-04-29 06:27:02 +0000188//===----------------------------------------------------------------------===//
189// Statistics.
190
191STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
192
Tobias Grosser8519f892013-12-18 10:49:53 +0000193class DiagnosticScopFound : public DiagnosticInfo {
194private:
195 static int PluginDiagnosticKind;
196
197 Function &F;
198 std::string FileName;
199 unsigned EntryLine, ExitLine;
200
201public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000202 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
203 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000204 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000205 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000206
207 virtual void print(DiagnosticPrinter &DP) const;
208
209 static bool classof(const DiagnosticInfo *DI) {
210 return DI->getKind() == PluginDiagnosticKind;
211 }
212};
213
Tobias Grosserdb6db502016-04-01 07:15:19 +0000214int DiagnosticScopFound::PluginDiagnosticKind =
215 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000216
Tobias Grosser8519f892013-12-18 10:49:53 +0000217void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000218 DP << "Polly detected an optimizable loop region (scop) in function '" << F
219 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000220
221 if (FileName.empty()) {
222 DP << "Scop location is unknown. Compile with debug info "
223 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000224 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000225 }
226
227 DP << FileName << ":" << EntryLine << ": Start of scop\n";
228 DP << FileName << ":" << ExitLine << ": End of scop";
229}
230
Tobias Grosser75805372011-04-29 06:27:02 +0000231//===----------------------------------------------------------------------===//
232// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000233
Johannes Doerfertb164c792014-09-18 11:17:17 +0000234ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000235 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000236 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000237 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000238}
239
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000240template <class RR, typename... Args>
241inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
242 Args &&... Arguments) const {
243
244 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000245 RejectLog &Log = Context.Log;
246 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000247
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000248 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000249 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000250
251 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000252 DEBUG(dbgs() << "\n");
253 } else {
254 assert(!Assert && "Verification of detected scop failed");
255 }
256
257 return false;
258}
259
Tobias Grossera1689932014-02-18 18:49:49 +0000260bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
261 if (!ValidRegions.count(&R))
262 return false;
263
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000264 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000265 DetectionContextMap.erase(&R);
266 const auto &It = DetectionContextMap.insert(
267 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
268 false /*verifying*/)));
269 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000270 return isValidRegion(Context);
271 }
Tobias Grossera1689932014-02-18 18:49:49 +0000272
273 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000274}
275
Tobias Grosser4f129a62011-10-08 00:30:55 +0000276std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000277 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000278 return "";
279
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000280 // Get the first error we found. Even in keep-going mode, this is the first
281 // reason that caused the candidate to be rejected.
282 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000283
284 // This can happen when we marked a region invalid, but didn't track
285 // an error for it.
286 if (Errors.size() == 0)
287 return "";
288
289 RejectReasonPtr RR = *Errors.begin();
290 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000291}
292
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000293bool ScopDetection::addOverApproximatedRegion(Region *AR,
294 DetectionContext &Context) const {
295
296 // If we already know about Ar we can exit.
297 if (!Context.NonAffineSubRegionSet.insert(AR))
298 return true;
299
300 // All loops in the region have to be overapproximated too if there
301 // are accesses that depend on the iteration count.
302 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000303 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000304 if (AR->contains(L))
305 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000306 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000307
308 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000309}
310
Johannes Doerfert09e36972015-10-07 20:17:36 +0000311bool ScopDetection::onlyValidRequiredInvariantLoads(
312 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
313 Region &CurRegion = Context.CurRegion;
314
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000315 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
316 return false;
317
Johannes Doerfert09e36972015-10-07 20:17:36 +0000318 for (LoadInst *Load : RequiredILS)
319 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
320 return false;
321
322 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
323
324 return true;
325}
326
Michael Kruse09eb4452016-03-03 22:10:47 +0000327bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000328 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000329
330 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000331 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000332 return false;
333
334 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
335 return false;
336
337 return true;
338}
339
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000340bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000341 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000342 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000343 Loop *L = LI->getLoopFor(&BB);
344 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000345
Michael Kruse09eb4452016-03-03 22:10:47 +0000346 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000347 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000348
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000349 if (!IsLoopBranch && AllowNonAffineSubRegions &&
350 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
351 return true;
352
353 if (IsLoopBranch)
354 return false;
355
356 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
357 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000358}
359
360bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000361 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000362 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000363
364 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
365 auto Opcode = BinOp->getOpcode();
366 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
367 Value *Op0 = BinOp->getOperand(0);
368 Value *Op1 = BinOp->getOperand(1);
369 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
370 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
371 }
372 }
373
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000374 // Non constant conditions of branches need to be ICmpInst.
375 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000376 if (!IsLoopBranch && AllowNonAffineSubRegions &&
377 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
378 return true;
379 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000380 }
Tobias Grosser75805372011-04-29 06:27:02 +0000381
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000382 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000383
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000384 // Are both operands of the ICmp affine?
385 if (isa<UndefValue>(ICmp->getOperand(0)) ||
386 isa<UndefValue>(ICmp->getOperand(1)))
387 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000388
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000389 Loop *L = LI->getLoopFor(ICmp->getParent());
390 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
391 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000392
Michael Kruse09eb4452016-03-03 22:10:47 +0000393 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000394 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000395
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000396 if (!IsLoopBranch && AllowNonAffineSubRegions &&
397 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
398 return true;
399
400 if (IsLoopBranch)
401 return false;
402
403 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
404 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000405}
406
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000407bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000408 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000409 DetectionContext &Context) const {
410 Region &CurRegion = Context.CurRegion;
411
412 TerminatorInst *TI = BB.getTerminator();
413
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000414 if (AllowUnreachable && isa<UnreachableInst>(TI))
415 return true;
416
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000417 // Return instructions are only valid if the region is the top level region.
418 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
419 return true;
420
421 Value *Condition = getConditionFromTerminator(TI);
422
423 if (!Condition)
424 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
425
426 // UndefValue is not allowed as condition.
427 if (isa<UndefValue>(Condition))
428 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
429
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000430 // Constant integer conditions are always affine.
431 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000432 return true;
433
434 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000435 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000436
437 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
438 assert(SI && "Terminator was neither branch nor switch");
439
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000440 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000441}
442
Johannes Doerfertcea61932016-02-21 19:13:19 +0000443bool ScopDetection::isValidCallInst(CallInst &CI,
444 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000445 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000446 return false;
447
448 if (CI.doesNotAccessMemory())
449 return true;
450
Johannes Doerfertcea61932016-02-21 19:13:19 +0000451 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000452 if (isValidIntrinsicInst(*II, Context))
453 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000454
Tobias Grosser75805372011-04-29 06:27:02 +0000455 Function *CalledFunction = CI.getCalledFunction();
456
457 // Indirect calls are not supported.
458 if (CalledFunction == 0)
459 return false;
460
Tobias Grosser898a6362016-03-23 06:40:15 +0000461 if (AllowModrefCall) {
462 switch (AA->getModRefBehavior(CalledFunction)) {
463 case llvm::FMRB_UnknownModRefBehavior:
464 return false;
465 case llvm::FMRB_DoesNotAccessMemory:
466 case llvm::FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000467 // Implicitly disable delinearization since we have an unknown
468 // accesses with an unknown access function.
469 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000470 Context.AST.add(&CI);
471 return true;
472 case llvm::FMRB_OnlyReadsArgumentPointees:
473 case llvm::FMRB_OnlyAccessesArgumentPointees:
474 for (const auto &Arg : CI.arg_operands()) {
475 if (!Arg->getType()->isPointerTy())
476 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000477
Tobias Grosser898a6362016-03-23 06:40:15 +0000478 // Bail if a pointer argument has a base address not known to
479 // ScalarEvolution. Note that a zero pointer is acceptable.
480 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
481 if (ArgSCEV->isZero())
482 continue;
483
484 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
485 if (!BP)
486 return false;
487
488 // Implicitly disable delinearization since we have an unknown
489 // accesses with an unknown access function.
490 Context.HasUnknownAccess = true;
491 }
492
493 Context.AST.add(&CI);
494 return true;
495 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000496 }
497
Johannes Doerfertcea61932016-02-21 19:13:19 +0000498 return false;
499}
500
501bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
502 DetectionContext &Context) const {
503 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000504 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000505
Johannes Doerfertcea61932016-02-21 19:13:19 +0000506 // The closest loop surrounding the call instruction.
507 Loop *L = LI->getLoopFor(II.getParent());
508
509 // The access function and base pointer for memory intrinsics.
510 const SCEV *AF;
511 const SCEVUnknown *BP;
512
513 switch (II.getIntrinsicID()) {
514 // Memory intrinsics that can be represented are supported.
515 case llvm::Intrinsic::memmove:
516 case llvm::Intrinsic::memcpy:
517 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000518 if (!AF->isZero()) {
519 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
520 // Bail if the source pointer is not valid.
521 if (!isValidAccess(&II, AF, BP, Context))
522 return false;
523 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000524 // Fall through
525 case llvm::Intrinsic::memset:
526 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000527 if (!AF->isZero()) {
528 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
529 // Bail if the destination pointer is not valid.
530 if (!isValidAccess(&II, AF, BP, Context))
531 return false;
532 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000533
534 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000535 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000536 Context))
537 return false;
538
539 return true;
540 default:
541 break;
542 }
543
Tobias Grosser75805372011-04-29 06:27:02 +0000544 return false;
545}
546
Tobias Grosser458fb782014-01-28 12:58:58 +0000547bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
548 // A reference to function argument or constant value is invariant.
549 if (isa<Argument>(Val) || isa<Constant>(Val))
550 return true;
551
552 const Instruction *I = dyn_cast<Instruction>(&Val);
553 if (!I)
554 return false;
555
556 if (!Reg.contains(I))
557 return true;
558
559 if (I->mayHaveSideEffects())
560 return false;
561
Johannes Doerfertfbb63b82016-04-09 21:57:13 +0000562 if (isa<SelectInst>(I))
563 return false;
564
Tobias Grosser458fb782014-01-28 12:58:58 +0000565 // When Val is a Phi node, it is likely not invariant. We do not check whether
566 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000567 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000568 if (isa<PHINode>(*I))
569 return false;
570
Tobias Grosser26108892014-04-02 20:18:19 +0000571 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000572 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000573 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000574
Tobias Grosser458fb782014-01-28 12:58:58 +0000575 return true;
576}
577
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000578/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
579/// register the '...' components.
580///
581/// Array access expressions as they are generated by gfortran contain smax(0,
582/// size) expressions that confuse the 'normal' delinearization algorithm.
583/// However, if we extract such expressions before the normal delinearization
584/// takes place they can actually help to identify array size expressions in
585/// fortran accesses. For the subsequently following delinearization the smax(0,
586/// size) component can be replaced by just 'size'. This is correct as we will
587/// always add and verify the assumption that for all subscript expressions
588/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
589/// that 0 <= size, which means smax(0, size) == size.
590struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
591public:
592 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
593 std::vector<const SCEV *> *Terms = nullptr) {
594
595 SCEVRemoveMax D(SE, Terms);
596 return D.visit(Expr);
597 }
598
599 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
600 : SE(SE), Terms(Terms) {}
601
602 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
603
604 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
605 return Expr;
606 }
607
608 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
609 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
610 }
611
612 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
613
614 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000615 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000616 auto Res = visit(Expr->getOperand(1));
617 if (Terms)
618 (*Terms).push_back(Res);
619 return Res;
620 }
621
622 return Expr;
623 }
624
Roman Gareev8aa43752015-12-17 20:37:17 +0000625 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000626
627 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
628
629 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
630 return Expr;
631 }
632
633 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
634
635 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
636 SmallVector<const SCEV *, 5> NewOps;
637 for (const SCEV *Op : Expr->operands())
638 NewOps.push_back(visit(Op));
639
640 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
641 }
642
643 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
644 SmallVector<const SCEV *, 5> NewOps;
645 for (const SCEV *Op : Expr->operands())
646 NewOps.push_back(visit(Op));
647
648 return SE.getAddExpr(NewOps);
649 }
650
651 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
652 SmallVector<const SCEV *, 5> NewOps;
653 for (const SCEV *Op : Expr->operands())
654 NewOps.push_back(visit(Op));
655
656 return SE.getMulExpr(NewOps);
657 }
658
659private:
660 ScalarEvolution &SE;
661 std::vector<const SCEV *> *Terms;
662};
663
Tobias Grosserd68ba422015-11-24 05:00:36 +0000664SmallVector<const SCEV *, 4>
665ScopDetection::getDelinearizationTerms(DetectionContext &Context,
666 const SCEVUnknown *BasePointer) const {
667 SmallVector<const SCEV *, 4> Terms;
668 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000669 std::vector<const SCEV *> MaxTerms;
670 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
671 if (MaxTerms.size() > 0) {
672 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
673 continue;
674 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000675 // In case the outermost expression is a plain add, we check if any of its
676 // terms has the form 4 * %inst * %param * %param ..., aka a term that
677 // contains a product between a parameter and an instruction that is
678 // inside the scop. Such instructions, if allowed at all, are instructions
679 // SCEV can not represent, but Polly is still looking through. As a
680 // result, these instructions can depend on induction variables and are
681 // most likely no array sizes. However, terms that are multiplied with
682 // them are likely candidates for array sizes.
683 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
684 for (auto Op : AF->operands()) {
685 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
686 SE->collectParametricTerms(AF2, Terms);
687 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
688 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000689
Tobias Grosserd68ba422015-11-24 05:00:36 +0000690 for (auto *MulOp : AF2->operands()) {
691 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
692 Operands.push_back(Const);
693 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
694 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
695 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000696 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000697
698 } else {
699 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000700 }
701 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000702 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000703 if (Operands.size())
704 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000705 }
706 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000707 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000708 if (Terms.empty())
709 SE->collectParametricTerms(Pair.second, Terms);
710 }
711 return Terms;
712}
Sebastian Pope8863b82014-05-12 19:02:02 +0000713
Tobias Grosserd68ba422015-11-24 05:00:36 +0000714bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
715 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000716 const SCEVUnknown *BasePointer,
717 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000718 Value *BaseValue = BasePointer->getValue();
719 Region &CurRegion = Context.CurRegion;
720 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000721 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000722 Sizes.clear();
723 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000724 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000725 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
726 auto *V = dyn_cast<Value>(Unknown->getValue());
727 if (auto *Load = dyn_cast<LoadInst>(V)) {
728 if (Context.CurRegion.contains(Load) &&
729 isHoistableLoad(Load, CurRegion, *LI, *SE))
730 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000731 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000732 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000733 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000734 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000735 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000736 Context, /*Assert=*/true, DelinearizedSize,
737 Context.Accesses[BasePointer].front().first, BaseValue);
738 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000739
Tobias Grosserd68ba422015-11-24 05:00:36 +0000740 // No array shape derived.
741 if (Sizes.empty()) {
742 if (AllowNonAffine)
743 return true;
744
Tobias Grosser230acc42014-09-13 14:47:55 +0000745 for (const auto &Pair : Context.Accesses[BasePointer]) {
746 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000747 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000748
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000749 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000750 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
751 BaseValue);
752 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000753 return false;
754 }
755 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000756 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000757 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000758 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000759}
760
Tobias Grosserd68ba422015-11-24 05:00:36 +0000761// We first store the resulting memory accesses in TempMemoryAccesses. Only
762// if the access functions for all memory accesses have been successfully
763// delinearized we continue. Otherwise, we either report a failure or, if
764// non-affine accesses are allowed, we drop the information. In case the
765// information is dropped the memory accesses need to be overapproximated
766// when translated to a polyhedral representation.
767bool ScopDetection::computeAccessFunctions(
768 DetectionContext &Context, const SCEVUnknown *BasePointer,
769 std::shared_ptr<ArrayShape> Shape) const {
770 Value *BaseValue = BasePointer->getValue();
771 bool BasePtrHasNonAffine = false;
772 MapInsnToMemAcc TempMemoryAccesses;
773 for (const auto &Pair : Context.Accesses[BasePointer]) {
774 const Instruction *Insn = Pair.first;
775 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000776 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000777 bool IsNonAffine = false;
778 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
779 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000780 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000781
782 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000783 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000784 Acc->DelinearizedSubscripts.push_back(Pair.second);
785 else
786 IsNonAffine = true;
787 } else {
788 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
789 Shape->DelinearizedSizes);
790 if (Acc->DelinearizedSubscripts.size() == 0)
791 IsNonAffine = true;
792 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000793 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000794 IsNonAffine = true;
795 }
796
797 // (Possibly) report non affine access
798 if (IsNonAffine) {
799 BasePtrHasNonAffine = true;
800 if (!AllowNonAffine)
801 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
802 Insn, BaseValue);
803 if (!KeepGoing && !AllowNonAffine)
804 return false;
805 }
806 }
807
808 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000809 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
810 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000811
812 return true;
813}
814
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000815bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
816 const SCEVUnknown *BasePointer,
817 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000818 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
819
820 auto Terms = getDelinearizationTerms(Context, BasePointer);
821
822 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
823 Context.ElementSize[BasePointer]);
824
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000825 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
826 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000827 return false;
828
829 return computeAccessFunctions(Context, BasePointer, Shape);
830}
831
832bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000833 // TODO: If we have an unknown access and other non-affine accesses we do
834 // not try to delinearize them for now.
835 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
836 return AllowNonAffine;
837
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000838 for (auto &Pair : Context.NonAffineAccesses) {
839 auto *BasePointer = Pair.first;
840 auto *Scope = Pair.second;
841 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000842 if (KeepGoing)
843 continue;
844 else
845 return false;
846 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000847 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000848 return true;
849}
850
Johannes Doerfertcea61932016-02-21 19:13:19 +0000851bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
852 const SCEVUnknown *BP,
853 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000854
Johannes Doerfertcea61932016-02-21 19:13:19 +0000855 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000856 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000857
Johannes Doerfertcea61932016-02-21 19:13:19 +0000858 auto *BV = BP->getValue();
859 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000860 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000861
Johannes Doerfertcea61932016-02-21 19:13:19 +0000862 // FIXME: Think about allowing IntToPtrInst
863 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
864 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
865
Tobias Grosser458fb782014-01-28 12:58:58 +0000866 // Check that the base address of the access is invariant in the current
867 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000868 if (!isInvariant(*BV, Context.CurRegion))
869 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000870
Johannes Doerfertcea61932016-02-21 19:13:19 +0000871 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000872
Johannes Doerfertcea61932016-02-21 19:13:19 +0000873 const SCEV *Size;
874 if (!isa<MemIntrinsic>(Inst)) {
875 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000876 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000877 auto *SizeTy =
878 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
879 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000880 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000881
Johannes Doerfertcea61932016-02-21 19:13:19 +0000882 if (Context.ElementSize[BP]) {
883 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
884 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
885 Inst, BV);
886
887 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
888 } else {
889 Context.ElementSize[BP] = Size;
890 }
891
892 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000893 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000894 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000895 for (const Loop *L : Loops)
896 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000897 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000898
Michael Kruse09eb4452016-03-03 22:10:47 +0000899 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000900 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000901 // Do not try to delinearize memory intrinsics and force them to be affine.
902 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
903 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
904 BV);
905 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
906 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000907
Johannes Doerfertcea61932016-02-21 19:13:19 +0000908 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000909 Context.NonAffineAccesses.insert(
910 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000911 } else if (!AllowNonAffine && !IsAffine) {
912 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
913 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000914 }
Tobias Grosser75805372011-04-29 06:27:02 +0000915
Tobias Grosser1eedb672014-09-24 21:04:29 +0000916 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000917 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000918
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000919 // Check if the base pointer of the memory access does alias with
920 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000921 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000922 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000923 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000924 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000925
Tobias Grosser1eedb672014-09-24 21:04:29 +0000926 if (!AS.isMustAlias()) {
927 if (PollyUseRuntimeAliasChecks) {
928 bool CanBuildRunTimeCheck = true;
929 // The run-time alias check places code that involves the base pointer at
930 // the beginning of the SCoP. This breaks if the base pointer is defined
931 // inside the scop. Hence, we can only create a run-time check if we are
932 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000933 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000934 for (const auto &Ptr : AS) {
935 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000936 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000937 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000938 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000939 Context.RequiredILS.insert(Load);
940 continue;
941 }
942
Tobias Grosser1eedb672014-09-24 21:04:29 +0000943 CanBuildRunTimeCheck = false;
944 break;
945 }
946 }
947
948 if (CanBuildRunTimeCheck)
949 return true;
950 }
Michael Kruse70131d32016-01-27 17:09:17 +0000951 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000952 }
Tobias Grosser75805372011-04-29 06:27:02 +0000953
954 return true;
955}
956
Johannes Doerfertcea61932016-02-21 19:13:19 +0000957bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
958 DetectionContext &Context) const {
959 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000960 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000961 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
962 const SCEVUnknown *BasePointer;
963
964 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
965
966 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
967}
968
Tobias Grosser75805372011-04-29 06:27:02 +0000969bool ScopDetection::isValidInstruction(Instruction &Inst,
970 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000971 for (auto &Op : Inst.operands()) {
972 auto *OpInst = dyn_cast<Instruction>(&Op);
973
974 if (!OpInst)
975 continue;
976
977 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
978 return false;
979 }
980
Johannes Doerfert81c41b92016-04-09 21:55:58 +0000981 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
982 return false;
983
Tobias Grosser75805372011-04-29 06:27:02 +0000984 // We only check the call instruction but not invoke instruction.
985 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000986 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000987 return true;
988
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000989 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000990 }
991
992 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000993 if (!isa<AllocaInst>(Inst))
994 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000995
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000996 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000997 }
998
999 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001000 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001001 Context.hasStores |= isa<StoreInst>(MemInst);
1002 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001003 if (!MemInst.isSimple())
1004 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1005 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001006
Michael Kruse70131d32016-01-27 17:09:17 +00001007 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001008 }
Tobias Grosser75805372011-04-29 06:27:02 +00001009
1010 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001011 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001012}
1013
Johannes Doerfertd020b772015-08-27 06:53:52 +00001014bool ScopDetection::canUseISLTripCount(Loop *L,
1015 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001016 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1017 // need to overapproximate it as a boxed loop.
1018 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001019 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001020
1021 // Loops without exiting blocks cannot be handled by the schedule generation
1022 // as it depends on a region covering that is not given.
1023 if (LoopControlBlocks.empty())
1024 return false;
1025
1026 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001027 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001028 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001029 return false;
1030 }
1031
Johannes Doerfertd020b772015-08-27 06:53:52 +00001032 // We can use ISL to compute the trip count of L.
1033 return true;
1034}
1035
Tobias Grosser75805372011-04-29 06:27:02 +00001036bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001037 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001038 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001039
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001040 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001041 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001042 while (R != &Context.CurRegion && !R->contains(L))
1043 R = R->getParent();
1044
1045 if (addOverApproximatedRegion(R, Context))
1046 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001047 }
Tobias Grosser75805372011-04-29 06:27:02 +00001048
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001049 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001050 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001051}
1052
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001053/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +00001054/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +00001055static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001056 auto *TripCount = SE.getBackedgeTakenCount(L);
1057
Johannes Doerfertf61df692015-10-04 14:56:08 +00001058 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001059 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001060 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1061 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1062 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001063
1064 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001065 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001066
1067 return count;
1068}
1069
Johannes Doerfertf61df692015-10-04 14:56:08 +00001070int ScopDetection::countBeneficialLoops(Region *R) const {
1071 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001072
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001073 auto L = LI->getLoopFor(R->getEntry());
1074 L = L ? R->outermostLoopInRegion(L) : nullptr;
1075 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001076
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001077 auto SubLoops =
1078 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1079
1080 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001081 if (R->contains(SubLoop))
1082 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001083
Johannes Doerfertf61df692015-10-04 14:56:08 +00001084 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001085}
1086
Tobias Grosser75805372011-04-29 06:27:02 +00001087Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001088 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001089 std::unique_ptr<Region> LastValidRegion;
1090 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001091
1092 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1093
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001094 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001095 const auto &It = DetectionContextMap.insert(std::make_pair(
1096 ExpandedRegion.get(),
1097 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1098 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001099 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001100 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001101
Johannes Doerfert717b8662015-09-08 21:44:27 +00001102 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001103 // If the exit is valid check all blocks
1104 // - if true, a valid region was found => store it + keep expanding
1105 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001106 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1107 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001108 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001109 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001110
Tobias Grosserd7e58642013-04-10 06:55:45 +00001111 // Store this region, because it is the greatest valid (encountered so
1112 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001113 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001114 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001115
1116 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001117 ExpandedRegion =
1118 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001119
1120 } else {
1121 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001122 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001123 ExpandedRegion =
1124 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001125 }
Tobias Grosser75805372011-04-29 06:27:02 +00001126 }
1127
Tobias Grosser378a9f22013-11-16 19:34:11 +00001128 DEBUG({
1129 if (LastValidRegion)
1130 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1131 else
1132 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1133 });
Tobias Grosser75805372011-04-29 06:27:02 +00001134
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001135 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001136}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001137static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001138 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001139 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001140 return false;
1141
1142 return true;
1143}
Tobias Grosser75805372011-04-29 06:27:02 +00001144
Johannes Doerferte46925f2015-10-01 10:59:14 +00001145unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001146 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001147 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001148 if (ValidRegions.count(SubRegion.get())) {
1149 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001150 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001151 } else
1152 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001153 }
1154 return Count;
1155}
1156
Johannes Doerferte46925f2015-10-01 10:59:14 +00001157void ScopDetection::removeCachedResults(const Region &R) {
1158 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001159 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001160}
1161
Tobias Grosser75805372011-04-29 06:27:02 +00001162void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001163 const auto &It = DetectionContextMap.insert(
1164 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1165 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001166
1167 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001168 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001169 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001170 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001171 RegionIsValid = isValidRegion(Context);
1172
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001173 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001174
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001175 if (PollyTrackFailures && HasErrors)
1176 RejectLogs.insert(std::make_pair(&R, Context.Log));
1177
Johannes Doerferte46925f2015-10-01 10:59:14 +00001178 if (HasErrors) {
1179 removeCachedResults(R);
1180 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001181 ++ValidRegion;
1182 ValidRegions.insert(&R);
1183 return;
1184 }
1185
David Blaikieb035f6d2014-04-15 18:45:27 +00001186 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001187 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001188
1189 // Try to expand regions.
1190 //
1191 // As the region tree normally only contains canonical regions, non canonical
1192 // regions that form a Scop are not found. Therefore, those non canonical
1193 // regions are checked by expanding the canonical ones.
1194
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001195 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001196
David Blaikieb035f6d2014-04-15 18:45:27 +00001197 for (auto &SubRegion : R)
1198 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001199
Tobias Grosser26108892014-04-02 20:18:19 +00001200 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001201 // Skip regions that had errors.
1202 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1203 if (HadErrors)
1204 continue;
1205
Tobias Grosser75805372011-04-29 06:27:02 +00001206 // Skip invalid regions. Regions may become invalid, if they are element of
1207 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001208 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001209 continue;
1210
1211 Region *ExpandedR = expandRegion(*CurrentRegion);
1212
1213 if (!ExpandedR)
1214 continue;
1215
1216 R.addSubRegion(ExpandedR, true);
1217 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001218 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001219
Tobias Grosser28a70c52014-01-29 19:05:30 +00001220 // Erase all (direct and indirect) children of ExpandedR from the valid
1221 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001222 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001223 }
1224}
1225
1226bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001227 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001228
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001229 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001230 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001231 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1232 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001233 return false;
1234 }
1235
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001236 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001237 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1238
1239 // Also check exception blocks (and possibly register them as non-affine
1240 // regions). Even though exception blocks are not modeled, we use them
1241 // to forward-propagate domain constraints during ScopInfo construction.
1242 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1243 return false;
1244
1245 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001246 continue;
1247
Tobias Grosser1d191902014-03-03 13:13:55 +00001248 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001249 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001250 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001251 }
Tobias Grosser75805372011-04-29 06:27:02 +00001252
Sebastian Pope8863b82014-05-12 19:02:02 +00001253 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001254 return false;
1255
Tobias Grosser75805372011-04-29 06:27:02 +00001256 return true;
1257}
1258
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001259bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1260 int NumLoops) const {
1261 int InstCount = 0;
1262
1263 for (auto *BB : Context.CurRegion.blocks())
1264 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001265 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001266
1267 InstCount = InstCount / NumLoops;
1268
1269 return InstCount >= ProfitabilityMinPerLoopInstructions;
1270}
1271
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001272bool ScopDetection::hasPossiblyDistributableLoop(
1273 DetectionContext &Context) const {
1274 for (auto *BB : Context.CurRegion.blocks()) {
1275 auto *L = LI->getLoopFor(BB);
1276 if (!Context.CurRegion.contains(L))
1277 continue;
1278 if (Context.BoxedLoopsSet.count(L))
1279 continue;
1280 unsigned StmtsWithStoresInLoops = 0;
1281 for (auto *LBB : L->blocks()) {
1282 bool MemStore = false;
1283 for (auto &I : *LBB)
1284 MemStore |= isa<StoreInst>(&I);
1285 StmtsWithStoresInLoops += MemStore;
1286 }
1287 return (StmtsWithStoresInLoops > 1);
1288 }
1289 return false;
1290}
1291
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001292bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1293 Region &CurRegion = Context.CurRegion;
1294
1295 if (PollyProcessUnprofitable)
1296 return true;
1297
1298 // We can probably not do a lot on scops that only write or only read
1299 // data.
1300 if (!Context.hasStores || !Context.hasLoads)
1301 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1302
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001303 int NumLoops = countBeneficialLoops(&CurRegion);
1304 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001305
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001306 // Scops with at least two loops may allow either loop fusion or tiling and
1307 // are consequently interesting to look at.
1308 if (NumAffineLoops >= 2)
1309 return true;
1310
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001311 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1312 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1313 return true;
1314
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001315 // Scops that contain a loop with a non-trivial amount of computation per
1316 // loop-iteration are interesting as we may be able to parallelize such
1317 // loops. Individual loops that have only a small amount of computation
1318 // per-iteration are performance-wise very fragile as any change to the
1319 // loop induction variables may affect performance. To not cause spurious
1320 // performance regressions, we do not consider such loops.
1321 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1322 return true;
1323
1324 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001325}
1326
Tobias Grosser75805372011-04-29 06:27:02 +00001327bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001328 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001329
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001330 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001331
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001332 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001333 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001334 return false;
1335 }
1336
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001337 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001338 DEBUG({
1339 dbgs() << "Region entry does not match -polly-region-only";
1340 dbgs() << "\n";
1341 });
1342 return false;
1343 }
1344
Tobias Grosserd654c252012-04-10 18:12:19 +00001345 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001346 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001347 if (CurRegion.getEntry() ==
1348 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1349 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001350
Hongbin Zheng94868e62012-04-07 12:29:17 +00001351 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001352 return false;
1353
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001354 DebugLoc DbgLoc;
1355 if (!isReducibleRegion(CurRegion, DbgLoc))
1356 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1357 &CurRegion, DbgLoc);
1358
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001359 if (!isProfitableRegion(Context))
1360 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001361
Tobias Grosser75805372011-04-29 06:27:02 +00001362 DEBUG(dbgs() << "OK\n");
1363 return true;
1364}
1365
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001366void ScopDetection::markFunctionAsInvalid(Function *F) const {
1367 F->addFnAttr(PollySkipFnAttr);
1368}
1369
Tobias Grosser75805372011-04-29 06:27:02 +00001370bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001371 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001372}
1373
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001374void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001375 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001376 unsigned LineEntry, LineExit;
1377 std::string FileName;
1378
Tobias Grosser00dc3092014-03-02 12:02:46 +00001379 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001380 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1381 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001382 }
1383}
1384
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001385void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001386 for (const Region *R : ValidRegions) {
1387 const Region *Parent = R->getParent();
1388 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1389 emitRejectionRemarks(F, RejectLogs.at(Parent));
1390 }
1391}
1392
1393void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1394 const Region *R) {
1395 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001396 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001397 if (IsValid)
1398 continue;
1399
1400 bool IsLeaf = Child->begin() == Child->end();
1401 if (!IsLeaf)
1402 emitMissedRemarksForLeaves(F, Child.get());
1403 else {
1404 if (RejectLogs.count(Child.get())) {
1405 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1406 }
1407 }
1408 }
1409}
1410
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001411bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1412 BasicBlock *REntry = R.getEntry();
1413 BasicBlock *RExit = R.getExit();
1414 // Map to match the color of a BasicBlock during the DFS walk.
1415 DenseMap<const BasicBlock *, Color> BBColorMap;
1416 // Stack keeping track of current BB and index of next child to be processed.
1417 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1418
1419 unsigned AdjacentBlockIndex = 0;
1420 BasicBlock *CurrBB, *SuccBB;
1421 CurrBB = REntry;
1422
1423 // Initialize the map for all BB with WHITE color.
1424 for (auto *BB : R.blocks())
1425 BBColorMap[BB] = ScopDetection::WHITE;
1426
1427 // Process the entry block of the Region.
1428 BBColorMap[CurrBB] = ScopDetection::GREY;
1429 DFSStack.push(std::make_pair(CurrBB, 0));
1430
1431 while (!DFSStack.empty()) {
1432 // Get next BB on stack to be processed.
1433 CurrBB = DFSStack.top().first;
1434 AdjacentBlockIndex = DFSStack.top().second;
1435 DFSStack.pop();
1436
1437 // Loop to iterate over the successors of current BB.
1438 const TerminatorInst *TInst = CurrBB->getTerminator();
1439 unsigned NSucc = TInst->getNumSuccessors();
1440 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1441 ++I, ++AdjacentBlockIndex) {
1442 SuccBB = TInst->getSuccessor(I);
1443
1444 // Checks for region exit block and self-loops in BB.
1445 if (SuccBB == RExit || SuccBB == CurrBB)
1446 continue;
1447
1448 // WHITE indicates an unvisited BB in DFS walk.
1449 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1450 // Push the current BB and the index of the next child to be visited.
1451 DFSStack.push(std::make_pair(CurrBB, I + 1));
1452 // Push the next BB to be processed.
1453 DFSStack.push(std::make_pair(SuccBB, 0));
1454 // First time the BB is being processed.
1455 BBColorMap[SuccBB] = ScopDetection::GREY;
1456 break;
1457 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1458 // GREY indicates a loop in the control flow.
1459 // If the destination dominates the source, it is a natural loop
1460 // else, an irreducible control flow in the region is detected.
1461 if (!DT->dominates(SuccBB, CurrBB)) {
1462 // Get debug info of instruction which causes irregular control flow.
1463 DbgLoc = TInst->getDebugLoc();
1464 return false;
1465 }
1466 }
1467 }
1468
1469 // If all children of current BB have been processed,
1470 // then mark that BB as fully processed.
1471 if (AdjacentBlockIndex == NSucc)
1472 BBColorMap[CurrBB] = ScopDetection::BLACK;
1473 }
1474
1475 return true;
1476}
1477
Tobias Grosser75805372011-04-29 06:27:02 +00001478bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001479 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001480 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001481 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001482 return false;
1483
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001484 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001485 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001486 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001487 Region *TopRegion = RI->getTopLevelRegion();
1488
Tobias Grosser2ff87232011-10-23 11:17:06 +00001489 releaseMemory();
1490
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001491 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001492 return false;
1493
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001494 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001495 return false;
1496
1497 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001498
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001499 // Only makes sense when we tracked errors.
1500 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001501 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001502 emitMissedRemarksForLeaves(F, TopRegion);
1503 }
1504
Johannes Doerferta05214f2014-10-15 23:24:28 +00001505 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001506 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001507
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001508 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001509 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001510 return false;
1511}
1512
Johannes Doerfertba65c162015-02-24 11:45:21 +00001513bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1514 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001515 const DetectionContext *DC = getDetectionContext(ScopR);
1516 assert(DC && "ScopR is no valid region!");
1517 return DC->NonAffineSubRegionSet.count(SubR);
1518}
1519
1520const ScopDetection::DetectionContext *
1521ScopDetection::getDetectionContext(const Region *R) const {
1522 auto DCMIt = DetectionContextMap.find(R);
1523 if (DCMIt == DetectionContextMap.end())
1524 return nullptr;
1525 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001526}
1527
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001528const ScopDetection::BoxedLoopsSetTy *
1529ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001530 const DetectionContext *DC = getDetectionContext(R);
1531 assert(DC && "ScopR is no valid region!");
1532 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001533}
1534
Hongbin Zheng22623202016-02-15 00:20:58 +00001535const MapInsnToMemAcc *
1536ScopDetection::getInsnToMemAccMap(const Region *R) const {
1537 const DetectionContext *DC = getDetectionContext(R);
1538 assert(DC && "ScopR is no valid region!");
1539 return &DC->InsnToMemAcc;
1540}
1541
Johannes Doerfert09e36972015-10-07 20:17:36 +00001542const InvariantLoadsSetTy *
1543ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001544 const DetectionContext *DC = getDetectionContext(R);
1545 assert(DC && "ScopR is no valid region!");
1546 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001547}
1548
Tobias Grosser75805372011-04-29 06:27:02 +00001549void polly::ScopDetection::verifyRegion(const Region &R) const {
1550 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001551
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001552 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001553 isValidRegion(Context);
1554}
1555
1556void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001557 if (!VerifyScops)
1558 return;
1559
Tobias Grosser26108892014-04-02 20:18:19 +00001560 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001561 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001562}
1563
1564void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001565 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001566 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001567 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001568 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001569 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001570 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001571 AU.setPreservesAll();
1572}
1573
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001574void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001575 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001576 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001577
1578 OS << "\n";
1579}
1580
1581void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001582 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001583 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001584 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001585
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001586 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001587}
1588
1589char ScopDetection::ID = 0;
1590
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001591Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1592
Tobias Grosser73600b82011-10-08 00:30:40 +00001593INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1594 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001595 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001596INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001597INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001598INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001599INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001600INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001601INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1602 "Polly - Detect static control parts (SCoPs)", false, false)