blob: cf6ba75648dff057cbfa343c6a84781ab302b409 [file] [log] [blame]
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001//===- ScopDetection.cpp - Detect Scops -----------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tobias Grosser75805372011-04-29 06:27:02 +00006//
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 Grosser75805372011-04-29 06:27:02 +000047#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000048#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000050#include "polly/Support/SCEVValidator.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000051#include "polly/Support/ScopHelper.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000052#include "polly/Support/ScopLocation.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000053#include "llvm/ADT/SmallPtrSet.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +000056#include "llvm/Analysis/Loads.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/LoopInfo.h"
Adam Nemete0f15412017-10-09 23:49:08 +000058#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000059#include "llvm/Analysis/RegionInfo.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000060#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000061#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000062#include "llvm/IR/BasicBlock.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000063#include "llvm/IR/DebugLoc.h"
64#include "llvm/IR/DerivedTypes.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000065#include "llvm/IR/DiagnosticInfo.h"
66#include "llvm/IR/DiagnosticPrinter.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000067#include "llvm/IR/Dominators.h"
68#include "llvm/IR/Function.h"
69#include "llvm/IR/InstrTypes.h"
70#include "llvm/IR/Instruction.h"
71#include "llvm/IR/Instructions.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000072#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000073#include "llvm/IR/Metadata.h"
74#include "llvm/IR/Module.h"
75#include "llvm/IR/PassManager.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000076#include "llvm/IR/Value.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080077#include "llvm/InitializePasses.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000078#include "llvm/Pass.h"
Tobias Grosser75805372011-04-29 06:27:02 +000079#include "llvm/Support/Debug.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000080#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000081#include <cassert>
Tobias Grosser60b54f12011-11-08 15:41:28 +000082
Tobias Grosser75805372011-04-29 06:27:02 +000083using namespace llvm;
84using namespace polly;
85
Chandler Carruth95fef942014-04-22 03:30:19 +000086#define DEBUG_TYPE "polly-detect"
87
Tobias Grosserc1a269b2015-12-21 21:00:43 +000088// This option is set to a very high value, as analyzing such loops increases
89// compile time on several cases. For experiments that enable this option,
90// a value of around 40 has been working to avoid run-time regressions with
91// Polly while still exposing interesting optimization opportunities.
92static cl::opt<int> ProfitabilityMinPerLoopInstructions(
93 "polly-detect-profitability-min-per-loop-insts",
94 cl::desc("The minimal number of per-loop instructions before a single loop "
95 "region is considered profitable"),
96 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
97
Tobias Grosser575aca82015-10-06 16:10:29 +000098bool polly::PollyProcessUnprofitable;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000099
Tobias Grosser575aca82015-10-06 16:10:29 +0000100static cl::opt<bool, true> XPollyProcessUnprofitable(
101 "polly-process-unprofitable",
102 cl::desc(
103 "Process scops that are unlikely to benefit from Polly optimizations."),
104 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
105 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000106
Siddharth Bhat286c9162017-06-09 08:23:40 +0000107static cl::list<std::string> OnlyFunctions(
Tobias Grosser483a90d2014-07-09 10:50:10 +0000108 "polly-only-func",
Siddharth Bhate2699b52017-07-24 12:40:52 +0000109 cl::desc("Only run on functions that match a regex. "
110 "Multiple regexes can be comma separated. "
111 "Scop detection will run on all functions that match "
112 "ANY of the regexes provided."),
Siddharth Bhat286c9162017-06-09 08:23:40 +0000113 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000114
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000115static cl::list<std::string> IgnoredFunctions(
116 "polly-ignore-func",
117 cl::desc("Ignore functions that match a regex. "
118 "Multiple regexes can be comma separated. "
119 "Scop detection will ignore all functions that match "
120 "ANY of the regexes provided."),
121 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
122
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000123bool polly::PollyAllowFullFunction;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000124
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000125static cl::opt<bool, true>
126 XAllowFullFunction("polly-detect-full-functions",
127 cl::desc("Allow the detection of full functions"),
128 cl::location(polly::PollyAllowFullFunction),
129 cl::init(false), cl::cat(PollyCategory));
Tobias Grosserd8945ba2017-05-19 12:13:02 +0000130
Tobias Grosser483a90d2014-07-09 10:50:10 +0000131static cl::opt<std::string> OnlyRegion(
132 "polly-only-region",
133 cl::desc("Only run on certain regions (The provided identifier must "
134 "appear in the name of the region's entry block"),
135 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
136 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000137
Tobias Grosser60cd9322011-11-10 12:47:26 +0000138static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000139 IgnoreAliasing("polly-ignore-aliasing",
140 cl::desc("Ignore possible aliasing of the array bases"),
141 cl::Hidden, cl::init(false), cl::ZeroOrMore,
142 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000143
Johannes Doerfertbda81432016-12-02 17:55:41 +0000144bool polly::PollyAllowUnsignedOperations;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000145
Johannes Doerfertbda81432016-12-02 17:55:41 +0000146static cl::opt<bool, true> XPollyAllowUnsignedOperations(
147 "polly-allow-unsigned-operations",
148 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
149 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
150 cl::init(true), cl::cat(PollyCategory));
151
Johannes Doerfertb164c792014-09-18 11:17:17 +0000152bool polly::PollyUseRuntimeAliasChecks;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000153
Johannes Doerfertb164c792014-09-18 11:17:17 +0000154static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
155 "polly-use-runtime-alias-checks",
156 cl::desc("Use runtime alias checks to resolve possible aliasing."),
157 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
158 cl::init(true), cl::cat(PollyCategory));
159
Tobias Grosser637bd632013-05-07 07:31:10 +0000160static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000161 ReportLevel("polly-report",
162 cl::desc("Print information about the activities of Polly"),
163 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000164
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000165static cl::opt<bool> AllowDifferentTypes(
166 "polly-allow-differing-element-types",
167 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000168 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000169
Tobias Grosser531891e2012-11-01 16:45:20 +0000170static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000171 AllowNonAffine("polly-allow-nonaffine",
172 cl::desc("Allow non affine access functions in arrays"),
173 cl::Hidden, cl::init(false), cl::ZeroOrMore,
174 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000175
Tobias Grosser898a6362016-03-23 06:40:15 +0000176static cl::opt<bool>
177 AllowModrefCall("polly-allow-modref-calls",
178 cl::desc("Allow functions with known modref behavior"),
179 cl::Hidden, cl::init(false), cl::ZeroOrMore,
180 cl::cat(PollyCategory));
181
Johannes Doerfertba65c162015-02-24 11:45:21 +0000182static cl::opt<bool> AllowNonAffineSubRegions(
183 "polly-allow-nonaffine-branches",
184 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000185 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000186
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000187static cl::opt<bool>
188 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
189 cl::desc("Allow non affine conditions for loops"),
190 cl::Hidden, cl::init(false), cl::ZeroOrMore,
191 cl::cat(PollyCategory));
192
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000193static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000194 TrackFailures("polly-detect-track-failures",
195 cl::desc("Track failure strings in detecting scop regions"),
196 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000197 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000198
Andreas Simbuerger04472402014-05-24 09:25:10 +0000199static cl::opt<bool> KeepGoing("polly-detect-keep-going",
200 cl::desc("Do not fail on the first error."),
201 cl::Hidden, cl::ZeroOrMore, cl::init(false),
202 cl::cat(PollyCategory));
203
Sebastian Pop18016682014-04-08 21:20:44 +0000204static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000205 PollyDelinearizeX("polly-delinearize",
206 cl::desc("Delinearize array access functions"),
207 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000208 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000209
Tobias Grossera1689932014-02-18 18:49:49 +0000210static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000211 VerifyScops("polly-detect-verify",
212 cl::desc("Verify the detected SCoPs after each transformation"),
213 cl::Hidden, cl::init(false), cl::ZeroOrMore,
214 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000215
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000216bool polly::PollyInvariantLoadHoisting;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000217
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000218static cl::opt<bool, true> XPollyInvariantLoadHoisting(
219 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
220 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000221 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000222
Tobias Grosserc80d6972016-09-02 06:33:33 +0000223/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000224static const unsigned MIN_LOOP_TRIP_COUNT = 8;
225
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000226bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000227bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000228StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000229
Tobias Grosser75805372011-04-29 06:27:02 +0000230//===----------------------------------------------------------------------===//
231// Statistics.
232
Tobias Grosserb45ae562016-11-26 07:37:46 +0000233STATISTIC(NumScopRegions, "Number of scops");
234STATISTIC(NumLoopsInScop, "Number of loops in scops");
Tobias Grosserfcc3ad52018-04-18 20:03:36 +0000235STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
Tobias Grosserb45ae562016-11-26 07:37:46 +0000236STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
237STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
238STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
239STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
240STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
241STATISTIC(NumScopsDepthLarger,
242 "Number of scops with maximal loop depth 6 and larger");
243STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
244STATISTIC(NumLoopsInProfScop,
245 "Number of loops in scops (profitable scops only)");
246STATISTIC(NumLoopsOverall, "Number of total loops");
Tobias Grosserfcc3ad52018-04-18 20:03:36 +0000247STATISTIC(NumProfScopsDepthZero,
248 "Number of scops with maximal loop depth 0 (profitable scops only)");
Tobias Grosserb45ae562016-11-26 07:37:46 +0000249STATISTIC(NumProfScopsDepthOne,
250 "Number of scops with maximal loop depth 1 (profitable scops only)");
251STATISTIC(NumProfScopsDepthTwo,
252 "Number of scops with maximal loop depth 2 (profitable scops only)");
253STATISTIC(NumProfScopsDepthThree,
254 "Number of scops with maximal loop depth 3 (profitable scops only)");
255STATISTIC(NumProfScopsDepthFour,
256 "Number of scops with maximal loop depth 4 (profitable scops only)");
257STATISTIC(NumProfScopsDepthFive,
258 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000259STATISTIC(NumProfScopsDepthLarger,
260 "Number of scops with maximal loop depth 6 and larger "
261 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000262STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
263STATISTIC(MaxNumLoopsInProfScop,
264 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000265
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000266static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
267 bool OnlyProfitable);
268
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000269namespace {
270
Tobias Grosser8519f892013-12-18 10:49:53 +0000271class DiagnosticScopFound : public DiagnosticInfo {
272private:
273 static int PluginDiagnosticKind;
274
275 Function &F;
276 std::string FileName;
277 unsigned EntryLine, ExitLine;
278
279public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000280 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
281 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000282 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000283 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000284
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000285 void print(DiagnosticPrinter &DP) const override;
Tobias Grosser8519f892013-12-18 10:49:53 +0000286
287 static bool classof(const DiagnosticInfo *DI) {
288 return DI->getKind() == PluginDiagnosticKind;
289 }
290};
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000291} // namespace
292
Tobias Grosserdb6db502016-04-01 07:15:19 +0000293int DiagnosticScopFound::PluginDiagnosticKind =
294 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000295
Tobias Grosser8519f892013-12-18 10:49:53 +0000296void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000297 DP << "Polly detected an optimizable loop region (scop) in function '" << F
298 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000299
300 if (FileName.empty()) {
301 DP << "Scop location is unknown. Compile with debug info "
302 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000303 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000304 }
305
306 DP << FileName << ":" << EntryLine << ": Start of scop\n";
307 DP << FileName << ":" << ExitLine << ": End of scop";
308}
309
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000310/// Check if a string matches any regex in a list of regexes.
311/// @param Str the input string to match against.
312/// @param RegexList a list of strings that are regular expressions.
313static bool doesStringMatchAnyRegex(StringRef Str,
314 const cl::list<std::string> &RegexList) {
315 for (auto RegexStr : RegexList) {
Siddharth Bhate2699b52017-07-24 12:40:52 +0000316 Regex R(RegexStr);
317
318 std::string Err;
319 if (!R.isValid(Err))
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000320 report_fatal_error("invalid regex given as input to polly: " + Err, true);
Siddharth Bhate2699b52017-07-24 12:40:52 +0000321
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000322 if (R.match(Str))
Siddharth Bhat286c9162017-06-09 08:23:40 +0000323 return true;
Siddharth Bhate2699b52017-07-24 12:40:52 +0000324 }
Siddharth Bhat286c9162017-06-09 08:23:40 +0000325 return false;
326}
Tobias Grosser75805372011-04-29 06:27:02 +0000327//===----------------------------------------------------------------------===//
328// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000329
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000330ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
331 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
Eli Friedmane737fc12017-07-17 23:58:33 +0000332 AliasAnalysis &AA, OptimizationRemarkEmitter &ORE)
333 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000334 if (!PollyProcessUnprofitable && LI.empty())
335 return;
336
337 Region *TopRegion = RI.getTopLevelRegion();
338
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000339 if (!OnlyFunctions.empty() &&
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000340 !doesStringMatchAnyRegex(F.getName(), OnlyFunctions))
341 return;
342
343 if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000344 return;
345
346 if (!isValidFunction(F))
347 return;
348
349 findScops(*TopRegion);
350
351 NumScopRegions += ValidRegions.size();
352
353 // Prune non-profitable regions.
354 for (auto &DIt : DetectionContextMap) {
355 auto &DC = DIt.getSecond();
356 if (DC.Log.hasErrors())
357 continue;
358 if (!ValidRegions.count(&DC.CurRegion))
359 continue;
360 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
361 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
362 if (isProfitableRegion(DC)) {
363 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
364 continue;
365 }
366
367 ValidRegions.remove(&DC.CurRegion);
368 }
369
370 NumProfScopRegions += ValidRegions.size();
371 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
372
373 // Only makes sense when we tracked errors.
374 if (PollyTrackFailures)
375 emitMissedRemarks(F);
376
377 if (ReportLevel)
378 printLocations(F);
379
380 assert(ValidRegions.size() <= DetectionContextMap.size() &&
381 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000382}
383
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000384template <class RR, typename... Args>
385inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
386 Args &&... Arguments) const {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000387 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000388 RejectLog &Log = Context.Log;
389 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000390
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000391 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000392 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000393
Nicola Zaghen349506a2018-05-15 13:37:17 +0000394 LLVM_DEBUG(dbgs() << RejectReason->getMessage());
395 LLVM_DEBUG(dbgs() << "\n");
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000396 } else {
397 assert(!Assert && "Verification of detected scop failed");
398 }
399
400 return false;
401}
402
Tobias Grossera1689932014-02-18 18:49:49 +0000403bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
404 if (!ValidRegions.count(&R))
405 return false;
406
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000407 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000408 DetectionContextMap.erase(getBBPairForRegion(&R));
409 const auto &It = DetectionContextMap.insert(std::make_pair(
410 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000411 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000412 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000413 return isValidRegion(Context);
414 }
Tobias Grossera1689932014-02-18 18:49:49 +0000415
416 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000417}
418
Tobias Grosser4f129a62011-10-08 00:30:55 +0000419std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000420 // Get the first error we found. Even in keep-going mode, this is the first
421 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000422 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000423
424 // This can happen when we marked a region invalid, but didn't track
425 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000426 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000427 return "";
428
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000429 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000430 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000431}
432
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000433bool ScopDetection::addOverApproximatedRegion(Region *AR,
434 DetectionContext &Context) const {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000435 // If we already know about Ar we can exit.
436 if (!Context.NonAffineSubRegionSet.insert(AR))
437 return true;
438
439 // All loops in the region have to be overapproximated too if there
440 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000441
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000442 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000443 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000444 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000445 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000446 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000447
448 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000449}
450
Johannes Doerfert09e36972015-10-07 20:17:36 +0000451bool ScopDetection::onlyValidRequiredInvariantLoads(
452 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
453 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000454 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000455
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000456 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
457 return false;
458
Tobias Grosser1c787e02017-03-02 12:15:37 +0000459 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000460 // If we already know a load has been accepted as required invariant, we
461 // already run the validation below once and consequently don't need to
462 // run it again. Hence, we return early. For certain test cases (e.g.,
463 // COSMO this avoids us spending 50% of scop-detection time in this
464 // very function (and its children).
465 if (Context.RequiredILS.count(Load))
466 continue;
Philip Pfaffeec1a3042018-06-29 07:29:45 +0000467 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000468 return false;
469
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000470 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000471 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
Guillaume Chatelet22755e4e2019-10-21 15:48:42 +0000472 Load->getType(),
473 MaybeAlign(Load->getAlignment()), DL))
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000474 continue;
475
Tobias Grosser1c787e02017-03-02 12:15:37 +0000476 if (NonAffineRegion->contains(Load) &&
477 Load->getParent() != NonAffineRegion->getEntry())
478 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000479 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000480 }
481
Johannes Doerfert09e36972015-10-07 20:17:36 +0000482 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
483
484 return true;
485}
486
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000487bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
488 Loop *Scope) const {
489 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000490 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000491 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000492 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000493
494 SmallPtrSet<Value *, 8> PtrVals;
495 for (auto *V : Values) {
496 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
497 V = P2I->getOperand(0);
498
499 if (!V->getType()->isPointerTy())
500 continue;
501
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000502 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000503 if (isa<SCEVConstant>(PtrSCEV))
504 continue;
505
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000506 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000507 if (!BasePtr)
508 return true;
509
510 auto *BasePtrVal = BasePtr->getValue();
511 if (PtrVals.insert(BasePtrVal).second) {
512 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000513 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000514 return true;
515 }
516 }
517
518 return false;
519}
520
Michael Kruse09eb4452016-03-03 22:10:47 +0000521bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000522 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000523 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000524 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000525 return false;
526
527 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
528 return false;
529
530 return true;
531}
532
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000533bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000534 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000535 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000536 Loop *L = LI.getLoopFor(&BB);
537 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000538
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000539 if (IsLoopBranch && L->isLoopLatch(&BB))
540 return false;
541
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000542 // Check for invalid usage of different pointers in one expression.
543 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
544 return false;
545
Michael Kruse09eb4452016-03-03 22:10:47 +0000546 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000547 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000548
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000549 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000550 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000551 return true;
552
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000553 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
554 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000555}
556
557bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000558 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000559 DetectionContext &Context) const {
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000560 // Constant integer conditions are always affine.
561 if (isa<ConstantInt>(Condition))
562 return true;
563
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000564 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
565 auto Opcode = BinOp->getOpcode();
566 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
567 Value *Op0 = BinOp->getOperand(0);
568 Value *Op1 = BinOp->getOperand(1);
569 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
570 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
571 }
572 }
573
Tobias Grosser0a62b2d2017-09-25 16:37:15 +0000574 if (auto PHI = dyn_cast<PHINode>(Condition)) {
575 auto *Unique = dyn_cast_or_null<ConstantInt>(
576 getUniqueNonErrorValue(PHI, &Context.CurRegion, LI, DT));
577 if (Unique && (Unique->isZero() || Unique->isOne()))
578 return true;
579 }
580
Tobias Grosser5e531df2017-09-25 20:27:15 +0000581 if (auto Load = dyn_cast<LoadInst>(Condition))
Michael Krusec0133992017-10-01 22:19:28 +0000582 if (!IsLoopBranch && Context.CurRegion.contains(Load)) {
Tobias Grosser5e531df2017-09-25 20:27:15 +0000583 Context.RequiredILS.insert(Load);
584 return true;
585 }
586
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000587 // Non constant conditions of branches need to be ICmpInst.
588 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000589 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000590 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000591 return true;
592 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000593 }
Tobias Grosser75805372011-04-29 06:27:02 +0000594
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000595 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000596
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000597 // Are both operands of the ICmp affine?
598 if (isa<UndefValue>(ICmp->getOperand(0)) ||
599 isa<UndefValue>(ICmp->getOperand(1)))
600 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000601
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000602 Loop *L = LI.getLoopFor(&BB);
603 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
604 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000605
Tobias Grosseree457592017-09-24 09:25:30 +0000606 LHS = tryForwardThroughPHI(LHS, Context.CurRegion, SE, LI, DT);
607 RHS = tryForwardThroughPHI(RHS, Context.CurRegion, SE, LI, DT);
608
Johannes Doerfertbda81432016-12-02 17:55:41 +0000609 // If unsigned operations are not allowed try to approximate the region.
610 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
611 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000612 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000613
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000614 // Check for invalid usage of different pointers in one expression.
615 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
616 involvesMultiplePtrs(RHS, nullptr, L))
617 return false;
618
619 // Check for invalid usage of different pointers in a relational comparison.
620 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
621 return false;
622
Michael Kruse09eb4452016-03-03 22:10:47 +0000623 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000624 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000625
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000626 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000627 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000628 return true;
629
630 if (IsLoopBranch)
631 return false;
632
633 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
634 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000635}
636
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000637bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000638 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000639 DetectionContext &Context) const {
640 Region &CurRegion = Context.CurRegion;
641
Chandler Carruthe303c872018-10-15 10:42:50 +0000642 Instruction *TI = BB.getTerminator();
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000643
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000644 if (AllowUnreachable && isa<UnreachableInst>(TI))
645 return true;
646
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000647 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000648 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000649 return true;
650
651 Value *Condition = getConditionFromTerminator(TI);
652
653 if (!Condition)
654 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
655
656 // UndefValue is not allowed as condition.
657 if (isa<UndefValue>(Condition))
658 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
659
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000660 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000661 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000662
663 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
664 assert(SI && "Terminator was neither branch nor switch");
665
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000666 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000667}
668
Johannes Doerfertcea61932016-02-21 19:13:19 +0000669bool ScopDetection::isValidCallInst(CallInst &CI,
670 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000671 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000672 return false;
673
674 if (CI.doesNotAccessMemory())
675 return true;
676
Johannes Doerfertcea61932016-02-21 19:13:19 +0000677 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000678 if (isValidIntrinsicInst(*II, Context))
679 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000680
Tobias Grosser75805372011-04-29 06:27:02 +0000681 Function *CalledFunction = CI.getCalledFunction();
682
683 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000684 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000685 return false;
686
Michael Kruse5369ea52018-04-20 18:55:44 +0000687 if (isDebugCall(&CI)) {
Nicola Zaghen349506a2018-05-15 13:37:17 +0000688 LLVM_DEBUG(dbgs() << "Allow call to debug function: "
689 << CalledFunction->getName() << '\n');
Michael Kruse5369ea52018-04-20 18:55:44 +0000690 return true;
691 }
692
Tobias Grosser898a6362016-03-23 06:40:15 +0000693 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000694 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000695 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000696 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000697 case FMRB_DoesNotAccessMemory:
698 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000699 // Implicitly disable delinearization since we have an unknown
700 // accesses with an unknown access function.
701 Context.HasUnknownAccess = true;
Eli Friedmanefe18d392018-09-11 23:48:14 +0000702 // Explicitly use addUnknown so we don't put a loop-variant
703 // pointer into the alias set.
704 Context.AST.addUnknown(&CI);
Tobias Grosser898a6362016-03-23 06:40:15 +0000705 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000706 case FMRB_OnlyReadsArgumentPointees:
707 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000708 for (const auto &Arg : CI.arg_operands()) {
709 if (!Arg->getType()->isPointerTy())
710 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000711
Tobias Grosser898a6362016-03-23 06:40:15 +0000712 // Bail if a pointer argument has a base address not known to
713 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000714 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000715 if (ArgSCEV->isZero())
716 continue;
717
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000718 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000719 if (!BP)
720 return false;
721
722 // Implicitly disable delinearization since we have an unknown
723 // accesses with an unknown access function.
724 Context.HasUnknownAccess = true;
725 }
726
Eli Friedmanefe18d392018-09-11 23:48:14 +0000727 // Explicitly use addUnknown so we don't put a loop-variant
728 // pointer into the alias set.
729 Context.AST.addUnknown(&CI);
Tobias Grosser898a6362016-03-23 06:40:15 +0000730 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000731 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000732 case FMRB_OnlyAccessesInaccessibleMem:
733 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000734 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000735 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000736 }
737
Johannes Doerfertcea61932016-02-21 19:13:19 +0000738 return false;
739}
740
741bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
742 DetectionContext &Context) const {
743 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000744 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000745
Johannes Doerfertcea61932016-02-21 19:13:19 +0000746 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000747 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000748
749 // The access function and base pointer for memory intrinsics.
750 const SCEV *AF;
751 const SCEVUnknown *BP;
752
753 switch (II.getIntrinsicID()) {
754 // Memory intrinsics that can be represented are supported.
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000755 case Intrinsic::memmove:
756 case Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000757 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000758 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000759 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000760 // Bail if the source pointer is not valid.
761 if (!isValidAccess(&II, AF, BP, Context))
762 return false;
763 }
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000764 LLVM_FALLTHROUGH;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000765 case Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000766 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000767 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000768 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000769 // Bail if the destination pointer is not valid.
770 if (!isValidAccess(&II, AF, BP, Context))
771 return false;
772 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000773
774 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000775 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000776 Context))
777 return false;
778
779 return true;
780 default:
781 break;
782 }
783
Tobias Grosser75805372011-04-29 06:27:02 +0000784 return false;
785}
786
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000787bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
788 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000789 // A reference to function argument or constant value is invariant.
790 if (isa<Argument>(Val) || isa<Constant>(Val))
791 return true;
792
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000793 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000794 if (!I)
795 return false;
796
797 if (!Reg.contains(I))
798 return true;
799
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000800 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
801 // is not hoistable, it will be rejected later, but here we assume it is and
802 // that makes the value invariant.
803 if (auto LI = dyn_cast<LoadInst>(I)) {
804 Ctx.RequiredILS.insert(LI);
805 return true;
806 }
807
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000808 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000809}
810
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000811namespace {
812
Tobias Grosserc80d6972016-09-02 06:33:33 +0000813/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000814/// register the '...' components.
815///
Michael Krusea6d48f52017-06-08 12:06:15 +0000816/// Array access expressions as they are generated by GFortran contain smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000817/// size) expressions that confuse the 'normal' delinearization algorithm.
818/// However, if we extract such expressions before the normal delinearization
819/// takes place they can actually help to identify array size expressions in
Michael Krusea6d48f52017-06-08 12:06:15 +0000820/// Fortran accesses. For the subsequently following delinearization the smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000821/// size) component can be replaced by just 'size'. This is correct as we will
822/// always add and verify the assumption that for all subscript expressions
823/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
824/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000825class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000826public:
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000827 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
828 : SCEVRewriteVisitor(SE), Terms(Terms) {}
829
Tobias Grosserebb626e2016-10-29 06:19:34 +0000830 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
831 std::vector<const SCEV *> *Terms = nullptr) {
832 SCEVRemoveMax Rewriter(SE, Terms);
833 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000834 }
835
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000836 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000837 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000838 auto Res = visit(Expr->getOperand(1));
839 if (Terms)
840 (*Terms).push_back(Res);
841 return Res;
842 }
843
844 return Expr;
845 }
846
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000847private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000848 std::vector<const SCEV *> *Terms;
849};
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000850} // namespace
851
Tobias Grosserd68ba422015-11-24 05:00:36 +0000852SmallVector<const SCEV *, 4>
853ScopDetection::getDelinearizationTerms(DetectionContext &Context,
854 const SCEVUnknown *BasePointer) const {
855 SmallVector<const SCEV *, 4> Terms;
856 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000857 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000858 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000859 if (!MaxTerms.empty()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000860 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
861 continue;
862 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000863 // In case the outermost expression is a plain add, we check if any of its
864 // terms has the form 4 * %inst * %param * %param ..., aka a term that
865 // contains a product between a parameter and an instruction that is
866 // inside the scop. Such instructions, if allowed at all, are instructions
867 // SCEV can not represent, but Polly is still looking through. As a
868 // result, these instructions can depend on induction variables and are
869 // most likely no array sizes. However, terms that are multiplied with
870 // them are likely candidates for array sizes.
871 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
872 for (auto Op : AF->operands()) {
873 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000874 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000875 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
876 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000877
Tobias Grosserd68ba422015-11-24 05:00:36 +0000878 for (auto *MulOp : AF2->operands()) {
879 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
880 Operands.push_back(Const);
881 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
882 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
883 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000884 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000885
886 } else {
887 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000888 }
889 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000890 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000891 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000892 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000893 }
894 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000895 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000896 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000897 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000898 }
899 return Terms;
900}
Sebastian Pope8863b82014-05-12 19:02:02 +0000901
Tobias Grosserd68ba422015-11-24 05:00:36 +0000902bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
903 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000904 const SCEVUnknown *BasePointer,
905 Loop *Scope) const {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000906 // If no sizes were found, all sizes are trivially valid. We allow this case
907 // to make it possible to pass known-affine accesses to the delinearization to
908 // try to recover some interesting multi-dimensional accesses, but to still
909 // allow the already known to be affine access in case the delinearization
910 // fails. In such situations, the delinearization will just return a Sizes
911 // array of size zero.
912 if (Sizes.size() == 0)
913 return true;
914
Tobias Grosserd68ba422015-11-24 05:00:36 +0000915 Value *BaseValue = BasePointer->getValue();
916 Region &CurRegion = Context.CurRegion;
917 for (const SCEV *DelinearizedSize : Sizes) {
Eli Friedman9b234b32019-05-14 21:32:54 +0000918 // Don't pass down the scope to isAfffine; array dimensions must be
919 // invariant across the entire scop.
920 if (!isAffine(DelinearizedSize, nullptr, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000921 Sizes.clear();
922 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000923 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000924 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
925 auto *V = dyn_cast<Value>(Unknown->getValue());
926 if (auto *Load = dyn_cast<LoadInst>(V)) {
927 if (Context.CurRegion.contains(Load) &&
Philip Pfaffeec1a3042018-06-29 07:29:45 +0000928 isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000929 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000930 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000931 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000932 }
Siddharth Bhata1b20862017-07-13 12:18:56 +0000933 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
934 Context.RequiredILS))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000935 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000936 Context, /*Assert=*/true, DelinearizedSize,
937 Context.Accesses[BasePointer].front().first, BaseValue);
938 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000939
Tobias Grosserd68ba422015-11-24 05:00:36 +0000940 // No array shape derived.
941 if (Sizes.empty()) {
942 if (AllowNonAffine)
943 return true;
944
Tobias Grosser230acc42014-09-13 14:47:55 +0000945 for (const auto &Pair : Context.Accesses[BasePointer]) {
946 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000947 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000948
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000949 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000950 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
951 BaseValue);
952 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000953 return false;
954 }
955 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000956 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000957 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000958 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000959}
960
Tobias Grosserd68ba422015-11-24 05:00:36 +0000961// We first store the resulting memory accesses in TempMemoryAccesses. Only
962// if the access functions for all memory accesses have been successfully
963// delinearized we continue. Otherwise, we either report a failure or, if
964// non-affine accesses are allowed, we drop the information. In case the
965// information is dropped the memory accesses need to be overapproximated
966// when translated to a polyhedral representation.
967bool ScopDetection::computeAccessFunctions(
968 DetectionContext &Context, const SCEVUnknown *BasePointer,
969 std::shared_ptr<ArrayShape> Shape) const {
970 Value *BaseValue = BasePointer->getValue();
971 bool BasePtrHasNonAffine = false;
972 MapInsnToMemAcc TempMemoryAccesses;
973 for (const auto &Pair : Context.Accesses[BasePointer]) {
974 const Instruction *Insn = Pair.first;
975 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000976 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000977 bool IsNonAffine = false;
978 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
979 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000980 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000981
982 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000983 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000984 Acc->DelinearizedSubscripts.push_back(Pair.second);
985 else
986 IsNonAffine = true;
987 } else {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000988 if (Shape->DelinearizedSizes.size() == 0) {
989 Acc->DelinearizedSubscripts.push_back(AF);
990 } else {
991 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
992 Shape->DelinearizedSizes);
993 if (Acc->DelinearizedSubscripts.size() == 0)
994 IsNonAffine = true;
995 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000996 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000997 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000998 IsNonAffine = true;
999 }
1000
1001 // (Possibly) report non affine access
1002 if (IsNonAffine) {
1003 BasePtrHasNonAffine = true;
1004 if (!AllowNonAffine)
1005 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
1006 Insn, BaseValue);
1007 if (!KeepGoing && !AllowNonAffine)
1008 return false;
1009 }
1010 }
1011
1012 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +00001013 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
1014 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +00001015
1016 return true;
1017}
1018
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001019bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
1020 const SCEVUnknown *BasePointer,
1021 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +00001022 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
1023
1024 auto Terms = getDelinearizationTerms(Context, BasePointer);
1025
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001026 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
1027 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +00001028
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001029 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
1030 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +00001031 return false;
1032
1033 return computeAccessFunctions(Context, BasePointer, Shape);
1034}
1035
1036bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +00001037 // TODO: If we have an unknown access and other non-affine accesses we do
1038 // not try to delinearize them for now.
1039 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
1040 return AllowNonAffine;
1041
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001042 for (auto &Pair : Context.NonAffineAccesses) {
1043 auto *BasePointer = Pair.first;
1044 auto *Scope = Pair.second;
1045 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +00001046 if (KeepGoing)
1047 continue;
1048 else
1049 return false;
1050 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001051 }
Tobias Grosserd68ba422015-11-24 05:00:36 +00001052 return true;
1053}
1054
Johannes Doerfertcea61932016-02-21 19:13:19 +00001055bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1056 const SCEVUnknown *BP,
1057 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001058
Johannes Doerfertcea61932016-02-21 19:13:19 +00001059 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +00001060 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001061
Johannes Doerfertcea61932016-02-21 19:13:19 +00001062 auto *BV = BP->getValue();
1063 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +00001064 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001065
Johannes Doerfertcea61932016-02-21 19:13:19 +00001066 // FIXME: Think about allowing IntToPtrInst
1067 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1068 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1069
Tobias Grosser458fb782014-01-28 12:58:58 +00001070 // Check that the base address of the access is invariant in the current
1071 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +00001072 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001073 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +00001074
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001075 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001076
Johannes Doerfertcea61932016-02-21 19:13:19 +00001077 const SCEV *Size;
1078 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001079 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001080 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001081 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001082 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1083 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001084 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +00001085
Johannes Doerfertcea61932016-02-21 19:13:19 +00001086 if (Context.ElementSize[BP]) {
1087 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1088 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1089 Inst, BV);
1090
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001091 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001092 } else {
1093 Context.ElementSize[BP] = Size;
1094 }
1095
1096 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001097 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001098 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001099 for (const Loop *L : Loops)
1100 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001101 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001102
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001103 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001104 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001105 // Do not try to delinearize memory intrinsics and force them to be affine.
1106 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1107 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1108 BV);
1109 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1110 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001111
Tobias Grosser1e55db32017-05-27 15:18:53 +00001112 if (!IsAffine || hasIVParams(AF))
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001113 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001114 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001115 } else if (!AllowNonAffine && !IsAffine) {
1116 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1117 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001118 }
Tobias Grosser75805372011-04-29 06:27:02 +00001119
Tobias Grosser1eedb672014-09-24 21:04:29 +00001120 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001121 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001122
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001123 // Check if the base pointer of the memory access does alias with
1124 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001125 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001126 Inst->getAAMetadata(AATags);
Michael Kruseb67e5d32018-08-17 19:31:41 +00001127 AliasSet &AS = Context.AST.getAliasSetFor(
1128 MemoryLocation(BP->getValue(), MemoryLocation::UnknownSize, AATags));
Tobias Grosser428b3e42013-02-04 15:46:25 +00001129
Tobias Grosser1eedb672014-09-24 21:04:29 +00001130 if (!AS.isMustAlias()) {
1131 if (PollyUseRuntimeAliasChecks) {
1132 bool CanBuildRunTimeCheck = true;
1133 // The run-time alias check places code that involves the base pointer at
1134 // the beginning of the SCoP. This breaks if the base pointer is defined
1135 // inside the scop. Hence, we can only create a run-time check if we are
1136 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001137 // However, we can ignore loads that will be hoisted.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001138
Philip Pfaffeec1a3042018-06-29 07:29:45 +00001139 InvariantLoadsSetTy VariantLS, InvariantLS;
1140 // In order to detect loads which are dependent on other invariant loads
1141 // as invariant, we use fixed-point iteration method here i.e we iterate
1142 // over the alias set for arbitrary number of times until it is safe to
1143 // assume that all the invariant loads have been detected
1144 while (1) {
1145 const unsigned int VariantSize = VariantLS.size(),
1146 InvariantSize = InvariantLS.size();
1147
1148 for (const auto &Ptr : AS) {
1149 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
1150 if (Inst && Context.CurRegion.contains(Inst)) {
1151 auto *Load = dyn_cast<LoadInst>(Inst);
1152 if (Load && InvariantLS.count(Load))
1153 continue;
1154 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT,
1155 InvariantLS)) {
1156 if (VariantLS.count(Load))
1157 VariantLS.remove(Load);
1158 Context.RequiredILS.insert(Load);
1159 InvariantLS.insert(Load);
1160 } else {
1161 CanBuildRunTimeCheck = false;
1162 VariantLS.insert(Load);
1163 }
1164 }
Tobias Grosser1eedb672014-09-24 21:04:29 +00001165 }
Philip Pfaffeec1a3042018-06-29 07:29:45 +00001166
1167 if (InvariantSize == InvariantLS.size() &&
1168 VariantSize == VariantLS.size())
1169 break;
Tobias Grosser1eedb672014-09-24 21:04:29 +00001170 }
1171
1172 if (CanBuildRunTimeCheck)
1173 return true;
1174 }
Michael Kruse70131d32016-01-27 17:09:17 +00001175 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001176 }
Tobias Grosser75805372011-04-29 06:27:02 +00001177
1178 return true;
1179}
1180
Johannes Doerfertcea61932016-02-21 19:13:19 +00001181bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1182 DetectionContext &Context) const {
1183 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001184 Loop *L = LI.getLoopFor(Inst->getParent());
1185 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001186 const SCEVUnknown *BasePointer;
1187
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001188 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001189
1190 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1191}
1192
Tobias Grosser75805372011-04-29 06:27:02 +00001193bool ScopDetection::isValidInstruction(Instruction &Inst,
1194 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001195 for (auto &Op : Inst.operands()) {
1196 auto *OpInst = dyn_cast<Instruction>(&Op);
1197
1198 if (!OpInst)
1199 continue;
1200
Tobias Grosser1f93d0f2017-09-26 15:00:10 +00001201 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT)) {
1202 auto *PHI = dyn_cast<PHINode>(OpInst);
1203 if (PHI) {
1204 for (User *U : PHI->users()) {
Chandler Carruth9ae926b2018-08-26 09:51:22 +00001205 auto *UI = dyn_cast<Instruction>(U);
1206 if (!UI || !UI->isTerminator())
Tobias Grosser1f93d0f2017-09-26 15:00:10 +00001207 return false;
1208 }
1209 } else {
1210 return false;
1211 }
1212 }
Tobias Grosserb12b0062015-11-11 12:44:18 +00001213 }
1214
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001215 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1216 return false;
1217
Tobias Grosser75805372011-04-29 06:27:02 +00001218 // We only check the call instruction but not invoke instruction.
1219 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001220 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001221 return true;
1222
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001223 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001224 }
1225
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001226 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001227 if (!isa<AllocaInst>(Inst))
1228 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001229
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001230 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001231 }
1232
1233 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001234 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001235 Context.hasStores |= isa<StoreInst>(MemInst);
1236 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001237 if (!MemInst.isSimple())
1238 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1239 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001240
Michael Kruse70131d32016-01-27 17:09:17 +00001241 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001242 }
Tobias Grosser75805372011-04-29 06:27:02 +00001243
1244 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001245 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001246}
1247
Tobias Grosser6d0970f2017-08-24 19:47:15 +00001248/// Check whether @p L has exiting blocks.
1249///
1250/// @param L The loop of interest
1251///
1252/// @return True if the loop has exiting blocks, false otherwise.
1253static bool hasExitingBlocks(Loop *L) {
1254 SmallVector<BasicBlock *, 4> ExitingBlocks;
1255 L->getExitingBlocks(ExitingBlocks);
1256 return !ExitingBlocks.empty();
1257}
1258
Johannes Doerfertd020b772015-08-27 06:53:52 +00001259bool ScopDetection::canUseISLTripCount(Loop *L,
1260 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001261 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1262 // need to overapproximate it as a boxed loop.
1263 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001264 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001265 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001266 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001267 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001268 return false;
1269 }
1270
Johannes Doerfertd020b772015-08-27 06:53:52 +00001271 // We can use ISL to compute the trip count of L.
1272 return true;
1273}
1274
Tobias Grosser75805372011-04-29 06:27:02 +00001275bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001276 // Loops that contain part but not all of the blocks of a region cannot be
1277 // handled by the schedule generation. Such loop constructs can happen
1278 // because a region can contain BBs that have no path to the exit block
Tobias Grosser6d0970f2017-08-24 19:47:15 +00001279 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1280 // loop.
1281 //
1282 // _______________
1283 // | Loop Header | <-----------.
1284 // --------------- |
1285 // | |
1286 // _______________ ______________
1287 // | RegionEntry |-----> | RegionExit |----->
1288 // --------------- --------------
1289 // |
1290 // _______________
1291 // | EndlessLoop | <--.
1292 // --------------- |
1293 // | |
1294 // \------------/
1295 //
1296 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1297 // neither entirely contained in the region RegionEntry->RegionExit
1298 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1299 // in the loop.
1300 // The block EndlessLoop is contained in the region because Region::contains
1301 // tests whether it is not dominated by RegionExit. This is probably to not
1302 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1303 // end can also be formed by an UnreachableInst. This case is already caught
1304 // by isErrorBlock(). We hence only have to reject endless loops here.
1305 if (!hasExitingBlocks(L))
1306 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
Tobias Grosser349d1c32016-09-20 17:05:22 +00001307
Michael Krusebeffdb92018-04-25 18:53:33 +00001308 // The algorithm for domain construction assumes that loops has only a single
1309 // exit block (and hence corresponds to a subregion). Note that we cannot use
1310 // L->getExitBlock() because it does not check whether all exiting edges point
1311 // to the same BB.
1312 SmallVector<BasicBlock *, 4> ExitBlocks;
1313 L->getExitBlocks(ExitBlocks);
1314 BasicBlock *TheExitBlock = ExitBlocks[0];
1315 for (BasicBlock *ExitBB : ExitBlocks) {
1316 if (TheExitBlock != ExitBB)
1317 return invalid<ReportLoopHasMultipleExits>(Context, /*Assert=*/true, L);
1318 }
1319
Johannes Doerfertf61df692015-10-04 14:56:08 +00001320 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001321 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001322
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001323 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001324 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001325 while (R != &Context.CurRegion && !R->contains(L))
1326 R = R->getParent();
1327
1328 if (addOverApproximatedRegion(R, Context))
1329 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001330 }
Tobias Grosser75805372011-04-29 06:27:02 +00001331
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001332 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001333 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001334}
1335
Tobias Grosserc80d6972016-09-02 06:33:33 +00001336/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001337/// count that is not known to be less than @MinProfitableTrips.
1338ScopDetection::LoopStats
1339ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001340 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001341 auto *TripCount = SE.getBackedgeTakenCount(L);
1342
Tobias Grosserb45ae562016-11-26 07:37:46 +00001343 int NumLoops = 1;
1344 int MaxLoopDepth = 1;
Michael Kruse7fac28fa2017-08-23 13:29:59 +00001345 if (MinProfitableTrips > 0)
1346 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
1347 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1348 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1349 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001350
Tobias Grosserb45ae562016-11-26 07:37:46 +00001351 for (auto &SubLoop : *L) {
1352 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1353 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001354 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001355 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001356
Tobias Grosserb45ae562016-11-26 07:37:46 +00001357 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001358}
1359
Tobias Grosserb45ae562016-11-26 07:37:46 +00001360ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001361ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1362 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001363 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001364 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001365
Tobias Grossercd01a362017-02-17 08:12:36 +00001366 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser93ab5582017-08-27 21:39:25 +00001367
1368 // If L is fully contained in R, move to first loop surrounding R. Otherwise,
1369 // L is either nullptr or already surrounding R.
1370 if (L && R->contains(L)) {
1371 L = R->outermostLoopInRegion(L);
1372 L = L->getParentLoop();
1373 }
Tobias Grossered21a1f2015-08-27 16:55:18 +00001374
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001375 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001376 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001377
1378 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001379 if (R->contains(SubLoop)) {
1380 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001381 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001382 LoopNum += Stats.NumLoops;
1383 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1384 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001385
Tobias Grosserb45ae562016-11-26 07:37:46 +00001386 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001387}
1388
Tobias Grosser75805372011-04-29 06:27:02 +00001389Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001390 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001391 std::unique_ptr<Region> LastValidRegion;
1392 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001393
Nicola Zaghen349506a2018-05-15 13:37:17 +00001394 LLVM_DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001395
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001396 while (ExpandedRegion) {
Siddharth Bhatc0f5f4d2017-12-05 00:06:09 +00001397 const auto &It = DetectionContextMap.insert(std::make_pair(
1398 getBBPairForRegion(ExpandedRegion.get()),
1399 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001400 DetectionContext &Context = It.first->second;
Nicola Zaghen349506a2018-05-15 13:37:17 +00001401 LLVM_DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001402 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001403
Johannes Doerfert717b8662015-09-08 21:44:27 +00001404 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001405 // If the exit is valid check all blocks
1406 // - if true, a valid region was found => store it + keep expanding
1407 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001408 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1409 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001410 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001411 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001412 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001413
Tobias Grosserd7e58642013-04-10 06:55:45 +00001414 // Store this region, because it is the greatest valid (encountered so
1415 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001416 if (LastValidRegion) {
1417 removeCachedResults(*LastValidRegion);
1418 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1419 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001420 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001421
1422 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001423 ExpandedRegion =
1424 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001425
1426 } else {
1427 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001428 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001429 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001430 ExpandedRegion =
1431 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001432 }
Tobias Grosser75805372011-04-29 06:27:02 +00001433 }
1434
Nicola Zaghen349506a2018-05-15 13:37:17 +00001435 LLVM_DEBUG({
Tobias Grosser378a9f22013-11-16 19:34:11 +00001436 if (LastValidRegion)
1437 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1438 else
1439 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1440 });
Tobias Grosser75805372011-04-29 06:27:02 +00001441
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001442 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001443}
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001444
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001445static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001446 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001447 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001448 return false;
1449
1450 return true;
1451}
Tobias Grosser75805372011-04-29 06:27:02 +00001452
Tobias Grosserb45ae562016-11-26 07:37:46 +00001453void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001454 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001455 if (ValidRegions.count(SubRegion.get())) {
1456 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001457 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001458 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001459 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001460}
1461
Johannes Doerferte46925f2015-10-01 10:59:14 +00001462void ScopDetection::removeCachedResults(const Region &R) {
1463 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001464}
1465
Tobias Grosser75805372011-04-29 06:27:02 +00001466void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001467 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001468 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001469 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001470
1471 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001472 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001473 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001474 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001475 RegionIsValid = isValidRegion(Context);
1476
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001477 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001478
Johannes Doerferte46925f2015-10-01 10:59:14 +00001479 if (HasErrors) {
1480 removeCachedResults(R);
1481 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001482 ValidRegions.insert(&R);
1483 return;
1484 }
1485
David Blaikieb035f6d2014-04-15 18:45:27 +00001486 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001487 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001488
1489 // Try to expand regions.
1490 //
1491 // As the region tree normally only contains canonical regions, non canonical
1492 // regions that form a Scop are not found. Therefore, those non canonical
1493 // regions are checked by expanding the canonical ones.
1494
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001495 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001496
David Blaikieb035f6d2014-04-15 18:45:27 +00001497 for (auto &SubRegion : R)
1498 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001499
Tobias Grosser26108892014-04-02 20:18:19 +00001500 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001501 // Skip invalid regions. Regions may become invalid, if they are element of
1502 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001503 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001504 continue;
1505
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001506 // Skip regions that had errors.
1507 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1508 if (HadErrors)
1509 continue;
1510
Tobias Grosser75805372011-04-29 06:27:02 +00001511 Region *ExpandedR = expandRegion(*CurrentRegion);
1512
1513 if (!ExpandedR)
1514 continue;
1515
1516 R.addSubRegion(ExpandedR, true);
1517 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001518 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001519 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001520 }
1521}
1522
1523bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001524 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001525
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001526 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001527 Loop *L = LI.getLoopFor(BB);
Tobias Grossera3aa4232017-07-15 22:42:17 +00001528 if (L && L->getHeader() == BB) {
1529 if (CurRegion.contains(L)) {
1530 if (!isValidLoop(L, Context) && !KeepGoing)
1531 return false;
1532 } else {
1533 SmallVector<BasicBlock *, 1> Latches;
1534 L->getLoopLatches(Latches);
1535 for (BasicBlock *Latch : Latches)
1536 if (CurRegion.contains(Latch))
1537 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1538 L);
1539 }
1540 }
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001541 }
1542
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001543 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001544 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001545
1546 // Also check exception blocks (and possibly register them as non-affine
1547 // regions). Even though exception blocks are not modeled, we use them
1548 // to forward-propagate domain constraints during ScopInfo construction.
1549 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1550 return false;
1551
1552 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001553 continue;
1554
Tobias Grosser1d191902014-03-03 13:13:55 +00001555 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001556 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001557 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001558 }
Tobias Grosser75805372011-04-29 06:27:02 +00001559
Sebastian Pope8863b82014-05-12 19:02:02 +00001560 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001561 return false;
1562
Tobias Grosser75805372011-04-29 06:27:02 +00001563 return true;
1564}
1565
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001566bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1567 int NumLoops) const {
1568 int InstCount = 0;
1569
Tobias Grosserb316dc12016-09-08 14:08:05 +00001570 if (NumLoops == 0)
1571 return false;
1572
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001573 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001574 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001575 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001576
1577 InstCount = InstCount / NumLoops;
1578
1579 return InstCount >= ProfitabilityMinPerLoopInstructions;
1580}
1581
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001582bool ScopDetection::hasPossiblyDistributableLoop(
1583 DetectionContext &Context) const {
1584 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001585 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001586 if (!Context.CurRegion.contains(L))
1587 continue;
1588 if (Context.BoxedLoopsSet.count(L))
1589 continue;
1590 unsigned StmtsWithStoresInLoops = 0;
1591 for (auto *LBB : L->blocks()) {
1592 bool MemStore = false;
1593 for (auto &I : *LBB)
1594 MemStore |= isa<StoreInst>(&I);
1595 StmtsWithStoresInLoops += MemStore;
1596 }
1597 return (StmtsWithStoresInLoops > 1);
1598 }
1599 return false;
1600}
1601
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001602bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1603 Region &CurRegion = Context.CurRegion;
1604
1605 if (PollyProcessUnprofitable)
1606 return true;
1607
1608 // We can probably not do a lot on scops that only write or only read
1609 // data.
1610 if (!Context.hasStores || !Context.hasLoads)
1611 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1612
Tobias Grossercd01a362017-02-17 08:12:36 +00001613 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001614 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001615 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001616
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001617 // Scops with at least two loops may allow either loop fusion or tiling and
1618 // are consequently interesting to look at.
1619 if (NumAffineLoops >= 2)
1620 return true;
1621
Michael Krusea6d48f52017-06-08 12:06:15 +00001622 // A loop with multiple non-trivial blocks might be amendable to distribution.
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001623 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1624 return true;
1625
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001626 // Scops that contain a loop with a non-trivial amount of computation per
1627 // loop-iteration are interesting as we may be able to parallelize such
1628 // loops. Individual loops that have only a small amount of computation
1629 // per-iteration are performance-wise very fragile as any change to the
1630 // loop induction variables may affect performance. To not cause spurious
1631 // performance regressions, we do not consider such loops.
1632 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1633 return true;
1634
1635 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001636}
1637
Tobias Grosser75805372011-04-29 06:27:02 +00001638bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001639 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001640
Nicola Zaghen349506a2018-05-15 13:37:17 +00001641 LLVM_DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001642
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001643 if (!PollyAllowFullFunction && CurRegion.isTopLevelRegion()) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00001644 LLVM_DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001645 return false;
1646 }
1647
Tobias Grosser134a5722017-03-07 15:50:43 +00001648 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001649 if (CurRegion.getExit() &&
1650 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00001651 LLVM_DEBUG(dbgs() << "Unreachable in exit\n");
Tobias Grosser134a5722017-03-07 15:50:43 +00001652 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1653 CurRegion.getExit(), DbgLoc);
1654 }
1655
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001656 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00001657 LLVM_DEBUG({
Tobias Grosser4449e522014-01-27 14:24:53 +00001658 dbgs() << "Region entry does not match -polly-region-only";
1659 dbgs() << "\n";
1660 });
1661 return false;
1662 }
1663
Tobias Grosserd654c252012-04-10 18:12:19 +00001664 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001665 // to insert alloca instruction there when translate scalar to array.
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001666 if (!PollyAllowFullFunction &&
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001667 CurRegion.getEntry() ==
1668 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001669 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001670
Hongbin Zheng94868e62012-04-07 12:29:17 +00001671 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001672 return false;
1673
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001674 if (!isReducibleRegion(CurRegion, DbgLoc))
1675 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1676 &CurRegion, DbgLoc);
1677
Nicola Zaghen349506a2018-05-15 13:37:17 +00001678 LLVM_DEBUG(dbgs() << "OK\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001679 return true;
1680}
1681
Tobias Grosser629109b2016-08-03 12:00:07 +00001682void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001683 F->addFnAttr(PollySkipFnAttr);
1684}
1685
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001686bool ScopDetection::isValidFunction(Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001687 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001688}
1689
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001690void ScopDetection::printLocations(Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001691 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001692 unsigned LineEntry, LineExit;
1693 std::string FileName;
1694
Tobias Grosser00dc3092014-03-02 12:02:46 +00001695 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001696 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1697 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001698 }
1699}
1700
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001701void ScopDetection::emitMissedRemarks(const Function &F) {
1702 for (auto &DIt : DetectionContextMap) {
1703 auto &DC = DIt.getSecond();
1704 if (DC.Log.hasErrors())
Eli Friedmane737fc12017-07-17 23:58:33 +00001705 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001706 }
1707}
1708
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001709bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001710 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001711 ///
1712 /// WHITE - Unvisited BB in DFS walk.
1713 /// GREY - BBs which are currently on the DFS stack for processing.
1714 /// BLACK - Visited and completely processed BB.
1715 enum Color { WHITE, GREY, BLACK };
1716
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001717 BasicBlock *REntry = R.getEntry();
1718 BasicBlock *RExit = R.getExit();
1719 // Map to match the color of a BasicBlock during the DFS walk.
1720 DenseMap<const BasicBlock *, Color> BBColorMap;
1721 // Stack keeping track of current BB and index of next child to be processed.
1722 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1723
1724 unsigned AdjacentBlockIndex = 0;
1725 BasicBlock *CurrBB, *SuccBB;
1726 CurrBB = REntry;
1727
1728 // Initialize the map for all BB with WHITE color.
1729 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001730 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001731
1732 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001733 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001734 DFSStack.push(std::make_pair(CurrBB, 0));
1735
1736 while (!DFSStack.empty()) {
1737 // Get next BB on stack to be processed.
1738 CurrBB = DFSStack.top().first;
1739 AdjacentBlockIndex = DFSStack.top().second;
1740 DFSStack.pop();
1741
1742 // Loop to iterate over the successors of current BB.
Chandler Carruthe303c872018-10-15 10:42:50 +00001743 const Instruction *TInst = CurrBB->getTerminator();
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001744 unsigned NSucc = TInst->getNumSuccessors();
1745 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1746 ++I, ++AdjacentBlockIndex) {
1747 SuccBB = TInst->getSuccessor(I);
1748
1749 // Checks for region exit block and self-loops in BB.
1750 if (SuccBB == RExit || SuccBB == CurrBB)
1751 continue;
1752
1753 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001754 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001755 // Push the current BB and the index of the next child to be visited.
1756 DFSStack.push(std::make_pair(CurrBB, I + 1));
1757 // Push the next BB to be processed.
1758 DFSStack.push(std::make_pair(SuccBB, 0));
1759 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001760 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001761 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001762 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001763 // GREY indicates a loop in the control flow.
1764 // If the destination dominates the source, it is a natural loop
1765 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001766 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001767 // Get debug info of instruction which causes irregular control flow.
1768 DbgLoc = TInst->getDebugLoc();
1769 return false;
1770 }
1771 }
1772 }
1773
1774 // If all children of current BB have been processed,
1775 // then mark that BB as fully processed.
1776 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001777 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001778 }
1779
1780 return true;
1781}
1782
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001783static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1784 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001785 if (!OnlyProfitable) {
1786 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001787 MaxNumLoopsInScop =
1788 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00001789 if (Stats.MaxDepth == 0)
1790 NumScopsDepthZero++;
1791 else if (Stats.MaxDepth == 1)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001792 NumScopsDepthOne++;
1793 else if (Stats.MaxDepth == 2)
1794 NumScopsDepthTwo++;
1795 else if (Stats.MaxDepth == 3)
1796 NumScopsDepthThree++;
1797 else if (Stats.MaxDepth == 4)
1798 NumScopsDepthFour++;
1799 else if (Stats.MaxDepth == 5)
1800 NumScopsDepthFive++;
1801 else
1802 NumScopsDepthLarger++;
1803 } else {
1804 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001805 MaxNumLoopsInProfScop =
1806 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00001807 if (Stats.MaxDepth == 0)
1808 NumProfScopsDepthZero++;
1809 else if (Stats.MaxDepth == 1)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001810 NumProfScopsDepthOne++;
1811 else if (Stats.MaxDepth == 2)
1812 NumProfScopsDepthTwo++;
1813 else if (Stats.MaxDepth == 3)
1814 NumProfScopsDepthThree++;
1815 else if (Stats.MaxDepth == 4)
1816 NumProfScopsDepthFour++;
1817 else if (Stats.MaxDepth == 5)
1818 NumProfScopsDepthFive++;
1819 else
1820 NumProfScopsDepthLarger++;
1821 }
1822}
1823
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001824ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001825ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001826 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001827 if (DCMIt == DetectionContextMap.end())
1828 return nullptr;
1829 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001830}
1831
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001832const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1833 const DetectionContext *DC = getDetectionContext(R);
1834 return DC ? &DC->Log : nullptr;
1835}
1836
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001837void ScopDetection::verifyRegion(const Region &R) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001838 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001839
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001840 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001841 isValidRegion(Context);
1842}
1843
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001844void ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001845 if (!VerifyScops)
1846 return;
1847
Tobias Grosser26108892014-04-02 20:18:19 +00001848 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001849 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001850}
1851
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001852bool ScopDetectionWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001853 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1854 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1855 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1856 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1857 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Eli Friedmane737fc12017-07-17 23:58:33 +00001858 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1859 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE));
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001860 return false;
1861}
1862
1863void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001864 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001865 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001866 AU.addRequired<DominatorTreeWrapperPass>();
Eli Friedmane737fc12017-07-17 23:58:33 +00001867 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001868 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001869 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001870 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001871 AU.setPreservesAll();
1872}
1873
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001874void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1875 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001876 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001877
1878 OS << "\n";
1879}
1880
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001881ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1882 // Disable runtime alias checks if we ignore aliasing all together.
1883 if (IgnoreAliasing)
1884 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001885}
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001886
Philip Pfaffef5a43942017-08-02 11:08:01 +00001887ScopAnalysis::ScopAnalysis() {
1888 // Disable runtime alias checks if we ignore aliasing all together.
1889 if (IgnoreAliasing)
1890 PollyUseRuntimeAliasChecks = false;
1891}
Tobias Grosser75805372011-04-29 06:27:02 +00001892
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001893void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001894
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001895char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001896
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001897AnalysisKey ScopAnalysis::Key;
1898
1899ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1900 auto &LI = FAM.getResult<LoopAnalysis>(F);
1901 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1902 auto &AA = FAM.getResult<AAManager>(F);
1903 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1904 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
Eli Friedmane737fc12017-07-17 23:58:33 +00001905 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1906 return {F, DT, SE, LI, RI, AA, ORE};
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001907}
1908
1909PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1910 FunctionAnalysisManager &FAM) {
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001911 OS << "Detected Scops in Function " << F.getName() << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001912 auto &SD = FAM.getResult<ScopAnalysis>(F);
1913 for (const Region *R : SD.ValidRegions)
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001914 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001915
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001916 OS << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001917 return PreservedAnalyses::all();
1918}
1919
1920Pass *polly::createScopDetectionWrapperPassPass() {
1921 return new ScopDetectionWrapperPass();
1922}
1923
1924INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001925 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001926 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001927INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001928INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001929INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001930INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001931INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Eli Friedmane737fc12017-07-17 23:58:33 +00001932INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001933INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001934 "Polly - Detect static control parts (SCoPs)", false, false)