blob: 0e8e0efbeafdae60546b7d268ad70e5021ffe5cb [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- ScopDetection.cpp - Detect Scops --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
16// Every Scop fullfills these restrictions:
17//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000050#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +000056#include "llvm/Analysis/Loads.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000059#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000060#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000061#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000062#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000064#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000065#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000066#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000068#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000069
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosserc1a269b2015-12-21 21:00:43 +000075// This option is set to a very high value, as analyzing such loops increases
76// compile time on several cases. For experiments that enable this option,
77// a value of around 40 has been working to avoid run-time regressions with
78// Polly while still exposing interesting optimization opportunities.
79static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80 "polly-detect-profitability-min-per-loop-insts",
81 cl::desc("The minimal number of per-loop instructions before a single loop "
82 "region is considered profitable"),
83 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84
Tobias Grosser575aca82015-10-06 16:10:29 +000085bool polly::PollyProcessUnprofitable;
86static cl::opt<bool, true> XPollyProcessUnprofitable(
87 "polly-process-unprofitable",
88 cl::desc(
89 "Process scops that are unlikely to benefit from Polly optimizations."),
90 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000092
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyFunction(
94 "polly-only-func",
95 cl::desc("Only run on functions that contain a certain string"),
96 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000098
Tobias Grosser483a90d2014-07-09 10:50:10 +000099static cl::opt<std::string> OnlyRegion(
100 "polly-only-region",
101 cl::desc("Only run on certain regions (The provided identifier must "
102 "appear in the name of the region's entry block"),
103 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
104 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000105
Tobias Grosser60cd9322011-11-10 12:47:26 +0000106static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 IgnoreAliasing("polly-ignore-aliasing",
108 cl::desc("Ignore possible aliasing of the array bases"),
109 cl::Hidden, cl::init(false), cl::ZeroOrMore,
110 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000111
Johannes Doerfertbda81432016-12-02 17:55:41 +0000112bool polly::PollyAllowUnsignedOperations;
113static cl::opt<bool, true> XPollyAllowUnsignedOperations(
114 "polly-allow-unsigned-operations",
115 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
116 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Johannes Doerfertb164c792014-09-18 11:17:17 +0000119bool polly::PollyUseRuntimeAliasChecks;
120static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
121 "polly-use-runtime-alias-checks",
122 cl::desc("Use runtime alias checks to resolve possible aliasing."),
123 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
124 cl::init(true), cl::cat(PollyCategory));
125
Tobias Grosser637bd632013-05-07 07:31:10 +0000126static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000127 ReportLevel("polly-report",
128 cl::desc("Print information about the activities of Polly"),
129 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000130
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000131static cl::opt<bool> AllowDifferentTypes(
132 "polly-allow-differing-element-types",
133 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000134 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000135
Tobias Grosser531891e2012-11-01 16:45:20 +0000136static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000137 AllowNonAffine("polly-allow-nonaffine",
138 cl::desc("Allow non affine access functions in arrays"),
139 cl::Hidden, cl::init(false), cl::ZeroOrMore,
140 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000141
Tobias Grosser898a6362016-03-23 06:40:15 +0000142static cl::opt<bool>
143 AllowModrefCall("polly-allow-modref-calls",
144 cl::desc("Allow functions with known modref behavior"),
145 cl::Hidden, cl::init(false), cl::ZeroOrMore,
146 cl::cat(PollyCategory));
147
Johannes Doerfertba65c162015-02-24 11:45:21 +0000148static cl::opt<bool> AllowNonAffineSubRegions(
149 "polly-allow-nonaffine-branches",
150 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000151 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000152
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000153static cl::opt<bool>
154 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
155 cl::desc("Allow non affine conditions for loops"),
156 cl::Hidden, cl::init(false), cl::ZeroOrMore,
157 cl::cat(PollyCategory));
158
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000159static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000160 TrackFailures("polly-detect-track-failures",
161 cl::desc("Track failure strings in detecting scop regions"),
162 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000163 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000164
Andreas Simbuerger04472402014-05-24 09:25:10 +0000165static cl::opt<bool> KeepGoing("polly-detect-keep-going",
166 cl::desc("Do not fail on the first error."),
167 cl::Hidden, cl::ZeroOrMore, cl::init(false),
168 cl::cat(PollyCategory));
169
Sebastian Pop18016682014-04-08 21:20:44 +0000170static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000171 PollyDelinearizeX("polly-delinearize",
172 cl::desc("Delinearize array access functions"),
173 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000174 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000175
Tobias Grossera1689932014-02-18 18:49:49 +0000176static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000177 VerifyScops("polly-detect-verify",
178 cl::desc("Verify the detected SCoPs after each transformation"),
179 cl::Hidden, cl::init(false), cl::ZeroOrMore,
180 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000181
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000182bool polly::PollyInvariantLoadHoisting;
183static cl::opt<bool, true> XPollyInvariantLoadHoisting(
184 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
185 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000186 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000187
Tobias Grosserc80d6972016-09-02 06:33:33 +0000188/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000189static const unsigned MIN_LOOP_TRIP_COUNT = 8;
190
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000191bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000192bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000193StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000194
Tobias Grosser75805372011-04-29 06:27:02 +0000195//===----------------------------------------------------------------------===//
196// Statistics.
197
Tobias Grosserb45ae562016-11-26 07:37:46 +0000198STATISTIC(NumScopRegions, "Number of scops");
199STATISTIC(NumLoopsInScop, "Number of loops in scops");
200STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
201STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
202STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
203STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
204STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
205STATISTIC(NumScopsDepthLarger,
206 "Number of scops with maximal loop depth 6 and larger");
207STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
208STATISTIC(NumLoopsInProfScop,
209 "Number of loops in scops (profitable scops only)");
210STATISTIC(NumLoopsOverall, "Number of total loops");
211STATISTIC(NumProfScopsDepthOne,
212 "Number of scops with maximal loop depth 1 (profitable scops only)");
213STATISTIC(NumProfScopsDepthTwo,
214 "Number of scops with maximal loop depth 2 (profitable scops only)");
215STATISTIC(NumProfScopsDepthThree,
216 "Number of scops with maximal loop depth 3 (profitable scops only)");
217STATISTIC(NumProfScopsDepthFour,
218 "Number of scops with maximal loop depth 4 (profitable scops only)");
219STATISTIC(NumProfScopsDepthFive,
220 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000221STATISTIC(NumProfScopsDepthLarger,
222 "Number of scops with maximal loop depth 6 and larger "
223 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000224STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
225STATISTIC(MaxNumLoopsInProfScop,
226 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000227
Tobias Grosser8519f892013-12-18 10:49:53 +0000228class DiagnosticScopFound : public DiagnosticInfo {
229private:
230 static int PluginDiagnosticKind;
231
232 Function &F;
233 std::string FileName;
234 unsigned EntryLine, ExitLine;
235
236public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000237 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
238 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000239 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000240 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000241
242 virtual void print(DiagnosticPrinter &DP) const;
243
244 static bool classof(const DiagnosticInfo *DI) {
245 return DI->getKind() == PluginDiagnosticKind;
246 }
247};
248
Tobias Grosserdb6db502016-04-01 07:15:19 +0000249int DiagnosticScopFound::PluginDiagnosticKind =
250 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000251
Tobias Grosser8519f892013-12-18 10:49:53 +0000252void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000253 DP << "Polly detected an optimizable loop region (scop) in function '" << F
254 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000255
256 if (FileName.empty()) {
257 DP << "Scop location is unknown. Compile with debug info "
258 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000259 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000260 }
261
262 DP << FileName << ":" << EntryLine << ": Start of scop\n";
263 DP << FileName << ":" << ExitLine << ": End of scop";
264}
265
Tobias Grosser75805372011-04-29 06:27:02 +0000266//===----------------------------------------------------------------------===//
267// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000268
Johannes Doerfertb164c792014-09-18 11:17:17 +0000269ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000270 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000271 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000272 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000273}
274
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000275template <class RR, typename... Args>
276inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
277 Args &&... Arguments) const {
278
279 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000280 RejectLog &Log = Context.Log;
281 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000282
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000283 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000284 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000285
286 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000287 DEBUG(dbgs() << "\n");
288 } else {
289 assert(!Assert && "Verification of detected scop failed");
290 }
291
292 return false;
293}
294
Tobias Grossera1689932014-02-18 18:49:49 +0000295bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
296 if (!ValidRegions.count(&R))
297 return false;
298
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000299 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000300 DetectionContextMap.erase(getBBPairForRegion(&R));
301 const auto &It = DetectionContextMap.insert(std::make_pair(
302 getBBPairForRegion(&R),
303 DetectionContext(const_cast<Region &>(R), *AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000304 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000305 return isValidRegion(Context);
306 }
Tobias Grossera1689932014-02-18 18:49:49 +0000307
308 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000309}
310
Tobias Grosser4f129a62011-10-08 00:30:55 +0000311std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000312 // Get the first error we found. Even in keep-going mode, this is the first
313 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000314 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000315
316 // This can happen when we marked a region invalid, but didn't track
317 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000318 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000319 return "";
320
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000321 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000322 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000323}
324
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000325bool ScopDetection::addOverApproximatedRegion(Region *AR,
326 DetectionContext &Context) const {
327
328 // If we already know about Ar we can exit.
329 if (!Context.NonAffineSubRegionSet.insert(AR))
330 return true;
331
332 // All loops in the region have to be overapproximated too if there
333 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000334
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000335 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000336 Loop *L = LI->getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000337 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000338 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000339 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000340
341 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000342}
343
Johannes Doerfert09e36972015-10-07 20:17:36 +0000344bool ScopDetection::onlyValidRequiredInvariantLoads(
345 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
346 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000347 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000348
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000349 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
350 return false;
351
Tobias Grosser1c787e02017-03-02 12:15:37 +0000352 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000353 // If we already know a load has been accepted as required invariant, we
354 // already run the validation below once and consequently don't need to
355 // run it again. Hence, we return early. For certain test cases (e.g.,
356 // COSMO this avoids us spending 50% of scop-detection time in this
357 // very function (and its children).
358 if (Context.RequiredILS.count(Load))
359 continue;
360
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000361 if (!isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000362 return false;
363
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000364 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
365
366 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
367 Load->getAlignment(), DL))
368 continue;
369
Tobias Grosser1c787e02017-03-02 12:15:37 +0000370 if (NonAffineRegion->contains(Load) &&
371 Load->getParent() != NonAffineRegion->getEntry())
372 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000373 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000374 }
375
Johannes Doerfert09e36972015-10-07 20:17:36 +0000376 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
377
378 return true;
379}
380
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000381bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
382 Loop *Scope) const {
383 SetVector<Value *> Values;
384 findValues(S0, *SE, Values);
385 if (S1)
386 findValues(S1, *SE, Values);
387
388 SmallPtrSet<Value *, 8> PtrVals;
389 for (auto *V : Values) {
390 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
391 V = P2I->getOperand(0);
392
393 if (!V->getType()->isPointerTy())
394 continue;
395
396 auto *PtrSCEV = SE->getSCEVAtScope(V, Scope);
397 if (isa<SCEVConstant>(PtrSCEV))
398 continue;
399
400 auto *BasePtr = dyn_cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
401 if (!BasePtr)
402 return true;
403
404 auto *BasePtrVal = BasePtr->getValue();
405 if (PtrVals.insert(BasePtrVal).second) {
406 for (auto *PtrVal : PtrVals)
407 if (PtrVal != BasePtrVal && !AA->isNoAlias(PtrVal, BasePtrVal))
408 return true;
409 }
410 }
411
412 return false;
413}
414
Michael Kruse09eb4452016-03-03 22:10:47 +0000415bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000416 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000417
418 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000419 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000420 return false;
421
422 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
423 return false;
424
425 return true;
426}
427
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000428bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000429 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000430 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000431 Loop *L = LI->getLoopFor(&BB);
432 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000433
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000434 if (IsLoopBranch && L->isLoopLatch(&BB))
435 return false;
436
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000437 // Check for invalid usage of different pointers in one expression.
438 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
439 return false;
440
Michael Kruse09eb4452016-03-03 22:10:47 +0000441 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000442 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000443
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000444 if (AllowNonAffineSubRegions &&
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000445 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
446 return true;
447
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000448 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
449 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000450}
451
452bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000453 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000454 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000455
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000456 // Constant integer conditions are always affine.
457 if (isa<ConstantInt>(Condition))
458 return true;
459
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000460 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
461 auto Opcode = BinOp->getOpcode();
462 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
463 Value *Op0 = BinOp->getOperand(0);
464 Value *Op1 = BinOp->getOperand(1);
465 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
466 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
467 }
468 }
469
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000470 // Non constant conditions of branches need to be ICmpInst.
471 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000472 if (!IsLoopBranch && AllowNonAffineSubRegions &&
473 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
474 return true;
475 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000476 }
Tobias Grosser75805372011-04-29 06:27:02 +0000477
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000478 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000479
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000480 // Are both operands of the ICmp affine?
481 if (isa<UndefValue>(ICmp->getOperand(0)) ||
482 isa<UndefValue>(ICmp->getOperand(1)))
483 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000484
Tobias Grossera2f8fa32016-11-13 19:27:04 +0000485 Loop *L = LI->getLoopFor(&BB);
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000486 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
487 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000488
Johannes Doerfertbda81432016-12-02 17:55:41 +0000489 // If unsigned operations are not allowed try to approximate the region.
490 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
491 return !IsLoopBranch && AllowNonAffineSubRegions &&
492 addOverApproximatedRegion(RI->getRegionFor(&BB), Context);
493
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000494 // Check for invalid usage of different pointers in one expression.
495 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
496 involvesMultiplePtrs(RHS, nullptr, L))
497 return false;
498
499 // Check for invalid usage of different pointers in a relational comparison.
500 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
501 return false;
502
Michael Kruse09eb4452016-03-03 22:10:47 +0000503 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000504 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000505
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000506 if (!IsLoopBranch && AllowNonAffineSubRegions &&
507 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
508 return true;
509
510 if (IsLoopBranch)
511 return false;
512
513 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
514 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000515}
516
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000517bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000518 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000519 DetectionContext &Context) const {
520 Region &CurRegion = Context.CurRegion;
521
522 TerminatorInst *TI = BB.getTerminator();
523
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000524 if (AllowUnreachable && isa<UnreachableInst>(TI))
525 return true;
526
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000527 // Return instructions are only valid if the region is the top level region.
528 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
529 return true;
530
531 Value *Condition = getConditionFromTerminator(TI);
532
533 if (!Condition)
534 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
535
536 // UndefValue is not allowed as condition.
537 if (isa<UndefValue>(Condition))
538 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
539
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000540 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000541 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000542
543 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
544 assert(SI && "Terminator was neither branch nor switch");
545
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000546 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000547}
548
Johannes Doerfertcea61932016-02-21 19:13:19 +0000549bool ScopDetection::isValidCallInst(CallInst &CI,
550 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000551 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000552 return false;
553
554 if (CI.doesNotAccessMemory())
555 return true;
556
Johannes Doerfertcea61932016-02-21 19:13:19 +0000557 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000558 if (isValidIntrinsicInst(*II, Context))
559 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000560
Tobias Grosser75805372011-04-29 06:27:02 +0000561 Function *CalledFunction = CI.getCalledFunction();
562
563 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000564 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000565 return false;
566
Tobias Grosser898a6362016-03-23 06:40:15 +0000567 if (AllowModrefCall) {
568 switch (AA->getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000569 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000570 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000571 case FMRB_DoesNotAccessMemory:
572 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000573 // Implicitly disable delinearization since we have an unknown
574 // accesses with an unknown access function.
575 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000576 Context.AST.add(&CI);
577 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000578 case FMRB_OnlyReadsArgumentPointees:
579 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000580 for (const auto &Arg : CI.arg_operands()) {
581 if (!Arg->getType()->isPointerTy())
582 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000583
Tobias Grosser898a6362016-03-23 06:40:15 +0000584 // Bail if a pointer argument has a base address not known to
585 // ScalarEvolution. Note that a zero pointer is acceptable.
586 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
587 if (ArgSCEV->isZero())
588 continue;
589
590 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
591 if (!BP)
592 return false;
593
594 // Implicitly disable delinearization since we have an unknown
595 // accesses with an unknown access function.
596 Context.HasUnknownAccess = true;
597 }
598
599 Context.AST.add(&CI);
600 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000601 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000602 case FMRB_OnlyAccessesInaccessibleMem:
603 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000604 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000605 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000606 }
607
Johannes Doerfertcea61932016-02-21 19:13:19 +0000608 return false;
609}
610
611bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
612 DetectionContext &Context) const {
613 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000614 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000615
Johannes Doerfertcea61932016-02-21 19:13:19 +0000616 // The closest loop surrounding the call instruction.
617 Loop *L = LI->getLoopFor(II.getParent());
618
619 // The access function and base pointer for memory intrinsics.
620 const SCEV *AF;
621 const SCEVUnknown *BP;
622
623 switch (II.getIntrinsicID()) {
624 // Memory intrinsics that can be represented are supported.
625 case llvm::Intrinsic::memmove:
626 case llvm::Intrinsic::memcpy:
627 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000628 if (!AF->isZero()) {
629 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
630 // Bail if the source pointer is not valid.
631 if (!isValidAccess(&II, AF, BP, Context))
632 return false;
633 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000634 // Fall through
635 case llvm::Intrinsic::memset:
636 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000637 if (!AF->isZero()) {
638 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
639 // Bail if the destination pointer is not valid.
640 if (!isValidAccess(&II, AF, BP, Context))
641 return false;
642 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000643
644 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000645 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000646 Context))
647 return false;
648
649 return true;
650 default:
651 break;
652 }
653
Tobias Grosser75805372011-04-29 06:27:02 +0000654 return false;
655}
656
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000657bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
658 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000659 // A reference to function argument or constant value is invariant.
660 if (isa<Argument>(Val) || isa<Constant>(Val))
661 return true;
662
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000663 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000664 if (!I)
665 return false;
666
667 if (!Reg.contains(I))
668 return true;
669
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000670 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
671 // is not hoistable, it will be rejected later, but here we assume it is and
672 // that makes the value invariant.
673 if (auto LI = dyn_cast<LoadInst>(I)) {
674 Ctx.RequiredILS.insert(LI);
675 return true;
676 }
677
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000678 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000679}
680
Tobias Grosserc80d6972016-09-02 06:33:33 +0000681/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000682/// register the '...' components.
683///
684/// Array access expressions as they are generated by gfortran contain smax(0,
685/// size) expressions that confuse the 'normal' delinearization algorithm.
686/// However, if we extract such expressions before the normal delinearization
687/// takes place they can actually help to identify array size expressions in
688/// fortran accesses. For the subsequently following delinearization the smax(0,
689/// size) component can be replaced by just 'size'. This is correct as we will
690/// always add and verify the assumption that for all subscript expressions
691/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
692/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000693class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000694public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000695 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
696 std::vector<const SCEV *> *Terms = nullptr) {
697 SCEVRemoveMax Rewriter(SE, Terms);
698 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000699 }
700
701 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000702 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000703
704 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000705 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000706 auto Res = visit(Expr->getOperand(1));
707 if (Terms)
708 (*Terms).push_back(Res);
709 return Res;
710 }
711
712 return Expr;
713 }
714
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000715private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000716 std::vector<const SCEV *> *Terms;
717};
718
Tobias Grosserd68ba422015-11-24 05:00:36 +0000719SmallVector<const SCEV *, 4>
720ScopDetection::getDelinearizationTerms(DetectionContext &Context,
721 const SCEVUnknown *BasePointer) const {
722 SmallVector<const SCEV *, 4> Terms;
723 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000724 std::vector<const SCEV *> MaxTerms;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000725 SCEVRemoveMax::rewrite(Pair.second, *SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000726 if (MaxTerms.size() > 0) {
727 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
728 continue;
729 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000730 // In case the outermost expression is a plain add, we check if any of its
731 // terms has the form 4 * %inst * %param * %param ..., aka a term that
732 // contains a product between a parameter and an instruction that is
733 // inside the scop. Such instructions, if allowed at all, are instructions
734 // SCEV can not represent, but Polly is still looking through. As a
735 // result, these instructions can depend on induction variables and are
736 // most likely no array sizes. However, terms that are multiplied with
737 // them are likely candidates for array sizes.
738 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
739 for (auto Op : AF->operands()) {
740 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
741 SE->collectParametricTerms(AF2, Terms);
742 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
743 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000744
Tobias Grosserd68ba422015-11-24 05:00:36 +0000745 for (auto *MulOp : AF2->operands()) {
746 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
747 Operands.push_back(Const);
748 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
749 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
750 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000751 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000752
753 } else {
754 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000755 }
756 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000757 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000758 if (Operands.size())
759 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000760 }
761 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000762 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000763 if (Terms.empty())
764 SE->collectParametricTerms(Pair.second, Terms);
765 }
766 return Terms;
767}
Sebastian Pope8863b82014-05-12 19:02:02 +0000768
Tobias Grosserd68ba422015-11-24 05:00:36 +0000769bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
770 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000771 const SCEVUnknown *BasePointer,
772 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000773 Value *BaseValue = BasePointer->getValue();
774 Region &CurRegion = Context.CurRegion;
775 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000776 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000777 Sizes.clear();
778 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000779 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000780 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
781 auto *V = dyn_cast<Value>(Unknown->getValue());
782 if (auto *Load = dyn_cast<LoadInst>(V)) {
783 if (Context.CurRegion.contains(Load) &&
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000784 isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000785 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000786 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000787 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000788 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000789 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000790 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000791 Context, /*Assert=*/true, DelinearizedSize,
792 Context.Accesses[BasePointer].front().first, BaseValue);
793 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000794
Tobias Grosserd68ba422015-11-24 05:00:36 +0000795 // No array shape derived.
796 if (Sizes.empty()) {
797 if (AllowNonAffine)
798 return true;
799
Tobias Grosser230acc42014-09-13 14:47:55 +0000800 for (const auto &Pair : Context.Accesses[BasePointer]) {
801 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000802 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000803
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000804 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000805 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
806 BaseValue);
807 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000808 return false;
809 }
810 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000811 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000812 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000813 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000814}
815
Tobias Grosserd68ba422015-11-24 05:00:36 +0000816// We first store the resulting memory accesses in TempMemoryAccesses. Only
817// if the access functions for all memory accesses have been successfully
818// delinearized we continue. Otherwise, we either report a failure or, if
819// non-affine accesses are allowed, we drop the information. In case the
820// information is dropped the memory accesses need to be overapproximated
821// when translated to a polyhedral representation.
822bool ScopDetection::computeAccessFunctions(
823 DetectionContext &Context, const SCEVUnknown *BasePointer,
824 std::shared_ptr<ArrayShape> Shape) const {
825 Value *BaseValue = BasePointer->getValue();
826 bool BasePtrHasNonAffine = false;
827 MapInsnToMemAcc TempMemoryAccesses;
828 for (const auto &Pair : Context.Accesses[BasePointer]) {
829 const Instruction *Insn = Pair.first;
830 auto *AF = Pair.second;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000831 AF = SCEVRemoveMax::rewrite(AF, *SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000832 bool IsNonAffine = false;
833 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
834 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000835 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000836
837 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000838 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000839 Acc->DelinearizedSubscripts.push_back(Pair.second);
840 else
841 IsNonAffine = true;
842 } else {
843 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
844 Shape->DelinearizedSizes);
845 if (Acc->DelinearizedSubscripts.size() == 0)
846 IsNonAffine = true;
847 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000848 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000849 IsNonAffine = true;
850 }
851
852 // (Possibly) report non affine access
853 if (IsNonAffine) {
854 BasePtrHasNonAffine = true;
855 if (!AllowNonAffine)
856 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
857 Insn, BaseValue);
858 if (!KeepGoing && !AllowNonAffine)
859 return false;
860 }
861 }
862
863 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000864 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
865 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000866
867 return true;
868}
869
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000870bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
871 const SCEVUnknown *BasePointer,
872 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000873 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
874
875 auto Terms = getDelinearizationTerms(Context, BasePointer);
876
877 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
878 Context.ElementSize[BasePointer]);
879
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000880 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
881 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000882 return false;
883
884 return computeAccessFunctions(Context, BasePointer, Shape);
885}
886
887bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000888 // TODO: If we have an unknown access and other non-affine accesses we do
889 // not try to delinearize them for now.
890 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
891 return AllowNonAffine;
892
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000893 for (auto &Pair : Context.NonAffineAccesses) {
894 auto *BasePointer = Pair.first;
895 auto *Scope = Pair.second;
896 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000897 if (KeepGoing)
898 continue;
899 else
900 return false;
901 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000902 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000903 return true;
904}
905
Johannes Doerfertcea61932016-02-21 19:13:19 +0000906bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
907 const SCEVUnknown *BP,
908 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000909
Johannes Doerfertcea61932016-02-21 19:13:19 +0000910 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000911 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000912
Johannes Doerfertcea61932016-02-21 19:13:19 +0000913 auto *BV = BP->getValue();
914 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000915 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000916
Johannes Doerfertcea61932016-02-21 19:13:19 +0000917 // FIXME: Think about allowing IntToPtrInst
918 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
919 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
920
Tobias Grosser458fb782014-01-28 12:58:58 +0000921 // Check that the base address of the access is invariant in the current
922 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000923 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000924 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000925
Johannes Doerfertcea61932016-02-21 19:13:19 +0000926 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000927
Johannes Doerfertcea61932016-02-21 19:13:19 +0000928 const SCEV *Size;
929 if (!isa<MemIntrinsic>(Inst)) {
930 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000931 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000932 auto *SizeTy =
933 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
934 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000935 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000936
Johannes Doerfertcea61932016-02-21 19:13:19 +0000937 if (Context.ElementSize[BP]) {
938 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
939 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
940 Inst, BV);
941
942 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
943 } else {
944 Context.ElementSize[BP] = Size;
945 }
946
947 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000948 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000949 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000950 for (const Loop *L : Loops)
951 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000952 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000953
Michael Kruse09eb4452016-03-03 22:10:47 +0000954 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000955 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000956 // Do not try to delinearize memory intrinsics and force them to be affine.
957 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
958 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
959 BV);
960 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
961 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000962
Johannes Doerfertcea61932016-02-21 19:13:19 +0000963 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000964 Context.NonAffineAccesses.insert(
965 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000966 } else if (!AllowNonAffine && !IsAffine) {
967 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
968 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000969 }
Tobias Grosser75805372011-04-29 06:27:02 +0000970
Tobias Grosser1eedb672014-09-24 21:04:29 +0000971 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000972 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000973
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000974 // Check if the base pointer of the memory access does alias with
975 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000976 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000977 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000978 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000979 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000980
Tobias Grosser1eedb672014-09-24 21:04:29 +0000981 if (!AS.isMustAlias()) {
982 if (PollyUseRuntimeAliasChecks) {
983 bool CanBuildRunTimeCheck = true;
984 // The run-time alias check places code that involves the base pointer at
985 // the beginning of the SCoP. This breaks if the base pointer is defined
986 // inside the scop. Hence, we can only create a run-time check if we are
987 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000988 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000989 for (const auto &Ptr : AS) {
990 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000991 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000992 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000993 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE, *DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000994 Context.RequiredILS.insert(Load);
995 continue;
996 }
997
Tobias Grosser1eedb672014-09-24 21:04:29 +0000998 CanBuildRunTimeCheck = false;
999 break;
1000 }
1001 }
1002
1003 if (CanBuildRunTimeCheck)
1004 return true;
1005 }
Michael Kruse70131d32016-01-27 17:09:17 +00001006 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001007 }
Tobias Grosser75805372011-04-29 06:27:02 +00001008
1009 return true;
1010}
1011
Johannes Doerfertcea61932016-02-21 19:13:19 +00001012bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1013 DetectionContext &Context) const {
1014 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +00001015 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001016 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
1017 const SCEVUnknown *BasePointer;
1018
1019 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
1020
1021 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1022}
1023
Tobias Grosser75805372011-04-29 06:27:02 +00001024bool ScopDetection::isValidInstruction(Instruction &Inst,
1025 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001026 for (auto &Op : Inst.operands()) {
1027 auto *OpInst = dyn_cast<Instruction>(&Op);
1028
1029 if (!OpInst)
1030 continue;
1031
1032 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
1033 return false;
1034 }
1035
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001036 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1037 return false;
1038
Tobias Grosser75805372011-04-29 06:27:02 +00001039 // We only check the call instruction but not invoke instruction.
1040 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001041 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001042 return true;
1043
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001044 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001045 }
1046
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001047 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001048 if (!isa<AllocaInst>(Inst))
1049 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001050
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001051 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001052 }
1053
1054 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001055 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001056 Context.hasStores |= isa<StoreInst>(MemInst);
1057 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001058 if (!MemInst.isSimple())
1059 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1060 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001061
Michael Kruse70131d32016-01-27 17:09:17 +00001062 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001063 }
Tobias Grosser75805372011-04-29 06:27:02 +00001064
1065 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001066 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001067}
1068
Tobias Grosser349d1c32016-09-20 17:05:22 +00001069/// Check whether @p L has exiting blocks.
1070///
1071/// @param L The loop of interest
1072///
1073/// @return True if the loop has exiting blocks, false otherwise.
1074static bool hasExitingBlocks(Loop *L) {
1075 SmallVector<BasicBlock *, 4> ExitingBlocks;
1076 L->getExitingBlocks(ExitingBlocks);
1077 return !ExitingBlocks.empty();
1078}
1079
Johannes Doerfertd020b772015-08-27 06:53:52 +00001080bool ScopDetection::canUseISLTripCount(Loop *L,
1081 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001082 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1083 // need to overapproximate it as a boxed loop.
1084 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001085 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001086 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001087 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001088 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001089 return false;
1090 }
1091
Johannes Doerfertd020b772015-08-27 06:53:52 +00001092 // We can use ISL to compute the trip count of L.
1093 return true;
1094}
1095
Tobias Grosser75805372011-04-29 06:27:02 +00001096bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001097 // Loops that contain part but not all of the blocks of a region cannot be
1098 // handled by the schedule generation. Such loop constructs can happen
1099 // because a region can contain BBs that have no path to the exit block
1100 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1101 // loop.
1102 //
1103 // _______________
1104 // | Loop Header | <-----------.
1105 // --------------- |
1106 // | |
1107 // _______________ ______________
1108 // | RegionEntry |-----> | RegionExit |----->
1109 // --------------- --------------
1110 // |
1111 // _______________
1112 // | EndlessLoop | <--.
1113 // --------------- |
1114 // | |
1115 // \------------/
1116 //
1117 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1118 // neither entirely contained in the region RegionEntry->RegionExit
1119 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1120 // in the loop.
1121 // The block EndlessLoop is contained in the region because Region::contains
1122 // tests whether it is not dominated by RegionExit. This is probably to not
1123 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1124 // end can also be formed by an UnreachableInst. This case is already caught
1125 // by isErrorBlock(). We hence only have to reject endless loops here.
1126 if (!hasExitingBlocks(L))
1127 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1128
Johannes Doerfertf61df692015-10-04 14:56:08 +00001129 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001130 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001131
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001132 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001133 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001134 while (R != &Context.CurRegion && !R->contains(L))
1135 R = R->getParent();
1136
1137 if (addOverApproximatedRegion(R, Context))
1138 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001139 }
Tobias Grosser75805372011-04-29 06:27:02 +00001140
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001141 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001142 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001143}
1144
Tobias Grosserc80d6972016-09-02 06:33:33 +00001145/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001146/// count that is not known to be less than @MinProfitableTrips.
1147ScopDetection::LoopStats
1148ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001149 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001150 auto *TripCount = SE.getBackedgeTakenCount(L);
1151
Tobias Grosserb45ae562016-11-26 07:37:46 +00001152 int NumLoops = 1;
1153 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001154 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001155 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001156 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1157 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001158
Tobias Grosserb45ae562016-11-26 07:37:46 +00001159 for (auto &SubLoop : *L) {
1160 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1161 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001162 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001163 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001164
Tobias Grosserb45ae562016-11-26 07:37:46 +00001165 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001166}
1167
Tobias Grosserb45ae562016-11-26 07:37:46 +00001168ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001169ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1170 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001171 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001172 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001173
Tobias Grossercd01a362017-02-17 08:12:36 +00001174 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001175 L = L ? R->outermostLoopInRegion(L) : nullptr;
1176 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001177
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001178 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001179 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001180
1181 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001182 if (R->contains(SubLoop)) {
1183 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001184 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001185 LoopNum += Stats.NumLoops;
1186 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1187 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001188
Tobias Grosserb45ae562016-11-26 07:37:46 +00001189 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001190}
1191
Tobias Grosser75805372011-04-29 06:27:02 +00001192Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001193 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001194 std::unique_ptr<Region> LastValidRegion;
1195 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001196
1197 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1198
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001199 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001200 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001201 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001202 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1203 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001204 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001205 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001206
Johannes Doerfert717b8662015-09-08 21:44:27 +00001207 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001208 // If the exit is valid check all blocks
1209 // - if true, a valid region was found => store it + keep expanding
1210 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001211 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1212 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001213 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001214 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001215 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001216
Tobias Grosserd7e58642013-04-10 06:55:45 +00001217 // Store this region, because it is the greatest valid (encountered so
1218 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001219 if (LastValidRegion) {
1220 removeCachedResults(*LastValidRegion);
1221 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1222 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001223 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001224
1225 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001226 ExpandedRegion =
1227 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001228
1229 } else {
1230 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001231 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001232 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001233 ExpandedRegion =
1234 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001235 }
Tobias Grosser75805372011-04-29 06:27:02 +00001236 }
1237
Tobias Grosser378a9f22013-11-16 19:34:11 +00001238 DEBUG({
1239 if (LastValidRegion)
1240 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1241 else
1242 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1243 });
Tobias Grosser75805372011-04-29 06:27:02 +00001244
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001245 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001246}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001247static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001248 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001249 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001250 return false;
1251
1252 return true;
1253}
Tobias Grosser75805372011-04-29 06:27:02 +00001254
Tobias Grosserb45ae562016-11-26 07:37:46 +00001255void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001256 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001257 if (ValidRegions.count(SubRegion.get())) {
1258 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001259 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001260 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001261 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001262}
1263
Johannes Doerferte46925f2015-10-01 10:59:14 +00001264void ScopDetection::removeCachedResults(const Region &R) {
1265 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001266}
1267
Tobias Grosser75805372011-04-29 06:27:02 +00001268void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001269 const auto &It = DetectionContextMap.insert(std::make_pair(
1270 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001271 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001272
1273 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001274 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001275 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001276 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001277 RegionIsValid = isValidRegion(Context);
1278
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001279 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001280
Johannes Doerferte46925f2015-10-01 10:59:14 +00001281 if (HasErrors) {
1282 removeCachedResults(R);
1283 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001284 ValidRegions.insert(&R);
1285 return;
1286 }
1287
David Blaikieb035f6d2014-04-15 18:45:27 +00001288 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001289 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001290
1291 // Try to expand regions.
1292 //
1293 // As the region tree normally only contains canonical regions, non canonical
1294 // regions that form a Scop are not found. Therefore, those non canonical
1295 // regions are checked by expanding the canonical ones.
1296
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001297 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001298
David Blaikieb035f6d2014-04-15 18:45:27 +00001299 for (auto &SubRegion : R)
1300 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001301
Tobias Grosser26108892014-04-02 20:18:19 +00001302 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001303 // Skip invalid regions. Regions may become invalid, if they are element of
1304 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001305 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001306 continue;
1307
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001308 // Skip regions that had errors.
1309 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1310 if (HadErrors)
1311 continue;
1312
Tobias Grosser75805372011-04-29 06:27:02 +00001313 Region *ExpandedR = expandRegion(*CurrentRegion);
1314
1315 if (!ExpandedR)
1316 continue;
1317
1318 R.addSubRegion(ExpandedR, true);
1319 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001320 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001321 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001322 }
1323}
1324
1325bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001326 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001327
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001328 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001329 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001330 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1331 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001332 return false;
1333 }
1334
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001335 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001336 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1337
1338 // Also check exception blocks (and possibly register them as non-affine
1339 // regions). Even though exception blocks are not modeled, we use them
1340 // to forward-propagate domain constraints during ScopInfo construction.
1341 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1342 return false;
1343
1344 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001345 continue;
1346
Tobias Grosser1d191902014-03-03 13:13:55 +00001347 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001348 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001349 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001350 }
Tobias Grosser75805372011-04-29 06:27:02 +00001351
Sebastian Pope8863b82014-05-12 19:02:02 +00001352 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001353 return false;
1354
Tobias Grosser75805372011-04-29 06:27:02 +00001355 return true;
1356}
1357
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001358bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1359 int NumLoops) const {
1360 int InstCount = 0;
1361
Tobias Grosserb316dc12016-09-08 14:08:05 +00001362 if (NumLoops == 0)
1363 return false;
1364
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001365 for (auto *BB : Context.CurRegion.blocks())
1366 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001367 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001368
1369 InstCount = InstCount / NumLoops;
1370
1371 return InstCount >= ProfitabilityMinPerLoopInstructions;
1372}
1373
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001374bool ScopDetection::hasPossiblyDistributableLoop(
1375 DetectionContext &Context) const {
1376 for (auto *BB : Context.CurRegion.blocks()) {
1377 auto *L = LI->getLoopFor(BB);
1378 if (!Context.CurRegion.contains(L))
1379 continue;
1380 if (Context.BoxedLoopsSet.count(L))
1381 continue;
1382 unsigned StmtsWithStoresInLoops = 0;
1383 for (auto *LBB : L->blocks()) {
1384 bool MemStore = false;
1385 for (auto &I : *LBB)
1386 MemStore |= isa<StoreInst>(&I);
1387 StmtsWithStoresInLoops += MemStore;
1388 }
1389 return (StmtsWithStoresInLoops > 1);
1390 }
1391 return false;
1392}
1393
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001394bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1395 Region &CurRegion = Context.CurRegion;
1396
1397 if (PollyProcessUnprofitable)
1398 return true;
1399
1400 // We can probably not do a lot on scops that only write or only read
1401 // data.
1402 if (!Context.hasStores || !Context.hasLoads)
1403 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1404
Tobias Grossercd01a362017-02-17 08:12:36 +00001405 int NumLoops =
1406 countBeneficialLoops(&CurRegion, *SE, *LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001407 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001408
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001409 // Scops with at least two loops may allow either loop fusion or tiling and
1410 // are consequently interesting to look at.
1411 if (NumAffineLoops >= 2)
1412 return true;
1413
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001414 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1415 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1416 return true;
1417
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001418 // Scops that contain a loop with a non-trivial amount of computation per
1419 // loop-iteration are interesting as we may be able to parallelize such
1420 // loops. Individual loops that have only a small amount of computation
1421 // per-iteration are performance-wise very fragile as any change to the
1422 // loop induction variables may affect performance. To not cause spurious
1423 // performance regressions, we do not consider such loops.
1424 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1425 return true;
1426
1427 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001428}
1429
Tobias Grosser75805372011-04-29 06:27:02 +00001430bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001431 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001432
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001433 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001434
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001435 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001436 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001437 return false;
1438 }
1439
Tobias Grosser134a5722017-03-07 15:50:43 +00001440 DebugLoc DbgLoc;
1441 if (isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
1442 DEBUG(dbgs() << "Unreachable in exit\n");
1443 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1444 CurRegion.getExit(), DbgLoc);
1445 }
1446
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001447 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001448 DEBUG({
1449 dbgs() << "Region entry does not match -polly-region-only";
1450 dbgs() << "\n";
1451 });
1452 return false;
1453 }
1454
Tobias Grosserd654c252012-04-10 18:12:19 +00001455 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001456 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001457 if (CurRegion.getEntry() ==
1458 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1459 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001460
Hongbin Zheng94868e62012-04-07 12:29:17 +00001461 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001462 return false;
1463
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001464 if (!isReducibleRegion(CurRegion, DbgLoc))
1465 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1466 &CurRegion, DbgLoc);
1467
Tobias Grosser75805372011-04-29 06:27:02 +00001468 DEBUG(dbgs() << "OK\n");
1469 return true;
1470}
1471
Tobias Grosser629109b2016-08-03 12:00:07 +00001472void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001473 F->addFnAttr(PollySkipFnAttr);
1474}
1475
Tobias Grosser75805372011-04-29 06:27:02 +00001476bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001477 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001478}
1479
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001480void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001481 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001482 unsigned LineEntry, LineExit;
1483 std::string FileName;
1484
Tobias Grosser00dc3092014-03-02 12:02:46 +00001485 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001486 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1487 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001488 }
1489}
1490
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001491void ScopDetection::emitMissedRemarks(const Function &F) {
1492 for (auto &DIt : DetectionContextMap) {
1493 auto &DC = DIt.getSecond();
1494 if (DC.Log.hasErrors())
1495 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001496 }
1497}
1498
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001499bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001500 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001501 ///
1502 /// WHITE - Unvisited BB in DFS walk.
1503 /// GREY - BBs which are currently on the DFS stack for processing.
1504 /// BLACK - Visited and completely processed BB.
1505 enum Color { WHITE, GREY, BLACK };
1506
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001507 BasicBlock *REntry = R.getEntry();
1508 BasicBlock *RExit = R.getExit();
1509 // Map to match the color of a BasicBlock during the DFS walk.
1510 DenseMap<const BasicBlock *, Color> BBColorMap;
1511 // Stack keeping track of current BB and index of next child to be processed.
1512 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1513
1514 unsigned AdjacentBlockIndex = 0;
1515 BasicBlock *CurrBB, *SuccBB;
1516 CurrBB = REntry;
1517
1518 // Initialize the map for all BB with WHITE color.
1519 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001520 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001521
1522 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001523 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001524 DFSStack.push(std::make_pair(CurrBB, 0));
1525
1526 while (!DFSStack.empty()) {
1527 // Get next BB on stack to be processed.
1528 CurrBB = DFSStack.top().first;
1529 AdjacentBlockIndex = DFSStack.top().second;
1530 DFSStack.pop();
1531
1532 // Loop to iterate over the successors of current BB.
1533 const TerminatorInst *TInst = CurrBB->getTerminator();
1534 unsigned NSucc = TInst->getNumSuccessors();
1535 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1536 ++I, ++AdjacentBlockIndex) {
1537 SuccBB = TInst->getSuccessor(I);
1538
1539 // Checks for region exit block and self-loops in BB.
1540 if (SuccBB == RExit || SuccBB == CurrBB)
1541 continue;
1542
1543 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001544 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001545 // Push the current BB and the index of the next child to be visited.
1546 DFSStack.push(std::make_pair(CurrBB, I + 1));
1547 // Push the next BB to be processed.
1548 DFSStack.push(std::make_pair(SuccBB, 0));
1549 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001550 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001551 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001552 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001553 // GREY indicates a loop in the control flow.
1554 // If the destination dominates the source, it is a natural loop
1555 // else, an irreducible control flow in the region is detected.
1556 if (!DT->dominates(SuccBB, CurrBB)) {
1557 // Get debug info of instruction which causes irregular control flow.
1558 DbgLoc = TInst->getDebugLoc();
1559 return false;
1560 }
1561 }
1562 }
1563
1564 // If all children of current BB have been processed,
1565 // then mark that BB as fully processed.
1566 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001567 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001568 }
1569
1570 return true;
1571}
1572
Tobias Grosserb45ae562016-11-26 07:37:46 +00001573void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1574 bool OnlyProfitable) {
1575 if (!OnlyProfitable) {
1576 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001577 MaxNumLoopsInScop =
1578 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001579 if (Stats.MaxDepth == 1)
1580 NumScopsDepthOne++;
1581 else if (Stats.MaxDepth == 2)
1582 NumScopsDepthTwo++;
1583 else if (Stats.MaxDepth == 3)
1584 NumScopsDepthThree++;
1585 else if (Stats.MaxDepth == 4)
1586 NumScopsDepthFour++;
1587 else if (Stats.MaxDepth == 5)
1588 NumScopsDepthFive++;
1589 else
1590 NumScopsDepthLarger++;
1591 } else {
1592 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001593 MaxNumLoopsInProfScop =
1594 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001595 if (Stats.MaxDepth == 1)
1596 NumProfScopsDepthOne++;
1597 else if (Stats.MaxDepth == 2)
1598 NumProfScopsDepthTwo++;
1599 else if (Stats.MaxDepth == 3)
1600 NumProfScopsDepthThree++;
1601 else if (Stats.MaxDepth == 4)
1602 NumProfScopsDepthFour++;
1603 else if (Stats.MaxDepth == 5)
1604 NumProfScopsDepthFive++;
1605 else
1606 NumProfScopsDepthLarger++;
1607 }
1608}
1609
Tobias Grosser75805372011-04-29 06:27:02 +00001610bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001611 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001612 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001613 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001614 return false;
1615
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001616 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001617 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001618 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001619 Region *TopRegion = RI->getTopLevelRegion();
1620
Tobias Grosser2ff87232011-10-23 11:17:06 +00001621 releaseMemory();
1622
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001623 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001624 return false;
1625
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001626 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001627 return false;
1628
1629 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001630
Tobias Grosserb45ae562016-11-26 07:37:46 +00001631 NumScopRegions += ValidRegions.size();
1632
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001633 // Prune non-profitable regions.
1634 for (auto &DIt : DetectionContextMap) {
1635 auto &DC = DIt.getSecond();
1636 if (DC.Log.hasErrors())
1637 continue;
1638 if (!ValidRegions.count(&DC.CurRegion))
1639 continue;
Tobias Grossercd01a362017-02-17 08:12:36 +00001640 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, *SE, *LI, 0);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001641 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
1642 if (isProfitableRegion(DC)) {
1643 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001644 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001645 }
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001646
1647 ValidRegions.remove(&DC.CurRegion);
1648 }
1649
Tobias Grosserb45ae562016-11-26 07:37:46 +00001650 NumProfScopRegions += ValidRegions.size();
Tobias Grossercd01a362017-02-17 08:12:36 +00001651 NumLoopsOverall += countBeneficialLoops(TopRegion, *SE, *LI, 0).NumLoops;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001652
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001653 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001654 if (PollyTrackFailures)
1655 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001656
Johannes Doerferta05214f2014-10-15 23:24:28 +00001657 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001658 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001659
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001660 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001661 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001662 return false;
1663}
1664
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001665ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001666ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001667 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001668 if (DCMIt == DetectionContextMap.end())
1669 return nullptr;
1670 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001671}
1672
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001673const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1674 const DetectionContext *DC = getDetectionContext(R);
1675 return DC ? &DC->Log : nullptr;
1676}
1677
Tobias Grosser75805372011-04-29 06:27:02 +00001678void polly::ScopDetection::verifyRegion(const Region &R) const {
1679 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001680
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001681 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001682 isValidRegion(Context);
1683}
1684
1685void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001686 if (!VerifyScops)
1687 return;
1688
Tobias Grosser26108892014-04-02 20:18:19 +00001689 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001690 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001691}
1692
1693void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001694 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001695 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001696 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001697 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001698 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001699 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001700 AU.setPreservesAll();
1701}
1702
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001703void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001704 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001705 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001706
1707 OS << "\n";
1708}
1709
1710void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001711 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001712 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001713
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001714 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001715}
1716
1717char ScopDetection::ID = 0;
1718
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001719Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1720
Tobias Grosser73600b82011-10-08 00:30:40 +00001721INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1722 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001723 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001724INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001725INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001726INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001727INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001728INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001729INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1730 "Polly - Detect static control parts (SCoPs)", false, false)