blob: 02f515af13eb0eaca39bfa6c1d07a79cdadb3caa [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//
2// The LLVM Compiler Infrastructure
3//
4// This file is distributed under the University of Illinois Open Source
5// License. See LICENSE.TXT for details.
6//
7//===----------------------------------------------------------------------===//
8//
9// Detect the maximal Scops of a function.
10//
11// A static control part (Scop) is a subgraph of the control flow graph (CFG)
12// that only has statically known control flow and can therefore be described
13// within the polyhedral model.
14//
Michael Krusea6d48f52017-06-08 12:06:15 +000015// Every Scop fulfills these restrictions:
Tobias Grosser75805372011-04-29 06:27:02 +000016//
17// * It is a single entry single exit region
18//
19// * Only affine linear bounds in the loops
20//
21// Every natural loop in a Scop must have a number of loop iterations that can
22// be described as an affine linear function in surrounding loop iterators or
23// parameters. (A parameter is a scalar that does not change its value during
24// execution of the Scop).
25//
26// * Only comparisons of affine linear expressions in conditions
27//
28// * All loops and conditions perfectly nested
29//
30// The control flow needs to be structured such that it could be written using
31// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
32// 'continue'.
33//
34// * Side effect free functions call
35//
Johannes Doerfertcea61932016-02-21 19:13:19 +000036// Function calls and intrinsics that do not have side effects (readnone)
37// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000038//
39// The Scop detection finds the largest Scops by checking if the largest
40// region is a Scop. If this is not the case, its canonical subregions are
41// checked until a region is a Scop. It is now tried to extend this Scop by
42// creating a larger non canonical region.
43//
44//===----------------------------------------------------------------------===//
45
Tobias Grosser5624d3c2015-12-21 12:38:56 +000046#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000049#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000050#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000051#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000052#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include "llvm/ADT/Statistic.h"
54#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +000055#include "llvm/Analysis/Loads.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000057#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000058#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000059#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000060#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000061#include "llvm/IR/DiagnosticInfo.h"
62#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000063#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000064#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000065#include "llvm/Support/Debug.h"
Siddharth Bhate2699b52017-07-24 12:40:52 +000066#include "llvm/Support/Regex.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
Siddharth Bhat286c9162017-06-09 08:23:40 +000093static cl::list<std::string> OnlyFunctions(
Tobias Grosser483a90d2014-07-09 10:50:10 +000094 "polly-only-func",
Siddharth Bhate2699b52017-07-24 12:40:52 +000095 cl::desc("Only run on functions that match a regex. "
96 "Multiple regexes can be comma separated. "
97 "Scop detection will run on all functions that match "
98 "ANY of the regexes provided."),
Siddharth Bhat286c9162017-06-09 08:23:40 +000099 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000100
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000101static cl::list<std::string> IgnoredFunctions(
102 "polly-ignore-func",
103 cl::desc("Ignore functions that match a regex. "
104 "Multiple regexes can be comma separated. "
105 "Scop detection will ignore all functions that match "
106 "ANY of the regexes provided."),
107 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
108
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000109bool polly::PollyAllowFullFunction;
110static cl::opt<bool, true>
111 XAllowFullFunction("polly-detect-full-functions",
112 cl::desc("Allow the detection of full functions"),
113 cl::location(polly::PollyAllowFullFunction),
114 cl::init(false), cl::cat(PollyCategory));
Tobias Grosserd8945ba2017-05-19 12:13:02 +0000115
Tobias Grosser483a90d2014-07-09 10:50:10 +0000116static cl::opt<std::string> OnlyRegion(
117 "polly-only-region",
118 cl::desc("Only run on certain regions (The provided identifier must "
119 "appear in the name of the region's entry block"),
120 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
121 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000122
Tobias Grosser60cd9322011-11-10 12:47:26 +0000123static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000124 IgnoreAliasing("polly-ignore-aliasing",
125 cl::desc("Ignore possible aliasing of the array bases"),
126 cl::Hidden, cl::init(false), cl::ZeroOrMore,
127 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000128
Johannes Doerfertbda81432016-12-02 17:55:41 +0000129bool polly::PollyAllowUnsignedOperations;
130static cl::opt<bool, true> XPollyAllowUnsignedOperations(
131 "polly-allow-unsigned-operations",
132 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
133 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
134 cl::init(true), cl::cat(PollyCategory));
135
Johannes Doerfertb164c792014-09-18 11:17:17 +0000136bool polly::PollyUseRuntimeAliasChecks;
137static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
138 "polly-use-runtime-alias-checks",
139 cl::desc("Use runtime alias checks to resolve possible aliasing."),
140 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
141 cl::init(true), cl::cat(PollyCategory));
142
Tobias Grosser637bd632013-05-07 07:31:10 +0000143static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000144 ReportLevel("polly-report",
145 cl::desc("Print information about the activities of Polly"),
146 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000147
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000148static cl::opt<bool> AllowDifferentTypes(
149 "polly-allow-differing-element-types",
150 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000151 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000152
Tobias Grosser531891e2012-11-01 16:45:20 +0000153static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000154 AllowNonAffine("polly-allow-nonaffine",
155 cl::desc("Allow non affine access functions in arrays"),
156 cl::Hidden, cl::init(false), cl::ZeroOrMore,
157 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000158
Tobias Grosser898a6362016-03-23 06:40:15 +0000159static cl::opt<bool>
160 AllowModrefCall("polly-allow-modref-calls",
161 cl::desc("Allow functions with known modref behavior"),
162 cl::Hidden, cl::init(false), cl::ZeroOrMore,
163 cl::cat(PollyCategory));
164
Johannes Doerfertba65c162015-02-24 11:45:21 +0000165static cl::opt<bool> AllowNonAffineSubRegions(
166 "polly-allow-nonaffine-branches",
167 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000168 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000169
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000170static cl::opt<bool>
171 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
172 cl::desc("Allow non affine conditions for loops"),
173 cl::Hidden, cl::init(false), cl::ZeroOrMore,
174 cl::cat(PollyCategory));
175
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000176static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000177 TrackFailures("polly-detect-track-failures",
178 cl::desc("Track failure strings in detecting scop regions"),
179 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000180 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000181
Andreas Simbuerger04472402014-05-24 09:25:10 +0000182static cl::opt<bool> KeepGoing("polly-detect-keep-going",
183 cl::desc("Do not fail on the first error."),
184 cl::Hidden, cl::ZeroOrMore, cl::init(false),
185 cl::cat(PollyCategory));
186
Sebastian Pop18016682014-04-08 21:20:44 +0000187static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000188 PollyDelinearizeX("polly-delinearize",
189 cl::desc("Delinearize array access functions"),
190 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000191 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000192
Tobias Grossera1689932014-02-18 18:49:49 +0000193static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000194 VerifyScops("polly-detect-verify",
195 cl::desc("Verify the detected SCoPs after each transformation"),
196 cl::Hidden, cl::init(false), cl::ZeroOrMore,
197 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000198
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000199bool polly::PollyInvariantLoadHoisting;
200static cl::opt<bool, true> XPollyInvariantLoadHoisting(
201 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
202 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000203 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000204
Tobias Grosserc80d6972016-09-02 06:33:33 +0000205/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000206static const unsigned MIN_LOOP_TRIP_COUNT = 8;
207
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000208bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000209bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000210StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000211
Tobias Grosser75805372011-04-29 06:27:02 +0000212//===----------------------------------------------------------------------===//
213// Statistics.
214
Michael Kruse5b228bb2017-08-22 17:09:51 +0000215STATISTIC(NumTotalLoops, "Number of loops (in- or out of scops, in any "
216 "function processed by Polly)");
Tobias Grosserb45ae562016-11-26 07:37:46 +0000217STATISTIC(NumScopRegions, "Number of scops");
218STATISTIC(NumLoopsInScop, "Number of loops in scops");
219STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
220STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
221STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
222STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
223STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
224STATISTIC(NumScopsDepthLarger,
225 "Number of scops with maximal loop depth 6 and larger");
226STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
227STATISTIC(NumLoopsInProfScop,
228 "Number of loops in scops (profitable scops only)");
229STATISTIC(NumLoopsOverall, "Number of total loops");
230STATISTIC(NumProfScopsDepthOne,
231 "Number of scops with maximal loop depth 1 (profitable scops only)");
232STATISTIC(NumProfScopsDepthTwo,
233 "Number of scops with maximal loop depth 2 (profitable scops only)");
234STATISTIC(NumProfScopsDepthThree,
235 "Number of scops with maximal loop depth 3 (profitable scops only)");
236STATISTIC(NumProfScopsDepthFour,
237 "Number of scops with maximal loop depth 4 (profitable scops only)");
238STATISTIC(NumProfScopsDepthFive,
239 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000240STATISTIC(NumProfScopsDepthLarger,
241 "Number of scops with maximal loop depth 6 and larger "
242 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000243STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
244STATISTIC(MaxNumLoopsInProfScop,
245 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000246
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000247static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
248 bool OnlyProfitable);
249
Tobias Grosser8519f892013-12-18 10:49:53 +0000250class DiagnosticScopFound : public DiagnosticInfo {
251private:
252 static int PluginDiagnosticKind;
253
254 Function &F;
255 std::string FileName;
256 unsigned EntryLine, ExitLine;
257
258public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000259 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
260 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000261 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000262 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000263
264 virtual void print(DiagnosticPrinter &DP) const;
265
266 static bool classof(const DiagnosticInfo *DI) {
267 return DI->getKind() == PluginDiagnosticKind;
268 }
269};
270
Tobias Grosserdb6db502016-04-01 07:15:19 +0000271int DiagnosticScopFound::PluginDiagnosticKind =
272 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000273
Tobias Grosser8519f892013-12-18 10:49:53 +0000274void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000275 DP << "Polly detected an optimizable loop region (scop) in function '" << F
276 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000277
278 if (FileName.empty()) {
279 DP << "Scop location is unknown. Compile with debug info "
280 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000281 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000282 }
283
284 DP << FileName << ":" << EntryLine << ": Start of scop\n";
285 DP << FileName << ":" << ExitLine << ": End of scop";
286}
287
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000288/// Check if a string matches any regex in a list of regexes.
289/// @param Str the input string to match against.
290/// @param RegexList a list of strings that are regular expressions.
291static bool doesStringMatchAnyRegex(StringRef Str,
292 const cl::list<std::string> &RegexList) {
293 for (auto RegexStr : RegexList) {
Siddharth Bhate2699b52017-07-24 12:40:52 +0000294 Regex R(RegexStr);
295
296 std::string Err;
297 if (!R.isValid(Err))
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000298 report_fatal_error("invalid regex given as input to polly: " + Err, true);
Siddharth Bhate2699b52017-07-24 12:40:52 +0000299
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000300 if (R.match(Str))
Siddharth Bhat286c9162017-06-09 08:23:40 +0000301 return true;
Siddharth Bhate2699b52017-07-24 12:40:52 +0000302 }
Siddharth Bhat286c9162017-06-09 08:23:40 +0000303 return false;
304}
Tobias Grosser75805372011-04-29 06:27:02 +0000305//===----------------------------------------------------------------------===//
306// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000307
Michael Kruse5b228bb2017-08-22 17:09:51 +0000308static void countTotalLoops(Loop *L) {
309 NumTotalLoops++;
310 for (Loop *SubLoop : L->getSubLoops())
311 countTotalLoops(SubLoop);
312}
313
314static void countTotalLoops(LoopInfo &LI) {
315 for (Loop *L : LI)
316 countTotalLoops(L);
317}
318
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000319ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
320 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
Eli Friedmane737fc12017-07-17 23:58:33 +0000321 AliasAnalysis &AA, OptimizationRemarkEmitter &ORE)
322 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000323
324 if (!PollyProcessUnprofitable && LI.empty())
325 return;
326
327 Region *TopRegion = RI.getTopLevelRegion();
328
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000329 if (OnlyFunctions.size() > 0 &&
330 !doesStringMatchAnyRegex(F.getName(), OnlyFunctions))
331 return;
332
333 if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000334 return;
335
336 if (!isValidFunction(F))
337 return;
338
339 findScops(*TopRegion);
340
Michael Kruse5b228bb2017-08-22 17:09:51 +0000341 countTotalLoops(LI);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000342 NumScopRegions += ValidRegions.size();
343
344 // Prune non-profitable regions.
345 for (auto &DIt : DetectionContextMap) {
346 auto &DC = DIt.getSecond();
347 if (DC.Log.hasErrors())
348 continue;
349 if (!ValidRegions.count(&DC.CurRegion))
350 continue;
351 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
352 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
353 if (isProfitableRegion(DC)) {
354 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
355 continue;
356 }
357
358 ValidRegions.remove(&DC.CurRegion);
359 }
360
361 NumProfScopRegions += ValidRegions.size();
362 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
363
364 // Only makes sense when we tracked errors.
365 if (PollyTrackFailures)
366 emitMissedRemarks(F);
367
368 if (ReportLevel)
369 printLocations(F);
370
371 assert(ValidRegions.size() <= DetectionContextMap.size() &&
372 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000373}
374
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000375template <class RR, typename... Args>
376inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
377 Args &&... Arguments) const {
378
379 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000380 RejectLog &Log = Context.Log;
381 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000382
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000383 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000384 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000385
386 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000387 DEBUG(dbgs() << "\n");
388 } else {
389 assert(!Assert && "Verification of detected scop failed");
390 }
391
392 return false;
393}
394
Tobias Grossera1689932014-02-18 18:49:49 +0000395bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
396 if (!ValidRegions.count(&R))
397 return false;
398
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000399 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000400 DetectionContextMap.erase(getBBPairForRegion(&R));
401 const auto &It = DetectionContextMap.insert(std::make_pair(
402 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000403 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000404 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000405 return isValidRegion(Context);
406 }
Tobias Grossera1689932014-02-18 18:49:49 +0000407
408 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000409}
410
Tobias Grosser4f129a62011-10-08 00:30:55 +0000411std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000412 // Get the first error we found. Even in keep-going mode, this is the first
413 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000414 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000415
416 // This can happen when we marked a region invalid, but didn't track
417 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000418 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000419 return "";
420
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000421 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000422 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000423}
424
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000425bool ScopDetection::addOverApproximatedRegion(Region *AR,
426 DetectionContext &Context) const {
427
428 // If we already know about Ar we can exit.
429 if (!Context.NonAffineSubRegionSet.insert(AR))
430 return true;
431
432 // All loops in the region have to be overapproximated too if there
433 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000434
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000435 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000436 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000437 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000438 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000439 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000440
441 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000442}
443
Johannes Doerfert09e36972015-10-07 20:17:36 +0000444bool ScopDetection::onlyValidRequiredInvariantLoads(
445 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
446 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000447 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000448
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000449 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
450 return false;
451
Tobias Grosser1c787e02017-03-02 12:15:37 +0000452 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000453 // If we already know a load has been accepted as required invariant, we
454 // already run the validation below once and consequently don't need to
455 // run it again. Hence, we return early. For certain test cases (e.g.,
456 // COSMO this avoids us spending 50% of scop-detection time in this
457 // very function (and its children).
458 if (Context.RequiredILS.count(Load))
459 continue;
460
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000461 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000462 return false;
463
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000464 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
465
466 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
467 Load->getAlignment(), DL))
468 continue;
469
Tobias Grosser1c787e02017-03-02 12:15:37 +0000470 if (NonAffineRegion->contains(Load) &&
471 Load->getParent() != NonAffineRegion->getEntry())
472 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000473 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000474 }
475
Johannes Doerfert09e36972015-10-07 20:17:36 +0000476 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
477
478 return true;
479}
480
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000481bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
482 Loop *Scope) const {
483 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000484 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000485 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000486 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000487
488 SmallPtrSet<Value *, 8> PtrVals;
489 for (auto *V : Values) {
490 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
491 V = P2I->getOperand(0);
492
493 if (!V->getType()->isPointerTy())
494 continue;
495
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000496 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000497 if (isa<SCEVConstant>(PtrSCEV))
498 continue;
499
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000500 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000501 if (!BasePtr)
502 return true;
503
504 auto *BasePtrVal = BasePtr->getValue();
505 if (PtrVals.insert(BasePtrVal).second) {
506 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000507 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000508 return true;
509 }
510 }
511
512 return false;
513}
514
Michael Kruse09eb4452016-03-03 22:10:47 +0000515bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000516 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000517
518 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000519 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000520 return false;
521
522 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
523 return false;
524
525 return true;
526}
527
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000528bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000529 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000530 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000531 Loop *L = LI.getLoopFor(&BB);
532 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000533
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000534 if (IsLoopBranch && L->isLoopLatch(&BB))
535 return false;
536
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000537 // Check for invalid usage of different pointers in one expression.
538 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
539 return false;
540
Michael Kruse09eb4452016-03-03 22:10:47 +0000541 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000542 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000543
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000544 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000545 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000546 return true;
547
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000548 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
549 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000550}
551
552bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000553 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000554 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000555
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000556 // Constant integer conditions are always affine.
557 if (isa<ConstantInt>(Condition))
558 return true;
559
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000560 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
561 auto Opcode = BinOp->getOpcode();
562 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
563 Value *Op0 = BinOp->getOperand(0);
564 Value *Op1 = BinOp->getOperand(1);
565 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
566 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
567 }
568 }
569
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000570 // Non constant conditions of branches need to be ICmpInst.
571 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000572 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000573 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000574 return true;
575 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000576 }
Tobias Grosser75805372011-04-29 06:27:02 +0000577
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000578 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000579
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000580 // Are both operands of the ICmp affine?
581 if (isa<UndefValue>(ICmp->getOperand(0)) ||
582 isa<UndefValue>(ICmp->getOperand(1)))
583 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000584
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000585 Loop *L = LI.getLoopFor(&BB);
586 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
587 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000588
Johannes Doerfertbda81432016-12-02 17:55:41 +0000589 // If unsigned operations are not allowed try to approximate the region.
590 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
591 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000592 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000593
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000594 // Check for invalid usage of different pointers in one expression.
595 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
596 involvesMultiplePtrs(RHS, nullptr, L))
597 return false;
598
599 // Check for invalid usage of different pointers in a relational comparison.
600 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
601 return false;
602
Michael Kruse09eb4452016-03-03 22:10:47 +0000603 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000604 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000605
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000606 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000607 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000608 return true;
609
610 if (IsLoopBranch)
611 return false;
612
613 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
614 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000615}
616
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000617bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000618 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000619 DetectionContext &Context) const {
620 Region &CurRegion = Context.CurRegion;
621
622 TerminatorInst *TI = BB.getTerminator();
623
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000624 if (AllowUnreachable && isa<UnreachableInst>(TI))
625 return true;
626
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000627 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000628 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000629 return true;
630
631 Value *Condition = getConditionFromTerminator(TI);
632
633 if (!Condition)
634 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
635
636 // UndefValue is not allowed as condition.
637 if (isa<UndefValue>(Condition))
638 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
639
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000640 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000641 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000642
643 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
644 assert(SI && "Terminator was neither branch nor switch");
645
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000646 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000647}
648
Johannes Doerfertcea61932016-02-21 19:13:19 +0000649bool ScopDetection::isValidCallInst(CallInst &CI,
650 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000651 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000652 return false;
653
654 if (CI.doesNotAccessMemory())
655 return true;
656
Johannes Doerfertcea61932016-02-21 19:13:19 +0000657 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000658 if (isValidIntrinsicInst(*II, Context))
659 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000660
Tobias Grosser75805372011-04-29 06:27:02 +0000661 Function *CalledFunction = CI.getCalledFunction();
662
663 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000664 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000665 return false;
666
Tobias Grosser898a6362016-03-23 06:40:15 +0000667 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000668 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000669 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000670 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000671 case FMRB_DoesNotAccessMemory:
672 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000673 // Implicitly disable delinearization since we have an unknown
674 // accesses with an unknown access function.
675 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000676 Context.AST.add(&CI);
677 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000678 case FMRB_OnlyReadsArgumentPointees:
679 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000680 for (const auto &Arg : CI.arg_operands()) {
681 if (!Arg->getType()->isPointerTy())
682 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000683
Tobias Grosser898a6362016-03-23 06:40:15 +0000684 // Bail if a pointer argument has a base address not known to
685 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000686 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000687 if (ArgSCEV->isZero())
688 continue;
689
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000690 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000691 if (!BP)
692 return false;
693
694 // Implicitly disable delinearization since we have an unknown
695 // accesses with an unknown access function.
696 Context.HasUnknownAccess = true;
697 }
698
699 Context.AST.add(&CI);
700 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000701 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000702 case FMRB_OnlyAccessesInaccessibleMem:
703 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000704 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000705 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000706 }
707
Johannes Doerfertcea61932016-02-21 19:13:19 +0000708 return false;
709}
710
711bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
712 DetectionContext &Context) const {
713 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000714 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000715
Johannes Doerfertcea61932016-02-21 19:13:19 +0000716 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000717 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000718
719 // The access function and base pointer for memory intrinsics.
720 const SCEV *AF;
721 const SCEVUnknown *BP;
722
723 switch (II.getIntrinsicID()) {
724 // Memory intrinsics that can be represented are supported.
725 case llvm::Intrinsic::memmove:
726 case llvm::Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000727 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000728 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000729 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000730 // Bail if the source pointer is not valid.
731 if (!isValidAccess(&II, AF, BP, Context))
732 return false;
733 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000734 // Fall through
735 case llvm::Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000736 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000737 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000738 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000739 // Bail if the destination pointer is not valid.
740 if (!isValidAccess(&II, AF, BP, Context))
741 return false;
742 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000743
744 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000745 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000746 Context))
747 return false;
748
749 return true;
750 default:
751 break;
752 }
753
Tobias Grosser75805372011-04-29 06:27:02 +0000754 return false;
755}
756
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000757bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
758 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000759 // A reference to function argument or constant value is invariant.
760 if (isa<Argument>(Val) || isa<Constant>(Val))
761 return true;
762
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000763 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000764 if (!I)
765 return false;
766
767 if (!Reg.contains(I))
768 return true;
769
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000770 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
771 // is not hoistable, it will be rejected later, but here we assume it is and
772 // that makes the value invariant.
773 if (auto LI = dyn_cast<LoadInst>(I)) {
774 Ctx.RequiredILS.insert(LI);
775 return true;
776 }
777
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000778 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000779}
780
Tobias Grosserc80d6972016-09-02 06:33:33 +0000781/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000782/// register the '...' components.
783///
Michael Krusea6d48f52017-06-08 12:06:15 +0000784/// Array access expressions as they are generated by GFortran contain smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000785/// size) expressions that confuse the 'normal' delinearization algorithm.
786/// However, if we extract such expressions before the normal delinearization
787/// takes place they can actually help to identify array size expressions in
Michael Krusea6d48f52017-06-08 12:06:15 +0000788/// Fortran accesses. For the subsequently following delinearization the smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000789/// size) component can be replaced by just 'size'. This is correct as we will
790/// always add and verify the assumption that for all subscript expressions
791/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
792/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000793class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000794public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000795 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
796 std::vector<const SCEV *> *Terms = nullptr) {
797 SCEVRemoveMax Rewriter(SE, Terms);
798 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000799 }
800
801 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000802 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000803
804 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000805 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000806 auto Res = visit(Expr->getOperand(1));
807 if (Terms)
808 (*Terms).push_back(Res);
809 return Res;
810 }
811
812 return Expr;
813 }
814
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000815private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000816 std::vector<const SCEV *> *Terms;
817};
818
Tobias Grosserd68ba422015-11-24 05:00:36 +0000819SmallVector<const SCEV *, 4>
820ScopDetection::getDelinearizationTerms(DetectionContext &Context,
821 const SCEVUnknown *BasePointer) const {
822 SmallVector<const SCEV *, 4> Terms;
823 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000824 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000825 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000826 if (MaxTerms.size() > 0) {
827 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
828 continue;
829 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000830 // In case the outermost expression is a plain add, we check if any of its
831 // terms has the form 4 * %inst * %param * %param ..., aka a term that
832 // contains a product between a parameter and an instruction that is
833 // inside the scop. Such instructions, if allowed at all, are instructions
834 // SCEV can not represent, but Polly is still looking through. As a
835 // result, these instructions can depend on induction variables and are
836 // most likely no array sizes. However, terms that are multiplied with
837 // them are likely candidates for array sizes.
838 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
839 for (auto Op : AF->operands()) {
840 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000841 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000842 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
843 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000844
Tobias Grosserd68ba422015-11-24 05:00:36 +0000845 for (auto *MulOp : AF2->operands()) {
846 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
847 Operands.push_back(Const);
848 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
849 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
850 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000851 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000852
853 } else {
854 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000855 }
856 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000857 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000858 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000859 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000860 }
861 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000862 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000863 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000864 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000865 }
866 return Terms;
867}
Sebastian Pope8863b82014-05-12 19:02:02 +0000868
Tobias Grosserd68ba422015-11-24 05:00:36 +0000869bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
870 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000871 const SCEVUnknown *BasePointer,
872 Loop *Scope) const {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000873 // If no sizes were found, all sizes are trivially valid. We allow this case
874 // to make it possible to pass known-affine accesses to the delinearization to
875 // try to recover some interesting multi-dimensional accesses, but to still
876 // allow the already known to be affine access in case the delinearization
877 // fails. In such situations, the delinearization will just return a Sizes
878 // array of size zero.
879 if (Sizes.size() == 0)
880 return true;
881
Tobias Grosserd68ba422015-11-24 05:00:36 +0000882 Value *BaseValue = BasePointer->getValue();
883 Region &CurRegion = Context.CurRegion;
884 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000885 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000886 Sizes.clear();
887 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000888 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000889 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
890 auto *V = dyn_cast<Value>(Unknown->getValue());
891 if (auto *Load = dyn_cast<LoadInst>(V)) {
892 if (Context.CurRegion.contains(Load) &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000893 isHoistableLoad(Load, CurRegion, LI, SE, DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000894 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000895 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000896 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000897 }
Siddharth Bhata1b20862017-07-13 12:18:56 +0000898 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
899 Context.RequiredILS))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000900 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000901 Context, /*Assert=*/true, DelinearizedSize,
902 Context.Accesses[BasePointer].front().first, BaseValue);
903 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000904
Tobias Grosserd68ba422015-11-24 05:00:36 +0000905 // No array shape derived.
906 if (Sizes.empty()) {
907 if (AllowNonAffine)
908 return true;
909
Tobias Grosser230acc42014-09-13 14:47:55 +0000910 for (const auto &Pair : Context.Accesses[BasePointer]) {
911 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000912 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000913
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000914 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000915 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
916 BaseValue);
917 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000918 return false;
919 }
920 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000921 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000922 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000923 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000924}
925
Tobias Grosserd68ba422015-11-24 05:00:36 +0000926// We first store the resulting memory accesses in TempMemoryAccesses. Only
927// if the access functions for all memory accesses have been successfully
928// delinearized we continue. Otherwise, we either report a failure or, if
929// non-affine accesses are allowed, we drop the information. In case the
930// information is dropped the memory accesses need to be overapproximated
931// when translated to a polyhedral representation.
932bool ScopDetection::computeAccessFunctions(
933 DetectionContext &Context, const SCEVUnknown *BasePointer,
934 std::shared_ptr<ArrayShape> Shape) const {
935 Value *BaseValue = BasePointer->getValue();
936 bool BasePtrHasNonAffine = false;
937 MapInsnToMemAcc TempMemoryAccesses;
938 for (const auto &Pair : Context.Accesses[BasePointer]) {
939 const Instruction *Insn = Pair.first;
940 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000941 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000942 bool IsNonAffine = false;
943 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
944 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000945 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000946
947 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000948 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000949 Acc->DelinearizedSubscripts.push_back(Pair.second);
950 else
951 IsNonAffine = true;
952 } else {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000953 if (Shape->DelinearizedSizes.size() == 0) {
954 Acc->DelinearizedSubscripts.push_back(AF);
955 } else {
956 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
957 Shape->DelinearizedSizes);
958 if (Acc->DelinearizedSubscripts.size() == 0)
959 IsNonAffine = true;
960 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000961 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000962 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000963 IsNonAffine = true;
964 }
965
966 // (Possibly) report non affine access
967 if (IsNonAffine) {
968 BasePtrHasNonAffine = true;
969 if (!AllowNonAffine)
970 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
971 Insn, BaseValue);
972 if (!KeepGoing && !AllowNonAffine)
973 return false;
974 }
975 }
976
977 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000978 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
979 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000980
981 return true;
982}
983
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000984bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
985 const SCEVUnknown *BasePointer,
986 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000987 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
988
989 auto Terms = getDelinearizationTerms(Context, BasePointer);
990
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000991 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
992 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000993
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000994 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
995 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000996 return false;
997
998 return computeAccessFunctions(Context, BasePointer, Shape);
999}
1000
1001bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +00001002 // TODO: If we have an unknown access and other non-affine accesses we do
1003 // not try to delinearize them for now.
1004 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
1005 return AllowNonAffine;
1006
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001007 for (auto &Pair : Context.NonAffineAccesses) {
1008 auto *BasePointer = Pair.first;
1009 auto *Scope = Pair.second;
1010 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +00001011 if (KeepGoing)
1012 continue;
1013 else
1014 return false;
1015 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001016 }
Tobias Grosserd68ba422015-11-24 05:00:36 +00001017 return true;
1018}
1019
Johannes Doerfertcea61932016-02-21 19:13:19 +00001020bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1021 const SCEVUnknown *BP,
1022 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001023
Johannes Doerfertcea61932016-02-21 19:13:19 +00001024 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +00001025 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001026
Johannes Doerfertcea61932016-02-21 19:13:19 +00001027 auto *BV = BP->getValue();
1028 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +00001029 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001030
Johannes Doerfertcea61932016-02-21 19:13:19 +00001031 // FIXME: Think about allowing IntToPtrInst
1032 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1033 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1034
Tobias Grosser458fb782014-01-28 12:58:58 +00001035 // Check that the base address of the access is invariant in the current
1036 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +00001037 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001038 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +00001039
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001040 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001041
Johannes Doerfertcea61932016-02-21 19:13:19 +00001042 const SCEV *Size;
1043 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001044 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001045 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001046 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001047 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1048 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001049 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +00001050
Johannes Doerfertcea61932016-02-21 19:13:19 +00001051 if (Context.ElementSize[BP]) {
1052 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1053 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1054 Inst, BV);
1055
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001056 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001057 } else {
1058 Context.ElementSize[BP] = Size;
1059 }
1060
1061 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001062 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001063 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001064 for (const Loop *L : Loops)
1065 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001066 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001067
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001068 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001069 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001070 // Do not try to delinearize memory intrinsics and force them to be affine.
1071 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1072 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1073 BV);
1074 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1075 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001076
Tobias Grosser1e55db32017-05-27 15:18:53 +00001077 if (!IsAffine || hasIVParams(AF))
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001078 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001079 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001080 } else if (!AllowNonAffine && !IsAffine) {
1081 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1082 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001083 }
Tobias Grosser75805372011-04-29 06:27:02 +00001084
Tobias Grosser1eedb672014-09-24 21:04:29 +00001085 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001086 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001087
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001088 // Check if the base pointer of the memory access does alias with
1089 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001090 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001091 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001092 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +00001093 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +00001094
Tobias Grosser1eedb672014-09-24 21:04:29 +00001095 if (!AS.isMustAlias()) {
1096 if (PollyUseRuntimeAliasChecks) {
1097 bool CanBuildRunTimeCheck = true;
1098 // The run-time alias check places code that involves the base pointer at
1099 // the beginning of the SCoP. This breaks if the base pointer is defined
1100 // inside the scop. Hence, we can only create a run-time check if we are
1101 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001102 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +00001103 for (const auto &Ptr : AS) {
1104 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001105 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001106 auto *Load = dyn_cast<LoadInst>(Inst);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001107 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001108 Context.RequiredILS.insert(Load);
1109 continue;
1110 }
1111
Tobias Grosser1eedb672014-09-24 21:04:29 +00001112 CanBuildRunTimeCheck = false;
1113 break;
1114 }
1115 }
1116
1117 if (CanBuildRunTimeCheck)
1118 return true;
1119 }
Michael Kruse70131d32016-01-27 17:09:17 +00001120 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001121 }
Tobias Grosser75805372011-04-29 06:27:02 +00001122
1123 return true;
1124}
1125
Johannes Doerfertcea61932016-02-21 19:13:19 +00001126bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1127 DetectionContext &Context) const {
1128 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001129 Loop *L = LI.getLoopFor(Inst->getParent());
1130 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001131 const SCEVUnknown *BasePointer;
1132
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001133 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001134
1135 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1136}
1137
Tobias Grosser75805372011-04-29 06:27:02 +00001138bool ScopDetection::isValidInstruction(Instruction &Inst,
1139 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001140 for (auto &Op : Inst.operands()) {
1141 auto *OpInst = dyn_cast<Instruction>(&Op);
1142
1143 if (!OpInst)
1144 continue;
1145
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001146 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT))
Tobias Grosserb12b0062015-11-11 12:44:18 +00001147 return false;
1148 }
1149
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001150 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1151 return false;
1152
Tobias Grosser75805372011-04-29 06:27:02 +00001153 // We only check the call instruction but not invoke instruction.
1154 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001155 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001156 return true;
1157
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001158 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001159 }
1160
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001161 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001162 if (!isa<AllocaInst>(Inst))
1163 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001164
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001165 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001166 }
1167
1168 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001169 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001170 Context.hasStores |= isa<StoreInst>(MemInst);
1171 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001172 if (!MemInst.isSimple())
1173 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1174 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001175
Michael Kruse70131d32016-01-27 17:09:17 +00001176 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001177 }
Tobias Grosser75805372011-04-29 06:27:02 +00001178
1179 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001180 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001181}
1182
Johannes Doerfertd020b772015-08-27 06:53:52 +00001183bool ScopDetection::canUseISLTripCount(Loop *L,
1184 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001185 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1186 // need to overapproximate it as a boxed loop.
1187 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001188 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001189 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001190 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001191 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001192 return false;
1193 }
1194
Johannes Doerfertd020b772015-08-27 06:53:52 +00001195 // We can use ISL to compute the trip count of L.
1196 return true;
1197}
1198
Tobias Grosser75805372011-04-29 06:27:02 +00001199bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001200 // Loops that contain part but not all of the blocks of a region cannot be
1201 // handled by the schedule generation. Such loop constructs can happen
1202 // because a region can contain BBs that have no path to the exit block
Jakub Kuderski0ac1e582017-08-22 22:01:53 +00001203 // (infinite loops, UnreachableInst).
1204 // We do not have to verify against infinite loops here -- they are
1205 // postdominated only by the virtual exit and do not appear in regions.
1206 // Instead of an infinite loop, a dead end can also be formed by an
1207 // UnreachableInst. This case is already caught by isErrorBlock().
1208
1209#ifndef NDEBUG
1210 // Make sure that the loop has exits (i.e. is not infinite).
1211 SmallVector<BasicBlock *, 4> ExitingBlocks;
1212 L->getExitingBlocks(ExitingBlocks);
1213 assert(!ExitingBlocks.empty() && "Region with an infinite loop found!");
1214#endif
Tobias Grosser349d1c32016-09-20 17:05:22 +00001215
Johannes Doerfertf61df692015-10-04 14:56:08 +00001216 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001217 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001218
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001219 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001220 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001221 while (R != &Context.CurRegion && !R->contains(L))
1222 R = R->getParent();
1223
1224 if (addOverApproximatedRegion(R, Context))
1225 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001226 }
Tobias Grosser75805372011-04-29 06:27:02 +00001227
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001228 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001229 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001230}
1231
Tobias Grosserc80d6972016-09-02 06:33:33 +00001232/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001233/// count that is not known to be less than @MinProfitableTrips.
1234ScopDetection::LoopStats
1235ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001236 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001237 auto *TripCount = SE.getBackedgeTakenCount(L);
1238
Tobias Grosserb45ae562016-11-26 07:37:46 +00001239 int NumLoops = 1;
1240 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001241 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001242 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001243 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1244 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001245
Tobias Grosserb45ae562016-11-26 07:37:46 +00001246 for (auto &SubLoop : *L) {
1247 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1248 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001249 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001250 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001251
Tobias Grosserb45ae562016-11-26 07:37:46 +00001252 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001253}
1254
Tobias Grosserb45ae562016-11-26 07:37:46 +00001255ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001256ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1257 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001258 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001259 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001260
Tobias Grossercd01a362017-02-17 08:12:36 +00001261 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001262 L = L ? R->outermostLoopInRegion(L) : nullptr;
1263 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001264
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001265 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001266 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001267
1268 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001269 if (R->contains(SubLoop)) {
1270 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001271 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001272 LoopNum += Stats.NumLoops;
1273 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1274 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001275
Tobias Grosserb45ae562016-11-26 07:37:46 +00001276 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001277}
1278
Tobias Grosser75805372011-04-29 06:27:02 +00001279Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001280 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001281 std::unique_ptr<Region> LastValidRegion;
1282 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001283
1284 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1285
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001286 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001287 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001288 getBBPairForRegion(ExpandedRegion.get()),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001289 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001290 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001291 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001292 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001293
Johannes Doerfert717b8662015-09-08 21:44:27 +00001294 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001295 // If the exit is valid check all blocks
1296 // - if true, a valid region was found => store it + keep expanding
1297 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001298 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1299 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001300 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001301 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001302 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001303
Tobias Grosserd7e58642013-04-10 06:55:45 +00001304 // Store this region, because it is the greatest valid (encountered so
1305 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001306 if (LastValidRegion) {
1307 removeCachedResults(*LastValidRegion);
1308 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1309 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001310 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001311
1312 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001313 ExpandedRegion =
1314 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001315
1316 } else {
1317 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001318 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001319 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001320 ExpandedRegion =
1321 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001322 }
Tobias Grosser75805372011-04-29 06:27:02 +00001323 }
1324
Tobias Grosser378a9f22013-11-16 19:34:11 +00001325 DEBUG({
1326 if (LastValidRegion)
1327 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1328 else
1329 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1330 });
Tobias Grosser75805372011-04-29 06:27:02 +00001331
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001332 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001333}
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001334static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001335 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001336 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001337 return false;
1338
1339 return true;
1340}
Tobias Grosser75805372011-04-29 06:27:02 +00001341
Tobias Grosserb45ae562016-11-26 07:37:46 +00001342void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001343 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001344 if (ValidRegions.count(SubRegion.get())) {
1345 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001346 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001347 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001348 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001349}
1350
Johannes Doerferte46925f2015-10-01 10:59:14 +00001351void ScopDetection::removeCachedResults(const Region &R) {
1352 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001353}
1354
Tobias Grosser75805372011-04-29 06:27:02 +00001355void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001356 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001357 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001358 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001359
1360 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001361 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001362 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001363 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001364 RegionIsValid = isValidRegion(Context);
1365
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001366 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001367
Johannes Doerferte46925f2015-10-01 10:59:14 +00001368 if (HasErrors) {
1369 removeCachedResults(R);
1370 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001371 ValidRegions.insert(&R);
1372 return;
1373 }
1374
David Blaikieb035f6d2014-04-15 18:45:27 +00001375 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001376 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001377
1378 // Try to expand regions.
1379 //
1380 // As the region tree normally only contains canonical regions, non canonical
1381 // regions that form a Scop are not found. Therefore, those non canonical
1382 // regions are checked by expanding the canonical ones.
1383
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001384 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001385
David Blaikieb035f6d2014-04-15 18:45:27 +00001386 for (auto &SubRegion : R)
1387 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001388
Tobias Grosser26108892014-04-02 20:18:19 +00001389 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001390 // Skip invalid regions. Regions may become invalid, if they are element of
1391 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001392 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001393 continue;
1394
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001395 // Skip regions that had errors.
1396 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1397 if (HadErrors)
1398 continue;
1399
Tobias Grosser75805372011-04-29 06:27:02 +00001400 Region *ExpandedR = expandRegion(*CurrentRegion);
1401
1402 if (!ExpandedR)
1403 continue;
1404
1405 R.addSubRegion(ExpandedR, true);
1406 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001407 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001408 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001409 }
1410}
1411
1412bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001413 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001414
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001415 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001416 Loop *L = LI.getLoopFor(BB);
Tobias Grossera3aa4232017-07-15 22:42:17 +00001417 if (L && L->getHeader() == BB) {
1418 if (CurRegion.contains(L)) {
1419 if (!isValidLoop(L, Context) && !KeepGoing)
1420 return false;
1421 } else {
1422 SmallVector<BasicBlock *, 1> Latches;
1423 L->getLoopLatches(Latches);
1424 for (BasicBlock *Latch : Latches)
1425 if (CurRegion.contains(Latch))
1426 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1427 L);
1428 }
1429 }
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001430 }
1431
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001432 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001433 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001434
1435 // Also check exception blocks (and possibly register them as non-affine
1436 // regions). Even though exception blocks are not modeled, we use them
1437 // to forward-propagate domain constraints during ScopInfo construction.
1438 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1439 return false;
1440
1441 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001442 continue;
1443
Tobias Grosser1d191902014-03-03 13:13:55 +00001444 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001445 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001446 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001447 }
Tobias Grosser75805372011-04-29 06:27:02 +00001448
Sebastian Pope8863b82014-05-12 19:02:02 +00001449 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001450 return false;
1451
Tobias Grosser75805372011-04-29 06:27:02 +00001452 return true;
1453}
1454
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001455bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1456 int NumLoops) const {
1457 int InstCount = 0;
1458
Tobias Grosserb316dc12016-09-08 14:08:05 +00001459 if (NumLoops == 0)
1460 return false;
1461
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001462 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001463 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001464 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001465
1466 InstCount = InstCount / NumLoops;
1467
1468 return InstCount >= ProfitabilityMinPerLoopInstructions;
1469}
1470
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001471bool ScopDetection::hasPossiblyDistributableLoop(
1472 DetectionContext &Context) const {
1473 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001474 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001475 if (!Context.CurRegion.contains(L))
1476 continue;
1477 if (Context.BoxedLoopsSet.count(L))
1478 continue;
1479 unsigned StmtsWithStoresInLoops = 0;
1480 for (auto *LBB : L->blocks()) {
1481 bool MemStore = false;
1482 for (auto &I : *LBB)
1483 MemStore |= isa<StoreInst>(&I);
1484 StmtsWithStoresInLoops += MemStore;
1485 }
1486 return (StmtsWithStoresInLoops > 1);
1487 }
1488 return false;
1489}
1490
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001491bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1492 Region &CurRegion = Context.CurRegion;
1493
1494 if (PollyProcessUnprofitable)
1495 return true;
1496
1497 // We can probably not do a lot on scops that only write or only read
1498 // data.
1499 if (!Context.hasStores || !Context.hasLoads)
1500 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1501
Tobias Grossercd01a362017-02-17 08:12:36 +00001502 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001503 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001504 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001505
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001506 // Scops with at least two loops may allow either loop fusion or tiling and
1507 // are consequently interesting to look at.
1508 if (NumAffineLoops >= 2)
1509 return true;
1510
Michael Krusea6d48f52017-06-08 12:06:15 +00001511 // A loop with multiple non-trivial blocks might be amendable to distribution.
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001512 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1513 return true;
1514
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001515 // Scops that contain a loop with a non-trivial amount of computation per
1516 // loop-iteration are interesting as we may be able to parallelize such
1517 // loops. Individual loops that have only a small amount of computation
1518 // per-iteration are performance-wise very fragile as any change to the
1519 // loop induction variables may affect performance. To not cause spurious
1520 // performance regressions, we do not consider such loops.
1521 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1522 return true;
1523
1524 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001525}
1526
Tobias Grosser75805372011-04-29 06:27:02 +00001527bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001528 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001529
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001530 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001531
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001532 if (!PollyAllowFullFunction && CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001533 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001534 return false;
1535 }
1536
Tobias Grosser134a5722017-03-07 15:50:43 +00001537 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001538 if (CurRegion.getExit() &&
1539 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Tobias Grosser134a5722017-03-07 15:50:43 +00001540 DEBUG(dbgs() << "Unreachable in exit\n");
1541 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1542 CurRegion.getExit(), DbgLoc);
1543 }
1544
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001545 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001546 DEBUG({
1547 dbgs() << "Region entry does not match -polly-region-only";
1548 dbgs() << "\n";
1549 });
1550 return false;
1551 }
1552
Tobias Grosserd654c252012-04-10 18:12:19 +00001553 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001554 // to insert alloca instruction there when translate scalar to array.
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001555 if (!PollyAllowFullFunction &&
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001556 CurRegion.getEntry() ==
1557 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001558 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001559
Hongbin Zheng94868e62012-04-07 12:29:17 +00001560 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001561 return false;
1562
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001563 if (!isReducibleRegion(CurRegion, DbgLoc))
1564 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1565 &CurRegion, DbgLoc);
1566
Tobias Grosser75805372011-04-29 06:27:02 +00001567 DEBUG(dbgs() << "OK\n");
1568 return true;
1569}
1570
Tobias Grosser629109b2016-08-03 12:00:07 +00001571void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001572 F->addFnAttr(PollySkipFnAttr);
1573}
1574
Tobias Grosser75805372011-04-29 06:27:02 +00001575bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001576 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001577}
1578
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001579void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001580 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001581 unsigned LineEntry, LineExit;
1582 std::string FileName;
1583
Tobias Grosser00dc3092014-03-02 12:02:46 +00001584 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001585 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1586 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001587 }
1588}
1589
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001590void ScopDetection::emitMissedRemarks(const Function &F) {
1591 for (auto &DIt : DetectionContextMap) {
1592 auto &DC = DIt.getSecond();
1593 if (DC.Log.hasErrors())
Eli Friedmane737fc12017-07-17 23:58:33 +00001594 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001595 }
1596}
1597
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001598bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001599 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001600 ///
1601 /// WHITE - Unvisited BB in DFS walk.
1602 /// GREY - BBs which are currently on the DFS stack for processing.
1603 /// BLACK - Visited and completely processed BB.
1604 enum Color { WHITE, GREY, BLACK };
1605
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001606 BasicBlock *REntry = R.getEntry();
1607 BasicBlock *RExit = R.getExit();
1608 // Map to match the color of a BasicBlock during the DFS walk.
1609 DenseMap<const BasicBlock *, Color> BBColorMap;
1610 // Stack keeping track of current BB and index of next child to be processed.
1611 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1612
1613 unsigned AdjacentBlockIndex = 0;
1614 BasicBlock *CurrBB, *SuccBB;
1615 CurrBB = REntry;
1616
1617 // Initialize the map for all BB with WHITE color.
1618 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001619 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001620
1621 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001622 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001623 DFSStack.push(std::make_pair(CurrBB, 0));
1624
1625 while (!DFSStack.empty()) {
1626 // Get next BB on stack to be processed.
1627 CurrBB = DFSStack.top().first;
1628 AdjacentBlockIndex = DFSStack.top().second;
1629 DFSStack.pop();
1630
1631 // Loop to iterate over the successors of current BB.
1632 const TerminatorInst *TInst = CurrBB->getTerminator();
1633 unsigned NSucc = TInst->getNumSuccessors();
1634 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1635 ++I, ++AdjacentBlockIndex) {
1636 SuccBB = TInst->getSuccessor(I);
1637
1638 // Checks for region exit block and self-loops in BB.
1639 if (SuccBB == RExit || SuccBB == CurrBB)
1640 continue;
1641
1642 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001643 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001644 // Push the current BB and the index of the next child to be visited.
1645 DFSStack.push(std::make_pair(CurrBB, I + 1));
1646 // Push the next BB to be processed.
1647 DFSStack.push(std::make_pair(SuccBB, 0));
1648 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001649 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001650 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001651 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001652 // GREY indicates a loop in the control flow.
1653 // If the destination dominates the source, it is a natural loop
1654 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001655 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001656 // Get debug info of instruction which causes irregular control flow.
1657 DbgLoc = TInst->getDebugLoc();
1658 return false;
1659 }
1660 }
1661 }
1662
1663 // If all children of current BB have been processed,
1664 // then mark that BB as fully processed.
1665 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001666 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001667 }
1668
1669 return true;
1670}
1671
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001672static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1673 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001674 if (!OnlyProfitable) {
1675 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001676 MaxNumLoopsInScop =
1677 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001678 if (Stats.MaxDepth == 1)
1679 NumScopsDepthOne++;
1680 else if (Stats.MaxDepth == 2)
1681 NumScopsDepthTwo++;
1682 else if (Stats.MaxDepth == 3)
1683 NumScopsDepthThree++;
1684 else if (Stats.MaxDepth == 4)
1685 NumScopsDepthFour++;
1686 else if (Stats.MaxDepth == 5)
1687 NumScopsDepthFive++;
1688 else
1689 NumScopsDepthLarger++;
1690 } else {
1691 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001692 MaxNumLoopsInProfScop =
1693 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001694 if (Stats.MaxDepth == 1)
1695 NumProfScopsDepthOne++;
1696 else if (Stats.MaxDepth == 2)
1697 NumProfScopsDepthTwo++;
1698 else if (Stats.MaxDepth == 3)
1699 NumProfScopsDepthThree++;
1700 else if (Stats.MaxDepth == 4)
1701 NumProfScopsDepthFour++;
1702 else if (Stats.MaxDepth == 5)
1703 NumProfScopsDepthFive++;
1704 else
1705 NumProfScopsDepthLarger++;
1706 }
1707}
1708
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001709ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001710ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001711 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001712 if (DCMIt == DetectionContextMap.end())
1713 return nullptr;
1714 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001715}
1716
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001717const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1718 const DetectionContext *DC = getDetectionContext(R);
1719 return DC ? &DC->Log : nullptr;
1720}
1721
Tobias Grosser75805372011-04-29 06:27:02 +00001722void polly::ScopDetection::verifyRegion(const Region &R) const {
1723 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001724
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001725 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001726 isValidRegion(Context);
1727}
1728
1729void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001730 if (!VerifyScops)
1731 return;
1732
Tobias Grosser26108892014-04-02 20:18:19 +00001733 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001734 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001735}
1736
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001737bool ScopDetectionWrapperPass::runOnFunction(llvm::Function &F) {
1738 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1739 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1740 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1741 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1742 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Eli Friedmane737fc12017-07-17 23:58:33 +00001743 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1744 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE));
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001745 return false;
1746}
1747
1748void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001749 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001750 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001751 AU.addRequired<DominatorTreeWrapperPass>();
Eli Friedmane737fc12017-07-17 23:58:33 +00001752 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001753 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001754 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001755 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001756 AU.setPreservesAll();
1757}
1758
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001759void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1760 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001761 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001762
1763 OS << "\n";
1764}
1765
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001766ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1767 // Disable runtime alias checks if we ignore aliasing all together.
1768 if (IgnoreAliasing)
1769 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001770}
Philip Pfaffef5a43942017-08-02 11:08:01 +00001771ScopAnalysis::ScopAnalysis() {
1772 // Disable runtime alias checks if we ignore aliasing all together.
1773 if (IgnoreAliasing)
1774 PollyUseRuntimeAliasChecks = false;
1775}
Tobias Grosser75805372011-04-29 06:27:02 +00001776
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001777void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001778
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001779char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001780
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001781AnalysisKey ScopAnalysis::Key;
1782
1783ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1784 auto &LI = FAM.getResult<LoopAnalysis>(F);
1785 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1786 auto &AA = FAM.getResult<AAManager>(F);
1787 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1788 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
Eli Friedmane737fc12017-07-17 23:58:33 +00001789 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1790 return {F, DT, SE, LI, RI, AA, ORE};
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001791}
1792
1793PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1794 FunctionAnalysisManager &FAM) {
Philip Pfaffe96d21432017-08-04 11:28:51 +00001795 Stream << "Detected Scops in Function " << F.getName() << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001796 auto &SD = FAM.getResult<ScopAnalysis>(F);
1797 for (const Region *R : SD.ValidRegions)
1798 Stream << "Valid Region for Scop: " << R->getNameStr() << '\n';
1799
1800 Stream << "\n";
1801 return PreservedAnalyses::all();
1802}
1803
1804Pass *polly::createScopDetectionWrapperPassPass() {
1805 return new ScopDetectionWrapperPass();
1806}
1807
1808INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001809 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001810 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001811INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001812INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001813INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001814INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001815INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Eli Friedmane737fc12017-07-17 23:58:33 +00001816INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001817INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001818 "Polly - Detect static control parts (SCoPs)", false, false)