blob: 480589e1f221534a25b2c3bda1f43ef2436a2317 [file] [log] [blame]
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001//===- ScopDetection.cpp - Detect Scops -----------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
Michael Krusea6d48f52017-06-08 12:06:15 +000016// Every Scop fulfills these restrictions:
Tobias Grosser75805372011-04-29 06:27:02 +000017//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000049#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000050#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000051#include "polly/Support/SCEVValidator.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000052#include "polly/Support/ScopHelper.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000054#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/SetVector.h"
56#include "llvm/ADT/SmallPtrSet.h"
57#include "llvm/ADT/SmallVector.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/ADT/Statistic.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000059#include "llvm/ADT/StringRef.h"
Tobias Grosser75805372011-04-29 06:27:02 +000060#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +000061#include "llvm/Analysis/Loads.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000062#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000063#include "llvm/Analysis/MemoryLocation.h"
Adam Nemete0f15412017-10-09 23:49:08 +000064#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000065#include "llvm/Analysis/RegionInfo.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000066#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000067#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000068#include "llvm/IR/BasicBlock.h"
69#include "llvm/IR/Constants.h"
70#include "llvm/IR/DebugLoc.h"
71#include "llvm/IR/DerivedTypes.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000072#include "llvm/IR/DiagnosticInfo.h"
73#include "llvm/IR/DiagnosticPrinter.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000074#include "llvm/IR/Dominators.h"
75#include "llvm/IR/Function.h"
76#include "llvm/IR/InstrTypes.h"
77#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Instructions.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000079#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000080#include "llvm/IR/Intrinsics.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000081#include "llvm/IR/LLVMContext.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000082#include "llvm/IR/Metadata.h"
83#include "llvm/IR/Module.h"
84#include "llvm/IR/PassManager.h"
85#include "llvm/IR/Type.h"
86#include "llvm/IR/Value.h"
87#include "llvm/Pass.h"
88#include "llvm/Support/Casting.h"
89#include "llvm/Support/CommandLine.h"
Tobias Grosser75805372011-04-29 06:27:02 +000090#include "llvm/Support/Debug.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000091#include "llvm/Support/ErrorHandling.h"
Siddharth Bhate2699b52017-07-24 12:40:52 +000092#include "llvm/Support/Regex.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000093#include "llvm/Support/raw_ostream.h"
94#include <algorithm>
95#include <cassert>
96#include <memory>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000097#include <stack>
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000098#include <string>
99#include <utility>
100#include <vector>
Tobias Grosser60b54f12011-11-08 15:41:28 +0000101
Tobias Grosser75805372011-04-29 06:27:02 +0000102using namespace llvm;
103using namespace polly;
104
Chandler Carruth95fef942014-04-22 03:30:19 +0000105#define DEBUG_TYPE "polly-detect"
106
Tobias Grosserc1a269b2015-12-21 21:00:43 +0000107// This option is set to a very high value, as analyzing such loops increases
108// compile time on several cases. For experiments that enable this option,
109// a value of around 40 has been working to avoid run-time regressions with
110// Polly while still exposing interesting optimization opportunities.
111static cl::opt<int> ProfitabilityMinPerLoopInstructions(
112 "polly-detect-profitability-min-per-loop-insts",
113 cl::desc("The minimal number of per-loop instructions before a single loop "
114 "region is considered profitable"),
115 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
116
Tobias Grosser575aca82015-10-06 16:10:29 +0000117bool polly::PollyProcessUnprofitable;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000118
Tobias Grosser575aca82015-10-06 16:10:29 +0000119static cl::opt<bool, true> XPollyProcessUnprofitable(
120 "polly-process-unprofitable",
121 cl::desc(
122 "Process scops that are unlikely to benefit from Polly optimizations."),
123 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
124 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000125
Siddharth Bhat286c9162017-06-09 08:23:40 +0000126static cl::list<std::string> OnlyFunctions(
Tobias Grosser483a90d2014-07-09 10:50:10 +0000127 "polly-only-func",
Siddharth Bhate2699b52017-07-24 12:40:52 +0000128 cl::desc("Only run on functions that match a regex. "
129 "Multiple regexes can be comma separated. "
130 "Scop detection will run on all functions that match "
131 "ANY of the regexes provided."),
Siddharth Bhat286c9162017-06-09 08:23:40 +0000132 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000133
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000134static cl::list<std::string> IgnoredFunctions(
135 "polly-ignore-func",
136 cl::desc("Ignore functions that match a regex. "
137 "Multiple regexes can be comma separated. "
138 "Scop detection will ignore all functions that match "
139 "ANY of the regexes provided."),
140 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
141
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000142bool polly::PollyAllowFullFunction;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000143
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000144static cl::opt<bool, true>
145 XAllowFullFunction("polly-detect-full-functions",
146 cl::desc("Allow the detection of full functions"),
147 cl::location(polly::PollyAllowFullFunction),
148 cl::init(false), cl::cat(PollyCategory));
Tobias Grosserd8945ba2017-05-19 12:13:02 +0000149
Tobias Grosser483a90d2014-07-09 10:50:10 +0000150static cl::opt<std::string> OnlyRegion(
151 "polly-only-region",
152 cl::desc("Only run on certain regions (The provided identifier must "
153 "appear in the name of the region's entry block"),
154 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
155 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000156
Tobias Grosser60cd9322011-11-10 12:47:26 +0000157static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000158 IgnoreAliasing("polly-ignore-aliasing",
159 cl::desc("Ignore possible aliasing of the array bases"),
160 cl::Hidden, cl::init(false), cl::ZeroOrMore,
161 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000162
Johannes Doerfertbda81432016-12-02 17:55:41 +0000163bool polly::PollyAllowUnsignedOperations;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000164
Johannes Doerfertbda81432016-12-02 17:55:41 +0000165static cl::opt<bool, true> XPollyAllowUnsignedOperations(
166 "polly-allow-unsigned-operations",
167 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
168 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
169 cl::init(true), cl::cat(PollyCategory));
170
Johannes Doerfertb164c792014-09-18 11:17:17 +0000171bool polly::PollyUseRuntimeAliasChecks;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000172
Johannes Doerfertb164c792014-09-18 11:17:17 +0000173static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
174 "polly-use-runtime-alias-checks",
175 cl::desc("Use runtime alias checks to resolve possible aliasing."),
176 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
177 cl::init(true), cl::cat(PollyCategory));
178
Tobias Grosser637bd632013-05-07 07:31:10 +0000179static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000180 ReportLevel("polly-report",
181 cl::desc("Print information about the activities of Polly"),
182 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000183
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000184static cl::opt<bool> AllowDifferentTypes(
185 "polly-allow-differing-element-types",
186 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000187 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000188
Tobias Grosser531891e2012-11-01 16:45:20 +0000189static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000190 AllowNonAffine("polly-allow-nonaffine",
191 cl::desc("Allow non affine access functions in arrays"),
192 cl::Hidden, cl::init(false), cl::ZeroOrMore,
193 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000194
Tobias Grosser898a6362016-03-23 06:40:15 +0000195static cl::opt<bool>
196 AllowModrefCall("polly-allow-modref-calls",
197 cl::desc("Allow functions with known modref behavior"),
198 cl::Hidden, cl::init(false), cl::ZeroOrMore,
199 cl::cat(PollyCategory));
200
Johannes Doerfertba65c162015-02-24 11:45:21 +0000201static cl::opt<bool> AllowNonAffineSubRegions(
202 "polly-allow-nonaffine-branches",
203 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000204 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000205
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000206static cl::opt<bool>
207 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
208 cl::desc("Allow non affine conditions for loops"),
209 cl::Hidden, cl::init(false), cl::ZeroOrMore,
210 cl::cat(PollyCategory));
211
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000212static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000213 TrackFailures("polly-detect-track-failures",
214 cl::desc("Track failure strings in detecting scop regions"),
215 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000216 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000217
Andreas Simbuerger04472402014-05-24 09:25:10 +0000218static cl::opt<bool> KeepGoing("polly-detect-keep-going",
219 cl::desc("Do not fail on the first error."),
220 cl::Hidden, cl::ZeroOrMore, cl::init(false),
221 cl::cat(PollyCategory));
222
Sebastian Pop18016682014-04-08 21:20:44 +0000223static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000224 PollyDelinearizeX("polly-delinearize",
225 cl::desc("Delinearize array access functions"),
226 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000227 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000228
Tobias Grossera1689932014-02-18 18:49:49 +0000229static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000230 VerifyScops("polly-detect-verify",
231 cl::desc("Verify the detected SCoPs after each transformation"),
232 cl::Hidden, cl::init(false), cl::ZeroOrMore,
233 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000234
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000235bool polly::PollyInvariantLoadHoisting;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000236
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000237static cl::opt<bool, true> XPollyInvariantLoadHoisting(
238 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
239 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000240 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000241
Tobias Grosserc80d6972016-09-02 06:33:33 +0000242/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000243static const unsigned MIN_LOOP_TRIP_COUNT = 8;
244
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000245bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000246bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000247StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000248
Tobias Grosser75805372011-04-29 06:27:02 +0000249//===----------------------------------------------------------------------===//
250// Statistics.
251
Tobias Grosserb45ae562016-11-26 07:37:46 +0000252STATISTIC(NumScopRegions, "Number of scops");
253STATISTIC(NumLoopsInScop, "Number of loops in scops");
Tobias Grosserfcc3ad52018-04-18 20:03:36 +0000254STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
Tobias Grosserb45ae562016-11-26 07:37:46 +0000255STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
256STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
257STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
258STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
259STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
260STATISTIC(NumScopsDepthLarger,
261 "Number of scops with maximal loop depth 6 and larger");
262STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
263STATISTIC(NumLoopsInProfScop,
264 "Number of loops in scops (profitable scops only)");
265STATISTIC(NumLoopsOverall, "Number of total loops");
Tobias Grosserfcc3ad52018-04-18 20:03:36 +0000266STATISTIC(NumProfScopsDepthZero,
267 "Number of scops with maximal loop depth 0 (profitable scops only)");
Tobias Grosserb45ae562016-11-26 07:37:46 +0000268STATISTIC(NumProfScopsDepthOne,
269 "Number of scops with maximal loop depth 1 (profitable scops only)");
270STATISTIC(NumProfScopsDepthTwo,
271 "Number of scops with maximal loop depth 2 (profitable scops only)");
272STATISTIC(NumProfScopsDepthThree,
273 "Number of scops with maximal loop depth 3 (profitable scops only)");
274STATISTIC(NumProfScopsDepthFour,
275 "Number of scops with maximal loop depth 4 (profitable scops only)");
276STATISTIC(NumProfScopsDepthFive,
277 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000278STATISTIC(NumProfScopsDepthLarger,
279 "Number of scops with maximal loop depth 6 and larger "
280 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000281STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
282STATISTIC(MaxNumLoopsInProfScop,
283 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000284
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000285static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
286 bool OnlyProfitable);
287
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000288namespace {
289
Tobias Grosser8519f892013-12-18 10:49:53 +0000290class DiagnosticScopFound : public DiagnosticInfo {
291private:
292 static int PluginDiagnosticKind;
293
294 Function &F;
295 std::string FileName;
296 unsigned EntryLine, ExitLine;
297
298public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000299 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
300 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000301 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000302 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000303
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000304 void print(DiagnosticPrinter &DP) const override;
Tobias Grosser8519f892013-12-18 10:49:53 +0000305
306 static bool classof(const DiagnosticInfo *DI) {
307 return DI->getKind() == PluginDiagnosticKind;
308 }
309};
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000310} // namespace
311
Tobias Grosserdb6db502016-04-01 07:15:19 +0000312int DiagnosticScopFound::PluginDiagnosticKind =
313 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000314
Tobias Grosser8519f892013-12-18 10:49:53 +0000315void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000316 DP << "Polly detected an optimizable loop region (scop) in function '" << F
317 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000318
319 if (FileName.empty()) {
320 DP << "Scop location is unknown. Compile with debug info "
321 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000322 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000323 }
324
325 DP << FileName << ":" << EntryLine << ": Start of scop\n";
326 DP << FileName << ":" << ExitLine << ": End of scop";
327}
328
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000329/// Check if a string matches any regex in a list of regexes.
330/// @param Str the input string to match against.
331/// @param RegexList a list of strings that are regular expressions.
332static bool doesStringMatchAnyRegex(StringRef Str,
333 const cl::list<std::string> &RegexList) {
334 for (auto RegexStr : RegexList) {
Siddharth Bhate2699b52017-07-24 12:40:52 +0000335 Regex R(RegexStr);
336
337 std::string Err;
338 if (!R.isValid(Err))
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000339 report_fatal_error("invalid regex given as input to polly: " + Err, true);
Siddharth Bhate2699b52017-07-24 12:40:52 +0000340
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000341 if (R.match(Str))
Siddharth Bhat286c9162017-06-09 08:23:40 +0000342 return true;
Siddharth Bhate2699b52017-07-24 12:40:52 +0000343 }
Siddharth Bhat286c9162017-06-09 08:23:40 +0000344 return false;
345}
Tobias Grosser75805372011-04-29 06:27:02 +0000346//===----------------------------------------------------------------------===//
347// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000348
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000349ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
350 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
Eli Friedmane737fc12017-07-17 23:58:33 +0000351 AliasAnalysis &AA, OptimizationRemarkEmitter &ORE)
352 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000353 if (!PollyProcessUnprofitable && LI.empty())
354 return;
355
356 Region *TopRegion = RI.getTopLevelRegion();
357
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000358 if (!OnlyFunctions.empty() &&
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000359 !doesStringMatchAnyRegex(F.getName(), OnlyFunctions))
360 return;
361
362 if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000363 return;
364
365 if (!isValidFunction(F))
366 return;
367
368 findScops(*TopRegion);
369
370 NumScopRegions += ValidRegions.size();
371
372 // Prune non-profitable regions.
373 for (auto &DIt : DetectionContextMap) {
374 auto &DC = DIt.getSecond();
375 if (DC.Log.hasErrors())
376 continue;
377 if (!ValidRegions.count(&DC.CurRegion))
378 continue;
379 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
380 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
381 if (isProfitableRegion(DC)) {
382 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
383 continue;
384 }
385
386 ValidRegions.remove(&DC.CurRegion);
387 }
388
389 NumProfScopRegions += ValidRegions.size();
390 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
391
392 // Only makes sense when we tracked errors.
393 if (PollyTrackFailures)
394 emitMissedRemarks(F);
395
396 if (ReportLevel)
397 printLocations(F);
398
399 assert(ValidRegions.size() <= DetectionContextMap.size() &&
400 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000401}
402
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000403template <class RR, typename... Args>
404inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
405 Args &&... Arguments) const {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000406 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000407 RejectLog &Log = Context.Log;
408 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000409
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000410 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000411 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000412
Nicola Zaghen349506a2018-05-15 13:37:17 +0000413 LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414 LLVM_DEBUG(dbgs() << "\n");
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000415 } else {
416 assert(!Assert && "Verification of detected scop failed");
417 }
418
419 return false;
420}
421
Tobias Grossera1689932014-02-18 18:49:49 +0000422bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
423 if (!ValidRegions.count(&R))
424 return false;
425
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000426 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000427 DetectionContextMap.erase(getBBPairForRegion(&R));
428 const auto &It = DetectionContextMap.insert(std::make_pair(
429 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000430 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000431 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000432 return isValidRegion(Context);
433 }
Tobias Grossera1689932014-02-18 18:49:49 +0000434
435 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000436}
437
Tobias Grosser4f129a62011-10-08 00:30:55 +0000438std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000439 // Get the first error we found. Even in keep-going mode, this is the first
440 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000441 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000442
443 // This can happen when we marked a region invalid, but didn't track
444 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000445 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000446 return "";
447
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000448 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000449 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000450}
451
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000452bool ScopDetection::addOverApproximatedRegion(Region *AR,
453 DetectionContext &Context) const {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000454 // If we already know about Ar we can exit.
455 if (!Context.NonAffineSubRegionSet.insert(AR))
456 return true;
457
458 // All loops in the region have to be overapproximated too if there
459 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000460
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000461 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000462 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000463 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000464 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000465 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000466
467 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000468}
469
Johannes Doerfert09e36972015-10-07 20:17:36 +0000470bool ScopDetection::onlyValidRequiredInvariantLoads(
471 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
472 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000473 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000474
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000475 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
476 return false;
477
Tobias Grosser1c787e02017-03-02 12:15:37 +0000478 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000479 // If we already know a load has been accepted as required invariant, we
480 // already run the validation below once and consequently don't need to
481 // run it again. Hence, we return early. For certain test cases (e.g.,
482 // COSMO this avoids us spending 50% of scop-detection time in this
483 // very function (and its children).
484 if (Context.RequiredILS.count(Load))
485 continue;
Philip Pfaffeec1a3042018-06-29 07:29:45 +0000486 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000487 return false;
488
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000489 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000490 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
491 Load->getAlignment(), DL))
492 continue;
493
Tobias Grosser1c787e02017-03-02 12:15:37 +0000494 if (NonAffineRegion->contains(Load) &&
495 Load->getParent() != NonAffineRegion->getEntry())
496 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000497 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000498 }
499
Johannes Doerfert09e36972015-10-07 20:17:36 +0000500 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
501
502 return true;
503}
504
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000505bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
506 Loop *Scope) const {
507 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000508 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000509 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000510 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000511
512 SmallPtrSet<Value *, 8> PtrVals;
513 for (auto *V : Values) {
514 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
515 V = P2I->getOperand(0);
516
517 if (!V->getType()->isPointerTy())
518 continue;
519
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000520 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000521 if (isa<SCEVConstant>(PtrSCEV))
522 continue;
523
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000524 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000525 if (!BasePtr)
526 return true;
527
528 auto *BasePtrVal = BasePtr->getValue();
529 if (PtrVals.insert(BasePtrVal).second) {
530 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000531 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000532 return true;
533 }
534 }
535
536 return false;
537}
538
Michael Kruse09eb4452016-03-03 22:10:47 +0000539bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000540 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000541 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000542 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000543 return false;
544
545 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
546 return false;
547
548 return true;
549}
550
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000551bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000552 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000553 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000554 Loop *L = LI.getLoopFor(&BB);
555 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000556
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000557 if (IsLoopBranch && L->isLoopLatch(&BB))
558 return false;
559
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000560 // Check for invalid usage of different pointers in one expression.
561 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
562 return false;
563
Michael Kruse09eb4452016-03-03 22:10:47 +0000564 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000565 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000566
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000567 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000568 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000569 return true;
570
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000571 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
572 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000573}
574
575bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000576 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000577 DetectionContext &Context) const {
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000578 // Constant integer conditions are always affine.
579 if (isa<ConstantInt>(Condition))
580 return true;
581
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000582 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
583 auto Opcode = BinOp->getOpcode();
584 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
585 Value *Op0 = BinOp->getOperand(0);
586 Value *Op1 = BinOp->getOperand(1);
587 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
588 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
589 }
590 }
591
Tobias Grosser0a62b2d2017-09-25 16:37:15 +0000592 if (auto PHI = dyn_cast<PHINode>(Condition)) {
593 auto *Unique = dyn_cast_or_null<ConstantInt>(
594 getUniqueNonErrorValue(PHI, &Context.CurRegion, LI, DT));
595 if (Unique && (Unique->isZero() || Unique->isOne()))
596 return true;
597 }
598
Tobias Grosser5e531df2017-09-25 20:27:15 +0000599 if (auto Load = dyn_cast<LoadInst>(Condition))
Michael Krusec0133992017-10-01 22:19:28 +0000600 if (!IsLoopBranch && Context.CurRegion.contains(Load)) {
Tobias Grosser5e531df2017-09-25 20:27:15 +0000601 Context.RequiredILS.insert(Load);
602 return true;
603 }
604
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000605 // Non constant conditions of branches need to be ICmpInst.
606 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000607 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000608 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000609 return true;
610 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000611 }
Tobias Grosser75805372011-04-29 06:27:02 +0000612
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000613 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000614
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000615 // Are both operands of the ICmp affine?
616 if (isa<UndefValue>(ICmp->getOperand(0)) ||
617 isa<UndefValue>(ICmp->getOperand(1)))
618 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000619
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000620 Loop *L = LI.getLoopFor(&BB);
621 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
622 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000623
Tobias Grosseree457592017-09-24 09:25:30 +0000624 LHS = tryForwardThroughPHI(LHS, Context.CurRegion, SE, LI, DT);
625 RHS = tryForwardThroughPHI(RHS, Context.CurRegion, SE, LI, DT);
626
Johannes Doerfertbda81432016-12-02 17:55:41 +0000627 // If unsigned operations are not allowed try to approximate the region.
628 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
629 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000630 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000631
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000632 // Check for invalid usage of different pointers in one expression.
633 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
634 involvesMultiplePtrs(RHS, nullptr, L))
635 return false;
636
637 // Check for invalid usage of different pointers in a relational comparison.
638 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
639 return false;
640
Michael Kruse09eb4452016-03-03 22:10:47 +0000641 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000642 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000643
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000644 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000645 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000646 return true;
647
648 if (IsLoopBranch)
649 return false;
650
651 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
652 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000653}
654
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000655bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000656 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000657 DetectionContext &Context) const {
658 Region &CurRegion = Context.CurRegion;
659
660 TerminatorInst *TI = BB.getTerminator();
661
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000662 if (AllowUnreachable && isa<UnreachableInst>(TI))
663 return true;
664
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000665 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000666 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000667 return true;
668
669 Value *Condition = getConditionFromTerminator(TI);
670
671 if (!Condition)
672 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
673
674 // UndefValue is not allowed as condition.
675 if (isa<UndefValue>(Condition))
676 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
677
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000678 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000679 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000680
681 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
682 assert(SI && "Terminator was neither branch nor switch");
683
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000684 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000685}
686
Johannes Doerfertcea61932016-02-21 19:13:19 +0000687bool ScopDetection::isValidCallInst(CallInst &CI,
688 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000689 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000690 return false;
691
692 if (CI.doesNotAccessMemory())
693 return true;
694
Johannes Doerfertcea61932016-02-21 19:13:19 +0000695 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000696 if (isValidIntrinsicInst(*II, Context))
697 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000698
Tobias Grosser75805372011-04-29 06:27:02 +0000699 Function *CalledFunction = CI.getCalledFunction();
700
701 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000702 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000703 return false;
704
Michael Kruse5369ea52018-04-20 18:55:44 +0000705 if (isDebugCall(&CI)) {
Nicola Zaghen349506a2018-05-15 13:37:17 +0000706 LLVM_DEBUG(dbgs() << "Allow call to debug function: "
707 << CalledFunction->getName() << '\n');
Michael Kruse5369ea52018-04-20 18:55:44 +0000708 return true;
709 }
710
Tobias Grosser898a6362016-03-23 06:40:15 +0000711 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000712 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000713 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000714 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000715 case FMRB_DoesNotAccessMemory:
716 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000717 // Implicitly disable delinearization since we have an unknown
718 // accesses with an unknown access function.
719 Context.HasUnknownAccess = true;
Eli Friedmanefe18d392018-09-11 23:48:14 +0000720 // Explicitly use addUnknown so we don't put a loop-variant
721 // pointer into the alias set.
722 Context.AST.addUnknown(&CI);
Tobias Grosser898a6362016-03-23 06:40:15 +0000723 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000724 case FMRB_OnlyReadsArgumentPointees:
725 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000726 for (const auto &Arg : CI.arg_operands()) {
727 if (!Arg->getType()->isPointerTy())
728 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000729
Tobias Grosser898a6362016-03-23 06:40:15 +0000730 // Bail if a pointer argument has a base address not known to
731 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000732 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000733 if (ArgSCEV->isZero())
734 continue;
735
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000736 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000737 if (!BP)
738 return false;
739
740 // Implicitly disable delinearization since we have an unknown
741 // accesses with an unknown access function.
742 Context.HasUnknownAccess = true;
743 }
744
Eli Friedmanefe18d392018-09-11 23:48:14 +0000745 // Explicitly use addUnknown so we don't put a loop-variant
746 // pointer into the alias set.
747 Context.AST.addUnknown(&CI);
Tobias Grosser898a6362016-03-23 06:40:15 +0000748 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000749 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000750 case FMRB_OnlyAccessesInaccessibleMem:
751 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000752 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000753 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000754 }
755
Johannes Doerfertcea61932016-02-21 19:13:19 +0000756 return false;
757}
758
759bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
760 DetectionContext &Context) const {
761 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000762 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000763
Johannes Doerfertcea61932016-02-21 19:13:19 +0000764 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000765 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000766
767 // The access function and base pointer for memory intrinsics.
768 const SCEV *AF;
769 const SCEVUnknown *BP;
770
771 switch (II.getIntrinsicID()) {
772 // Memory intrinsics that can be represented are supported.
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000773 case Intrinsic::memmove:
774 case Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000775 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000776 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000777 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000778 // Bail if the source pointer is not valid.
779 if (!isValidAccess(&II, AF, BP, Context))
780 return false;
781 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000782 // Fall through
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000783 case Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000784 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000785 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000786 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000787 // Bail if the destination pointer is not valid.
788 if (!isValidAccess(&II, AF, BP, Context))
789 return false;
790 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000791
792 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000793 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000794 Context))
795 return false;
796
797 return true;
798 default:
799 break;
800 }
801
Tobias Grosser75805372011-04-29 06:27:02 +0000802 return false;
803}
804
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000805bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
806 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000807 // A reference to function argument or constant value is invariant.
808 if (isa<Argument>(Val) || isa<Constant>(Val))
809 return true;
810
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000811 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000812 if (!I)
813 return false;
814
815 if (!Reg.contains(I))
816 return true;
817
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000818 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
819 // is not hoistable, it will be rejected later, but here we assume it is and
820 // that makes the value invariant.
821 if (auto LI = dyn_cast<LoadInst>(I)) {
822 Ctx.RequiredILS.insert(LI);
823 return true;
824 }
825
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000826 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000827}
828
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000829namespace {
830
Tobias Grosserc80d6972016-09-02 06:33:33 +0000831/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000832/// register the '...' components.
833///
Michael Krusea6d48f52017-06-08 12:06:15 +0000834/// Array access expressions as they are generated by GFortran contain smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000835/// size) expressions that confuse the 'normal' delinearization algorithm.
836/// However, if we extract such expressions before the normal delinearization
837/// takes place they can actually help to identify array size expressions in
Michael Krusea6d48f52017-06-08 12:06:15 +0000838/// Fortran accesses. For the subsequently following delinearization the smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000839/// size) component can be replaced by just 'size'. This is correct as we will
840/// always add and verify the assumption that for all subscript expressions
841/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
842/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000843class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000844public:
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000845 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
846 : SCEVRewriteVisitor(SE), Terms(Terms) {}
847
Tobias Grosserebb626e2016-10-29 06:19:34 +0000848 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
849 std::vector<const SCEV *> *Terms = nullptr) {
850 SCEVRemoveMax Rewriter(SE, Terms);
851 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000852 }
853
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000854 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000855 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000856 auto Res = visit(Expr->getOperand(1));
857 if (Terms)
858 (*Terms).push_back(Res);
859 return Res;
860 }
861
862 return Expr;
863 }
864
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000865private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000866 std::vector<const SCEV *> *Terms;
867};
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000868} // namespace
869
Tobias Grosserd68ba422015-11-24 05:00:36 +0000870SmallVector<const SCEV *, 4>
871ScopDetection::getDelinearizationTerms(DetectionContext &Context,
872 const SCEVUnknown *BasePointer) const {
873 SmallVector<const SCEV *, 4> Terms;
874 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000875 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000876 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000877 if (!MaxTerms.empty()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000878 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
879 continue;
880 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000881 // In case the outermost expression is a plain add, we check if any of its
882 // terms has the form 4 * %inst * %param * %param ..., aka a term that
883 // contains a product between a parameter and an instruction that is
884 // inside the scop. Such instructions, if allowed at all, are instructions
885 // SCEV can not represent, but Polly is still looking through. As a
886 // result, these instructions can depend on induction variables and are
887 // most likely no array sizes. However, terms that are multiplied with
888 // them are likely candidates for array sizes.
889 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
890 for (auto Op : AF->operands()) {
891 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000892 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000893 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
894 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000895
Tobias Grosserd68ba422015-11-24 05:00:36 +0000896 for (auto *MulOp : AF2->operands()) {
897 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
898 Operands.push_back(Const);
899 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
900 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
901 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000902 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000903
904 } else {
905 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000906 }
907 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000908 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000909 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000910 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000911 }
912 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000913 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000914 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000915 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000916 }
917 return Terms;
918}
Sebastian Pope8863b82014-05-12 19:02:02 +0000919
Tobias Grosserd68ba422015-11-24 05:00:36 +0000920bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
921 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000922 const SCEVUnknown *BasePointer,
923 Loop *Scope) const {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000924 // If no sizes were found, all sizes are trivially valid. We allow this case
925 // to make it possible to pass known-affine accesses to the delinearization to
926 // try to recover some interesting multi-dimensional accesses, but to still
927 // allow the already known to be affine access in case the delinearization
928 // fails. In such situations, the delinearization will just return a Sizes
929 // array of size zero.
930 if (Sizes.size() == 0)
931 return true;
932
Tobias Grosserd68ba422015-11-24 05:00:36 +0000933 Value *BaseValue = BasePointer->getValue();
934 Region &CurRegion = Context.CurRegion;
935 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000936 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000937 Sizes.clear();
938 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000939 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000940 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
941 auto *V = dyn_cast<Value>(Unknown->getValue());
942 if (auto *Load = dyn_cast<LoadInst>(V)) {
943 if (Context.CurRegion.contains(Load) &&
Philip Pfaffeec1a3042018-06-29 07:29:45 +0000944 isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000945 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000946 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000947 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000948 }
Siddharth Bhata1b20862017-07-13 12:18:56 +0000949 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
950 Context.RequiredILS))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000951 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000952 Context, /*Assert=*/true, DelinearizedSize,
953 Context.Accesses[BasePointer].front().first, BaseValue);
954 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000955
Tobias Grosserd68ba422015-11-24 05:00:36 +0000956 // No array shape derived.
957 if (Sizes.empty()) {
958 if (AllowNonAffine)
959 return true;
960
Tobias Grosser230acc42014-09-13 14:47:55 +0000961 for (const auto &Pair : Context.Accesses[BasePointer]) {
962 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000963 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000964
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000965 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000966 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
967 BaseValue);
968 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000969 return false;
970 }
971 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000972 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000973 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000974 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000975}
976
Tobias Grosserd68ba422015-11-24 05:00:36 +0000977// We first store the resulting memory accesses in TempMemoryAccesses. Only
978// if the access functions for all memory accesses have been successfully
979// delinearized we continue. Otherwise, we either report a failure or, if
980// non-affine accesses are allowed, we drop the information. In case the
981// information is dropped the memory accesses need to be overapproximated
982// when translated to a polyhedral representation.
983bool ScopDetection::computeAccessFunctions(
984 DetectionContext &Context, const SCEVUnknown *BasePointer,
985 std::shared_ptr<ArrayShape> Shape) const {
986 Value *BaseValue = BasePointer->getValue();
987 bool BasePtrHasNonAffine = false;
988 MapInsnToMemAcc TempMemoryAccesses;
989 for (const auto &Pair : Context.Accesses[BasePointer]) {
990 const Instruction *Insn = Pair.first;
991 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000992 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000993 bool IsNonAffine = false;
994 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
995 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000996 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000997
998 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000999 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +00001000 Acc->DelinearizedSubscripts.push_back(Pair.second);
1001 else
1002 IsNonAffine = true;
1003 } else {
Tobias Grosser1e55db32017-05-27 15:18:53 +00001004 if (Shape->DelinearizedSizes.size() == 0) {
1005 Acc->DelinearizedSubscripts.push_back(AF);
1006 } else {
1007 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
1008 Shape->DelinearizedSizes);
1009 if (Acc->DelinearizedSubscripts.size() == 0)
1010 IsNonAffine = true;
1011 }
Tobias Grosserd68ba422015-11-24 05:00:36 +00001012 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001013 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +00001014 IsNonAffine = true;
1015 }
1016
1017 // (Possibly) report non affine access
1018 if (IsNonAffine) {
1019 BasePtrHasNonAffine = true;
1020 if (!AllowNonAffine)
1021 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
1022 Insn, BaseValue);
1023 if (!KeepGoing && !AllowNonAffine)
1024 return false;
1025 }
1026 }
1027
1028 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +00001029 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
1030 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +00001031
1032 return true;
1033}
1034
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001035bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
1036 const SCEVUnknown *BasePointer,
1037 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +00001038 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
1039
1040 auto Terms = getDelinearizationTerms(Context, BasePointer);
1041
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001042 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
1043 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +00001044
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001045 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
1046 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +00001047 return false;
1048
1049 return computeAccessFunctions(Context, BasePointer, Shape);
1050}
1051
1052bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +00001053 // TODO: If we have an unknown access and other non-affine accesses we do
1054 // not try to delinearize them for now.
1055 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
1056 return AllowNonAffine;
1057
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001058 for (auto &Pair : Context.NonAffineAccesses) {
1059 auto *BasePointer = Pair.first;
1060 auto *Scope = Pair.second;
1061 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +00001062 if (KeepGoing)
1063 continue;
1064 else
1065 return false;
1066 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001067 }
Tobias Grosserd68ba422015-11-24 05:00:36 +00001068 return true;
1069}
1070
Johannes Doerfertcea61932016-02-21 19:13:19 +00001071bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1072 const SCEVUnknown *BP,
1073 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001074
Johannes Doerfertcea61932016-02-21 19:13:19 +00001075 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +00001076 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001077
Johannes Doerfertcea61932016-02-21 19:13:19 +00001078 auto *BV = BP->getValue();
1079 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +00001080 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001081
Johannes Doerfertcea61932016-02-21 19:13:19 +00001082 // FIXME: Think about allowing IntToPtrInst
1083 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1084 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1085
Tobias Grosser458fb782014-01-28 12:58:58 +00001086 // Check that the base address of the access is invariant in the current
1087 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +00001088 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001089 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +00001090
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001091 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001092
Johannes Doerfertcea61932016-02-21 19:13:19 +00001093 const SCEV *Size;
1094 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001095 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001096 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001097 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001098 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1099 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001100 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +00001101
Johannes Doerfertcea61932016-02-21 19:13:19 +00001102 if (Context.ElementSize[BP]) {
1103 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1104 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1105 Inst, BV);
1106
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001107 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001108 } else {
1109 Context.ElementSize[BP] = Size;
1110 }
1111
1112 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001113 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001114 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001115 for (const Loop *L : Loops)
1116 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001117 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001118
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001119 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001120 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001121 // Do not try to delinearize memory intrinsics and force them to be affine.
1122 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1123 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1124 BV);
1125 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1126 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001127
Tobias Grosser1e55db32017-05-27 15:18:53 +00001128 if (!IsAffine || hasIVParams(AF))
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001129 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001130 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001131 } else if (!AllowNonAffine && !IsAffine) {
1132 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1133 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001134 }
Tobias Grosser75805372011-04-29 06:27:02 +00001135
Tobias Grosser1eedb672014-09-24 21:04:29 +00001136 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001137 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001138
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001139 // Check if the base pointer of the memory access does alias with
1140 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001141 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001142 Inst->getAAMetadata(AATags);
Michael Kruseb67e5d32018-08-17 19:31:41 +00001143 AliasSet &AS = Context.AST.getAliasSetFor(
1144 MemoryLocation(BP->getValue(), MemoryLocation::UnknownSize, AATags));
Tobias Grosser428b3e42013-02-04 15:46:25 +00001145
Tobias Grosser1eedb672014-09-24 21:04:29 +00001146 if (!AS.isMustAlias()) {
1147 if (PollyUseRuntimeAliasChecks) {
1148 bool CanBuildRunTimeCheck = true;
1149 // The run-time alias check places code that involves the base pointer at
1150 // the beginning of the SCoP. This breaks if the base pointer is defined
1151 // inside the scop. Hence, we can only create a run-time check if we are
1152 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001153 // However, we can ignore loads that will be hoisted.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001154
Philip Pfaffeec1a3042018-06-29 07:29:45 +00001155 InvariantLoadsSetTy VariantLS, InvariantLS;
1156 // In order to detect loads which are dependent on other invariant loads
1157 // as invariant, we use fixed-point iteration method here i.e we iterate
1158 // over the alias set for arbitrary number of times until it is safe to
1159 // assume that all the invariant loads have been detected
1160 while (1) {
1161 const unsigned int VariantSize = VariantLS.size(),
1162 InvariantSize = InvariantLS.size();
1163
1164 for (const auto &Ptr : AS) {
1165 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
1166 if (Inst && Context.CurRegion.contains(Inst)) {
1167 auto *Load = dyn_cast<LoadInst>(Inst);
1168 if (Load && InvariantLS.count(Load))
1169 continue;
1170 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT,
1171 InvariantLS)) {
1172 if (VariantLS.count(Load))
1173 VariantLS.remove(Load);
1174 Context.RequiredILS.insert(Load);
1175 InvariantLS.insert(Load);
1176 } else {
1177 CanBuildRunTimeCheck = false;
1178 VariantLS.insert(Load);
1179 }
1180 }
Tobias Grosser1eedb672014-09-24 21:04:29 +00001181 }
Philip Pfaffeec1a3042018-06-29 07:29:45 +00001182
1183 if (InvariantSize == InvariantLS.size() &&
1184 VariantSize == VariantLS.size())
1185 break;
Tobias Grosser1eedb672014-09-24 21:04:29 +00001186 }
1187
1188 if (CanBuildRunTimeCheck)
1189 return true;
1190 }
Michael Kruse70131d32016-01-27 17:09:17 +00001191 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001192 }
Tobias Grosser75805372011-04-29 06:27:02 +00001193
1194 return true;
1195}
1196
Johannes Doerfertcea61932016-02-21 19:13:19 +00001197bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1198 DetectionContext &Context) const {
1199 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001200 Loop *L = LI.getLoopFor(Inst->getParent());
1201 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001202 const SCEVUnknown *BasePointer;
1203
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001204 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001205
1206 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1207}
1208
Tobias Grosser75805372011-04-29 06:27:02 +00001209bool ScopDetection::isValidInstruction(Instruction &Inst,
1210 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001211 for (auto &Op : Inst.operands()) {
1212 auto *OpInst = dyn_cast<Instruction>(&Op);
1213
1214 if (!OpInst)
1215 continue;
1216
Tobias Grosser1f93d0f2017-09-26 15:00:10 +00001217 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT)) {
1218 auto *PHI = dyn_cast<PHINode>(OpInst);
1219 if (PHI) {
1220 for (User *U : PHI->users()) {
Chandler Carruth9ae926b2018-08-26 09:51:22 +00001221 auto *UI = dyn_cast<Instruction>(U);
1222 if (!UI || !UI->isTerminator())
Tobias Grosser1f93d0f2017-09-26 15:00:10 +00001223 return false;
1224 }
1225 } else {
1226 return false;
1227 }
1228 }
Tobias Grosserb12b0062015-11-11 12:44:18 +00001229 }
1230
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001231 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1232 return false;
1233
Tobias Grosser75805372011-04-29 06:27:02 +00001234 // We only check the call instruction but not invoke instruction.
1235 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001236 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001237 return true;
1238
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001239 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001240 }
1241
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001242 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001243 if (!isa<AllocaInst>(Inst))
1244 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001245
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001246 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001247 }
1248
1249 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001250 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001251 Context.hasStores |= isa<StoreInst>(MemInst);
1252 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001253 if (!MemInst.isSimple())
1254 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1255 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001256
Michael Kruse70131d32016-01-27 17:09:17 +00001257 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001258 }
Tobias Grosser75805372011-04-29 06:27:02 +00001259
1260 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001261 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001262}
1263
Tobias Grosser6d0970f2017-08-24 19:47:15 +00001264/// Check whether @p L has exiting blocks.
1265///
1266/// @param L The loop of interest
1267///
1268/// @return True if the loop has exiting blocks, false otherwise.
1269static bool hasExitingBlocks(Loop *L) {
1270 SmallVector<BasicBlock *, 4> ExitingBlocks;
1271 L->getExitingBlocks(ExitingBlocks);
1272 return !ExitingBlocks.empty();
1273}
1274
Johannes Doerfertd020b772015-08-27 06:53:52 +00001275bool ScopDetection::canUseISLTripCount(Loop *L,
1276 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001277 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1278 // need to overapproximate it as a boxed loop.
1279 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001280 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001281 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001282 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001283 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001284 return false;
1285 }
1286
Johannes Doerfertd020b772015-08-27 06:53:52 +00001287 // We can use ISL to compute the trip count of L.
1288 return true;
1289}
1290
Tobias Grosser75805372011-04-29 06:27:02 +00001291bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001292 // Loops that contain part but not all of the blocks of a region cannot be
1293 // handled by the schedule generation. Such loop constructs can happen
1294 // because a region can contain BBs that have no path to the exit block
Tobias Grosser6d0970f2017-08-24 19:47:15 +00001295 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1296 // loop.
1297 //
1298 // _______________
1299 // | Loop Header | <-----------.
1300 // --------------- |
1301 // | |
1302 // _______________ ______________
1303 // | RegionEntry |-----> | RegionExit |----->
1304 // --------------- --------------
1305 // |
1306 // _______________
1307 // | EndlessLoop | <--.
1308 // --------------- |
1309 // | |
1310 // \------------/
1311 //
1312 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1313 // neither entirely contained in the region RegionEntry->RegionExit
1314 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1315 // in the loop.
1316 // The block EndlessLoop is contained in the region because Region::contains
1317 // tests whether it is not dominated by RegionExit. This is probably to not
1318 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1319 // end can also be formed by an UnreachableInst. This case is already caught
1320 // by isErrorBlock(). We hence only have to reject endless loops here.
1321 if (!hasExitingBlocks(L))
1322 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
Tobias Grosser349d1c32016-09-20 17:05:22 +00001323
Michael Krusebeffdb92018-04-25 18:53:33 +00001324 // The algorithm for domain construction assumes that loops has only a single
1325 // exit block (and hence corresponds to a subregion). Note that we cannot use
1326 // L->getExitBlock() because it does not check whether all exiting edges point
1327 // to the same BB.
1328 SmallVector<BasicBlock *, 4> ExitBlocks;
1329 L->getExitBlocks(ExitBlocks);
1330 BasicBlock *TheExitBlock = ExitBlocks[0];
1331 for (BasicBlock *ExitBB : ExitBlocks) {
1332 if (TheExitBlock != ExitBB)
1333 return invalid<ReportLoopHasMultipleExits>(Context, /*Assert=*/true, L);
1334 }
1335
Johannes Doerfertf61df692015-10-04 14:56:08 +00001336 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001337 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001338
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001339 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001340 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001341 while (R != &Context.CurRegion && !R->contains(L))
1342 R = R->getParent();
1343
1344 if (addOverApproximatedRegion(R, Context))
1345 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001346 }
Tobias Grosser75805372011-04-29 06:27:02 +00001347
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001348 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001349 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001350}
1351
Tobias Grosserc80d6972016-09-02 06:33:33 +00001352/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001353/// count that is not known to be less than @MinProfitableTrips.
1354ScopDetection::LoopStats
1355ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001356 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001357 auto *TripCount = SE.getBackedgeTakenCount(L);
1358
Tobias Grosserb45ae562016-11-26 07:37:46 +00001359 int NumLoops = 1;
1360 int MaxLoopDepth = 1;
Michael Kruse7fac28fa2017-08-23 13:29:59 +00001361 if (MinProfitableTrips > 0)
1362 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
1363 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1364 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1365 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001366
Tobias Grosserb45ae562016-11-26 07:37:46 +00001367 for (auto &SubLoop : *L) {
1368 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1369 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001370 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001371 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001372
Tobias Grosserb45ae562016-11-26 07:37:46 +00001373 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001374}
1375
Tobias Grosserb45ae562016-11-26 07:37:46 +00001376ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001377ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1378 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001379 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001380 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001381
Tobias Grossercd01a362017-02-17 08:12:36 +00001382 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser93ab5582017-08-27 21:39:25 +00001383
1384 // If L is fully contained in R, move to first loop surrounding R. Otherwise,
1385 // L is either nullptr or already surrounding R.
1386 if (L && R->contains(L)) {
1387 L = R->outermostLoopInRegion(L);
1388 L = L->getParentLoop();
1389 }
Tobias Grossered21a1f2015-08-27 16:55:18 +00001390
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001391 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001392 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001393
1394 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001395 if (R->contains(SubLoop)) {
1396 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001397 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001398 LoopNum += Stats.NumLoops;
1399 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1400 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001401
Tobias Grosserb45ae562016-11-26 07:37:46 +00001402 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001403}
1404
Tobias Grosser75805372011-04-29 06:27:02 +00001405Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001406 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001407 std::unique_ptr<Region> LastValidRegion;
1408 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001409
Nicola Zaghen349506a2018-05-15 13:37:17 +00001410 LLVM_DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001411
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001412 while (ExpandedRegion) {
Siddharth Bhatc0f5f4d2017-12-05 00:06:09 +00001413 const auto &It = DetectionContextMap.insert(std::make_pair(
1414 getBBPairForRegion(ExpandedRegion.get()),
1415 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001416 DetectionContext &Context = It.first->second;
Nicola Zaghen349506a2018-05-15 13:37:17 +00001417 LLVM_DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001418 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001419
Johannes Doerfert717b8662015-09-08 21:44:27 +00001420 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001421 // If the exit is valid check all blocks
1422 // - if true, a valid region was found => store it + keep expanding
1423 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001424 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1425 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001426 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001427 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001428 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001429
Tobias Grosserd7e58642013-04-10 06:55:45 +00001430 // Store this region, because it is the greatest valid (encountered so
1431 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001432 if (LastValidRegion) {
1433 removeCachedResults(*LastValidRegion);
1434 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1435 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001436 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001437
1438 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001439 ExpandedRegion =
1440 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001441
1442 } else {
1443 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001444 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001445 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001446 ExpandedRegion =
1447 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001448 }
Tobias Grosser75805372011-04-29 06:27:02 +00001449 }
1450
Nicola Zaghen349506a2018-05-15 13:37:17 +00001451 LLVM_DEBUG({
Tobias Grosser378a9f22013-11-16 19:34:11 +00001452 if (LastValidRegion)
1453 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1454 else
1455 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1456 });
Tobias Grosser75805372011-04-29 06:27:02 +00001457
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001458 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001459}
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001460
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001461static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001462 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001463 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001464 return false;
1465
1466 return true;
1467}
Tobias Grosser75805372011-04-29 06:27:02 +00001468
Tobias Grosserb45ae562016-11-26 07:37:46 +00001469void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001470 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001471 if (ValidRegions.count(SubRegion.get())) {
1472 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001473 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001474 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001475 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001476}
1477
Johannes Doerferte46925f2015-10-01 10:59:14 +00001478void ScopDetection::removeCachedResults(const Region &R) {
1479 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001480}
1481
Tobias Grosser75805372011-04-29 06:27:02 +00001482void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001483 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001484 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001485 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001486
1487 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001488 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001489 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001490 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001491 RegionIsValid = isValidRegion(Context);
1492
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001493 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001494
Johannes Doerferte46925f2015-10-01 10:59:14 +00001495 if (HasErrors) {
1496 removeCachedResults(R);
1497 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001498 ValidRegions.insert(&R);
1499 return;
1500 }
1501
David Blaikieb035f6d2014-04-15 18:45:27 +00001502 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001503 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001504
1505 // Try to expand regions.
1506 //
1507 // As the region tree normally only contains canonical regions, non canonical
1508 // regions that form a Scop are not found. Therefore, those non canonical
1509 // regions are checked by expanding the canonical ones.
1510
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001511 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001512
David Blaikieb035f6d2014-04-15 18:45:27 +00001513 for (auto &SubRegion : R)
1514 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001515
Tobias Grosser26108892014-04-02 20:18:19 +00001516 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001517 // Skip invalid regions. Regions may become invalid, if they are element of
1518 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001519 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001520 continue;
1521
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001522 // Skip regions that had errors.
1523 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1524 if (HadErrors)
1525 continue;
1526
Tobias Grosser75805372011-04-29 06:27:02 +00001527 Region *ExpandedR = expandRegion(*CurrentRegion);
1528
1529 if (!ExpandedR)
1530 continue;
1531
1532 R.addSubRegion(ExpandedR, true);
1533 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001534 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001535 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001536 }
1537}
1538
1539bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001540 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001541
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001542 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001543 Loop *L = LI.getLoopFor(BB);
Tobias Grossera3aa4232017-07-15 22:42:17 +00001544 if (L && L->getHeader() == BB) {
1545 if (CurRegion.contains(L)) {
1546 if (!isValidLoop(L, Context) && !KeepGoing)
1547 return false;
1548 } else {
1549 SmallVector<BasicBlock *, 1> Latches;
1550 L->getLoopLatches(Latches);
1551 for (BasicBlock *Latch : Latches)
1552 if (CurRegion.contains(Latch))
1553 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1554 L);
1555 }
1556 }
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001557 }
1558
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001559 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001560 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001561
1562 // Also check exception blocks (and possibly register them as non-affine
1563 // regions). Even though exception blocks are not modeled, we use them
1564 // to forward-propagate domain constraints during ScopInfo construction.
1565 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1566 return false;
1567
1568 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001569 continue;
1570
Tobias Grosser1d191902014-03-03 13:13:55 +00001571 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001572 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001573 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001574 }
Tobias Grosser75805372011-04-29 06:27:02 +00001575
Sebastian Pope8863b82014-05-12 19:02:02 +00001576 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001577 return false;
1578
Tobias Grosser75805372011-04-29 06:27:02 +00001579 return true;
1580}
1581
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001582bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1583 int NumLoops) const {
1584 int InstCount = 0;
1585
Tobias Grosserb316dc12016-09-08 14:08:05 +00001586 if (NumLoops == 0)
1587 return false;
1588
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001589 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001590 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001591 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001592
1593 InstCount = InstCount / NumLoops;
1594
1595 return InstCount >= ProfitabilityMinPerLoopInstructions;
1596}
1597
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001598bool ScopDetection::hasPossiblyDistributableLoop(
1599 DetectionContext &Context) const {
1600 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001601 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001602 if (!Context.CurRegion.contains(L))
1603 continue;
1604 if (Context.BoxedLoopsSet.count(L))
1605 continue;
1606 unsigned StmtsWithStoresInLoops = 0;
1607 for (auto *LBB : L->blocks()) {
1608 bool MemStore = false;
1609 for (auto &I : *LBB)
1610 MemStore |= isa<StoreInst>(&I);
1611 StmtsWithStoresInLoops += MemStore;
1612 }
1613 return (StmtsWithStoresInLoops > 1);
1614 }
1615 return false;
1616}
1617
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001618bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1619 Region &CurRegion = Context.CurRegion;
1620
1621 if (PollyProcessUnprofitable)
1622 return true;
1623
1624 // We can probably not do a lot on scops that only write or only read
1625 // data.
1626 if (!Context.hasStores || !Context.hasLoads)
1627 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1628
Tobias Grossercd01a362017-02-17 08:12:36 +00001629 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001630 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001631 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001632
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001633 // Scops with at least two loops may allow either loop fusion or tiling and
1634 // are consequently interesting to look at.
1635 if (NumAffineLoops >= 2)
1636 return true;
1637
Michael Krusea6d48f52017-06-08 12:06:15 +00001638 // A loop with multiple non-trivial blocks might be amendable to distribution.
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001639 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1640 return true;
1641
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001642 // Scops that contain a loop with a non-trivial amount of computation per
1643 // loop-iteration are interesting as we may be able to parallelize such
1644 // loops. Individual loops that have only a small amount of computation
1645 // per-iteration are performance-wise very fragile as any change to the
1646 // loop induction variables may affect performance. To not cause spurious
1647 // performance regressions, we do not consider such loops.
1648 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1649 return true;
1650
1651 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001652}
1653
Tobias Grosser75805372011-04-29 06:27:02 +00001654bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001655 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001656
Nicola Zaghen349506a2018-05-15 13:37:17 +00001657 LLVM_DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001658
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001659 if (!PollyAllowFullFunction && CurRegion.isTopLevelRegion()) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00001660 LLVM_DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001661 return false;
1662 }
1663
Tobias Grosser134a5722017-03-07 15:50:43 +00001664 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001665 if (CurRegion.getExit() &&
1666 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00001667 LLVM_DEBUG(dbgs() << "Unreachable in exit\n");
Tobias Grosser134a5722017-03-07 15:50:43 +00001668 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1669 CurRegion.getExit(), DbgLoc);
1670 }
1671
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001672 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00001673 LLVM_DEBUG({
Tobias Grosser4449e522014-01-27 14:24:53 +00001674 dbgs() << "Region entry does not match -polly-region-only";
1675 dbgs() << "\n";
1676 });
1677 return false;
1678 }
1679
Tobias Grosserd654c252012-04-10 18:12:19 +00001680 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001681 // to insert alloca instruction there when translate scalar to array.
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001682 if (!PollyAllowFullFunction &&
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001683 CurRegion.getEntry() ==
1684 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001685 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001686
Hongbin Zheng94868e62012-04-07 12:29:17 +00001687 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001688 return false;
1689
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001690 if (!isReducibleRegion(CurRegion, DbgLoc))
1691 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1692 &CurRegion, DbgLoc);
1693
Nicola Zaghen349506a2018-05-15 13:37:17 +00001694 LLVM_DEBUG(dbgs() << "OK\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001695 return true;
1696}
1697
Tobias Grosser629109b2016-08-03 12:00:07 +00001698void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001699 F->addFnAttr(PollySkipFnAttr);
1700}
1701
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001702bool ScopDetection::isValidFunction(Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001703 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001704}
1705
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001706void ScopDetection::printLocations(Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001707 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001708 unsigned LineEntry, LineExit;
1709 std::string FileName;
1710
Tobias Grosser00dc3092014-03-02 12:02:46 +00001711 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001712 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1713 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001714 }
1715}
1716
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001717void ScopDetection::emitMissedRemarks(const Function &F) {
1718 for (auto &DIt : DetectionContextMap) {
1719 auto &DC = DIt.getSecond();
1720 if (DC.Log.hasErrors())
Eli Friedmane737fc12017-07-17 23:58:33 +00001721 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001722 }
1723}
1724
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001725bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001726 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001727 ///
1728 /// WHITE - Unvisited BB in DFS walk.
1729 /// GREY - BBs which are currently on the DFS stack for processing.
1730 /// BLACK - Visited and completely processed BB.
1731 enum Color { WHITE, GREY, BLACK };
1732
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001733 BasicBlock *REntry = R.getEntry();
1734 BasicBlock *RExit = R.getExit();
1735 // Map to match the color of a BasicBlock during the DFS walk.
1736 DenseMap<const BasicBlock *, Color> BBColorMap;
1737 // Stack keeping track of current BB and index of next child to be processed.
1738 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1739
1740 unsigned AdjacentBlockIndex = 0;
1741 BasicBlock *CurrBB, *SuccBB;
1742 CurrBB = REntry;
1743
1744 // Initialize the map for all BB with WHITE color.
1745 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001746 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001747
1748 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001749 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001750 DFSStack.push(std::make_pair(CurrBB, 0));
1751
1752 while (!DFSStack.empty()) {
1753 // Get next BB on stack to be processed.
1754 CurrBB = DFSStack.top().first;
1755 AdjacentBlockIndex = DFSStack.top().second;
1756 DFSStack.pop();
1757
1758 // Loop to iterate over the successors of current BB.
1759 const TerminatorInst *TInst = CurrBB->getTerminator();
1760 unsigned NSucc = TInst->getNumSuccessors();
1761 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1762 ++I, ++AdjacentBlockIndex) {
1763 SuccBB = TInst->getSuccessor(I);
1764
1765 // Checks for region exit block and self-loops in BB.
1766 if (SuccBB == RExit || SuccBB == CurrBB)
1767 continue;
1768
1769 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001770 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001771 // Push the current BB and the index of the next child to be visited.
1772 DFSStack.push(std::make_pair(CurrBB, I + 1));
1773 // Push the next BB to be processed.
1774 DFSStack.push(std::make_pair(SuccBB, 0));
1775 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001776 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001777 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001778 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001779 // GREY indicates a loop in the control flow.
1780 // If the destination dominates the source, it is a natural loop
1781 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001782 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001783 // Get debug info of instruction which causes irregular control flow.
1784 DbgLoc = TInst->getDebugLoc();
1785 return false;
1786 }
1787 }
1788 }
1789
1790 // If all children of current BB have been processed,
1791 // then mark that BB as fully processed.
1792 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001793 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001794 }
1795
1796 return true;
1797}
1798
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001799static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1800 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001801 if (!OnlyProfitable) {
1802 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001803 MaxNumLoopsInScop =
1804 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00001805 if (Stats.MaxDepth == 0)
1806 NumScopsDepthZero++;
1807 else if (Stats.MaxDepth == 1)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001808 NumScopsDepthOne++;
1809 else if (Stats.MaxDepth == 2)
1810 NumScopsDepthTwo++;
1811 else if (Stats.MaxDepth == 3)
1812 NumScopsDepthThree++;
1813 else if (Stats.MaxDepth == 4)
1814 NumScopsDepthFour++;
1815 else if (Stats.MaxDepth == 5)
1816 NumScopsDepthFive++;
1817 else
1818 NumScopsDepthLarger++;
1819 } else {
1820 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001821 MaxNumLoopsInProfScop =
1822 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00001823 if (Stats.MaxDepth == 0)
1824 NumProfScopsDepthZero++;
1825 else if (Stats.MaxDepth == 1)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001826 NumProfScopsDepthOne++;
1827 else if (Stats.MaxDepth == 2)
1828 NumProfScopsDepthTwo++;
1829 else if (Stats.MaxDepth == 3)
1830 NumProfScopsDepthThree++;
1831 else if (Stats.MaxDepth == 4)
1832 NumProfScopsDepthFour++;
1833 else if (Stats.MaxDepth == 5)
1834 NumProfScopsDepthFive++;
1835 else
1836 NumProfScopsDepthLarger++;
1837 }
1838}
1839
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001840ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001841ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001842 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001843 if (DCMIt == DetectionContextMap.end())
1844 return nullptr;
1845 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001846}
1847
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001848const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1849 const DetectionContext *DC = getDetectionContext(R);
1850 return DC ? &DC->Log : nullptr;
1851}
1852
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001853void ScopDetection::verifyRegion(const Region &R) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001854 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001855
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001856 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001857 isValidRegion(Context);
1858}
1859
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001860void ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001861 if (!VerifyScops)
1862 return;
1863
Tobias Grosser26108892014-04-02 20:18:19 +00001864 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001865 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001866}
1867
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001868bool ScopDetectionWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001869 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1870 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1871 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1872 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1873 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Eli Friedmane737fc12017-07-17 23:58:33 +00001874 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1875 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE));
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001876 return false;
1877}
1878
1879void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001880 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001881 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001882 AU.addRequired<DominatorTreeWrapperPass>();
Eli Friedmane737fc12017-07-17 23:58:33 +00001883 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001884 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001885 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001886 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001887 AU.setPreservesAll();
1888}
1889
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001890void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1891 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001892 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001893
1894 OS << "\n";
1895}
1896
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001897ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1898 // Disable runtime alias checks if we ignore aliasing all together.
1899 if (IgnoreAliasing)
1900 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001901}
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001902
Philip Pfaffef5a43942017-08-02 11:08:01 +00001903ScopAnalysis::ScopAnalysis() {
1904 // Disable runtime alias checks if we ignore aliasing all together.
1905 if (IgnoreAliasing)
1906 PollyUseRuntimeAliasChecks = false;
1907}
Tobias Grosser75805372011-04-29 06:27:02 +00001908
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001909void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001910
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001911char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001912
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001913AnalysisKey ScopAnalysis::Key;
1914
1915ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1916 auto &LI = FAM.getResult<LoopAnalysis>(F);
1917 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1918 auto &AA = FAM.getResult<AAManager>(F);
1919 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1920 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
Eli Friedmane737fc12017-07-17 23:58:33 +00001921 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1922 return {F, DT, SE, LI, RI, AA, ORE};
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001923}
1924
1925PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1926 FunctionAnalysisManager &FAM) {
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001927 OS << "Detected Scops in Function " << F.getName() << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001928 auto &SD = FAM.getResult<ScopAnalysis>(F);
1929 for (const Region *R : SD.ValidRegions)
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001930 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001931
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001932 OS << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001933 return PreservedAnalyses::all();
1934}
1935
1936Pass *polly::createScopDetectionWrapperPassPass() {
1937 return new ScopDetectionWrapperPass();
1938}
1939
1940INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001941 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001942 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001943INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001944INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001945INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001946INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001947INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Eli Friedmane737fc12017-07-17 23:58:33 +00001948INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001949INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001950 "Polly - Detect static control parts (SCoPs)", false, false)