blob: 31ee882d0ce5faf02c3baca1a9b52fdf7ca89ece [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) {
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000353 if (!isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000354 return false;
355
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000356 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
357
358 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
359 Load->getAlignment(), DL))
360 continue;
361
Tobias Grosser1c787e02017-03-02 12:15:37 +0000362 if (NonAffineRegion->contains(Load) &&
363 Load->getParent() != NonAffineRegion->getEntry())
364 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000365 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000366 }
367
Johannes Doerfert09e36972015-10-07 20:17:36 +0000368 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
369
370 return true;
371}
372
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000373bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
374 Loop *Scope) const {
375 SetVector<Value *> Values;
376 findValues(S0, *SE, Values);
377 if (S1)
378 findValues(S1, *SE, Values);
379
380 SmallPtrSet<Value *, 8> PtrVals;
381 for (auto *V : Values) {
382 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
383 V = P2I->getOperand(0);
384
385 if (!V->getType()->isPointerTy())
386 continue;
387
388 auto *PtrSCEV = SE->getSCEVAtScope(V, Scope);
389 if (isa<SCEVConstant>(PtrSCEV))
390 continue;
391
392 auto *BasePtr = dyn_cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
393 if (!BasePtr)
394 return true;
395
396 auto *BasePtrVal = BasePtr->getValue();
397 if (PtrVals.insert(BasePtrVal).second) {
398 for (auto *PtrVal : PtrVals)
399 if (PtrVal != BasePtrVal && !AA->isNoAlias(PtrVal, BasePtrVal))
400 return true;
401 }
402 }
403
404 return false;
405}
406
Michael Kruse09eb4452016-03-03 22:10:47 +0000407bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000408 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000409
410 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000411 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000412 return false;
413
414 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
415 return false;
416
417 return true;
418}
419
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000420bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000421 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000422 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000423 Loop *L = LI->getLoopFor(&BB);
424 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000425
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000426 if (IsLoopBranch && L->isLoopLatch(&BB))
427 return false;
428
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000429 // Check for invalid usage of different pointers in one expression.
430 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
431 return false;
432
Michael Kruse09eb4452016-03-03 22:10:47 +0000433 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000434 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000435
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000436 if (AllowNonAffineSubRegions &&
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000437 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
438 return true;
439
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000440 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
441 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000442}
443
444bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000445 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000446 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000447
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000448 // Constant integer conditions are always affine.
449 if (isa<ConstantInt>(Condition))
450 return true;
451
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000452 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
453 auto Opcode = BinOp->getOpcode();
454 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
455 Value *Op0 = BinOp->getOperand(0);
456 Value *Op1 = BinOp->getOperand(1);
457 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
458 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
459 }
460 }
461
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000462 // Non constant conditions of branches need to be ICmpInst.
463 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000464 if (!IsLoopBranch && AllowNonAffineSubRegions &&
465 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
466 return true;
467 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000468 }
Tobias Grosser75805372011-04-29 06:27:02 +0000469
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000470 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000471
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000472 // Are both operands of the ICmp affine?
473 if (isa<UndefValue>(ICmp->getOperand(0)) ||
474 isa<UndefValue>(ICmp->getOperand(1)))
475 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000476
Tobias Grossera2f8fa32016-11-13 19:27:04 +0000477 Loop *L = LI->getLoopFor(&BB);
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000478 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
479 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000480
Johannes Doerfertbda81432016-12-02 17:55:41 +0000481 // If unsigned operations are not allowed try to approximate the region.
482 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
483 return !IsLoopBranch && AllowNonAffineSubRegions &&
484 addOverApproximatedRegion(RI->getRegionFor(&BB), Context);
485
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000486 // Check for invalid usage of different pointers in one expression.
487 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
488 involvesMultiplePtrs(RHS, nullptr, L))
489 return false;
490
491 // Check for invalid usage of different pointers in a relational comparison.
492 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
493 return false;
494
Michael Kruse09eb4452016-03-03 22:10:47 +0000495 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000496 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000497
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000498 if (!IsLoopBranch && AllowNonAffineSubRegions &&
499 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
500 return true;
501
502 if (IsLoopBranch)
503 return false;
504
505 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
506 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000507}
508
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000509bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000510 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000511 DetectionContext &Context) const {
512 Region &CurRegion = Context.CurRegion;
513
514 TerminatorInst *TI = BB.getTerminator();
515
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000516 if (AllowUnreachable && isa<UnreachableInst>(TI))
517 return true;
518
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000519 // Return instructions are only valid if the region is the top level region.
520 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
521 return true;
522
523 Value *Condition = getConditionFromTerminator(TI);
524
525 if (!Condition)
526 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
527
528 // UndefValue is not allowed as condition.
529 if (isa<UndefValue>(Condition))
530 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
531
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000532 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000533 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000534
535 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
536 assert(SI && "Terminator was neither branch nor switch");
537
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000538 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000539}
540
Johannes Doerfertcea61932016-02-21 19:13:19 +0000541bool ScopDetection::isValidCallInst(CallInst &CI,
542 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000543 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000544 return false;
545
546 if (CI.doesNotAccessMemory())
547 return true;
548
Johannes Doerfertcea61932016-02-21 19:13:19 +0000549 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000550 if (isValidIntrinsicInst(*II, Context))
551 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000552
Tobias Grosser75805372011-04-29 06:27:02 +0000553 Function *CalledFunction = CI.getCalledFunction();
554
555 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000556 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000557 return false;
558
Tobias Grosser898a6362016-03-23 06:40:15 +0000559 if (AllowModrefCall) {
560 switch (AA->getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000561 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000562 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000563 case FMRB_DoesNotAccessMemory:
564 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000565 // Implicitly disable delinearization since we have an unknown
566 // accesses with an unknown access function.
567 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000568 Context.AST.add(&CI);
569 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000570 case FMRB_OnlyReadsArgumentPointees:
571 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000572 for (const auto &Arg : CI.arg_operands()) {
573 if (!Arg->getType()->isPointerTy())
574 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000575
Tobias Grosser898a6362016-03-23 06:40:15 +0000576 // Bail if a pointer argument has a base address not known to
577 // ScalarEvolution. Note that a zero pointer is acceptable.
578 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
579 if (ArgSCEV->isZero())
580 continue;
581
582 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
583 if (!BP)
584 return false;
585
586 // Implicitly disable delinearization since we have an unknown
587 // accesses with an unknown access function.
588 Context.HasUnknownAccess = true;
589 }
590
591 Context.AST.add(&CI);
592 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000593 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000594 case FMRB_OnlyAccessesInaccessibleMem:
595 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000596 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000597 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000598 }
599
Johannes Doerfertcea61932016-02-21 19:13:19 +0000600 return false;
601}
602
603bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
604 DetectionContext &Context) const {
605 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000606 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000607
Johannes Doerfertcea61932016-02-21 19:13:19 +0000608 // The closest loop surrounding the call instruction.
609 Loop *L = LI->getLoopFor(II.getParent());
610
611 // The access function and base pointer for memory intrinsics.
612 const SCEV *AF;
613 const SCEVUnknown *BP;
614
615 switch (II.getIntrinsicID()) {
616 // Memory intrinsics that can be represented are supported.
617 case llvm::Intrinsic::memmove:
618 case llvm::Intrinsic::memcpy:
619 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000620 if (!AF->isZero()) {
621 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
622 // Bail if the source pointer is not valid.
623 if (!isValidAccess(&II, AF, BP, Context))
624 return false;
625 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000626 // Fall through
627 case llvm::Intrinsic::memset:
628 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000629 if (!AF->isZero()) {
630 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
631 // Bail if the destination pointer is not valid.
632 if (!isValidAccess(&II, AF, BP, Context))
633 return false;
634 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000635
636 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000637 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000638 Context))
639 return false;
640
641 return true;
642 default:
643 break;
644 }
645
Tobias Grosser75805372011-04-29 06:27:02 +0000646 return false;
647}
648
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000649bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
650 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000651 // A reference to function argument or constant value is invariant.
652 if (isa<Argument>(Val) || isa<Constant>(Val))
653 return true;
654
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000655 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000656 if (!I)
657 return false;
658
659 if (!Reg.contains(I))
660 return true;
661
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000662 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
663 // is not hoistable, it will be rejected later, but here we assume it is and
664 // that makes the value invariant.
665 if (auto LI = dyn_cast<LoadInst>(I)) {
666 Ctx.RequiredILS.insert(LI);
667 return true;
668 }
669
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000670 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000671}
672
Tobias Grosserc80d6972016-09-02 06:33:33 +0000673/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000674/// register the '...' components.
675///
676/// Array access expressions as they are generated by gfortran contain smax(0,
677/// size) expressions that confuse the 'normal' delinearization algorithm.
678/// However, if we extract such expressions before the normal delinearization
679/// takes place they can actually help to identify array size expressions in
680/// fortran accesses. For the subsequently following delinearization the smax(0,
681/// size) component can be replaced by just 'size'. This is correct as we will
682/// always add and verify the assumption that for all subscript expressions
683/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
684/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000685class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000686public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000687 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
688 std::vector<const SCEV *> *Terms = nullptr) {
689 SCEVRemoveMax Rewriter(SE, Terms);
690 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000691 }
692
693 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000694 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000695
696 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000697 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000698 auto Res = visit(Expr->getOperand(1));
699 if (Terms)
700 (*Terms).push_back(Res);
701 return Res;
702 }
703
704 return Expr;
705 }
706
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000707private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000708 std::vector<const SCEV *> *Terms;
709};
710
Tobias Grosserd68ba422015-11-24 05:00:36 +0000711SmallVector<const SCEV *, 4>
712ScopDetection::getDelinearizationTerms(DetectionContext &Context,
713 const SCEVUnknown *BasePointer) const {
714 SmallVector<const SCEV *, 4> Terms;
715 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000716 std::vector<const SCEV *> MaxTerms;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000717 SCEVRemoveMax::rewrite(Pair.second, *SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000718 if (MaxTerms.size() > 0) {
719 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
720 continue;
721 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000722 // In case the outermost expression is a plain add, we check if any of its
723 // terms has the form 4 * %inst * %param * %param ..., aka a term that
724 // contains a product between a parameter and an instruction that is
725 // inside the scop. Such instructions, if allowed at all, are instructions
726 // SCEV can not represent, but Polly is still looking through. As a
727 // result, these instructions can depend on induction variables and are
728 // most likely no array sizes. However, terms that are multiplied with
729 // them are likely candidates for array sizes.
730 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
731 for (auto Op : AF->operands()) {
732 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
733 SE->collectParametricTerms(AF2, Terms);
734 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
735 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000736
Tobias Grosserd68ba422015-11-24 05:00:36 +0000737 for (auto *MulOp : AF2->operands()) {
738 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
739 Operands.push_back(Const);
740 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
741 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
742 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000743 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000744
745 } else {
746 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000747 }
748 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000749 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000750 if (Operands.size())
751 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000752 }
753 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000754 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000755 if (Terms.empty())
756 SE->collectParametricTerms(Pair.second, Terms);
757 }
758 return Terms;
759}
Sebastian Pope8863b82014-05-12 19:02:02 +0000760
Tobias Grosserd68ba422015-11-24 05:00:36 +0000761bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
762 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000763 const SCEVUnknown *BasePointer,
764 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000765 Value *BaseValue = BasePointer->getValue();
766 Region &CurRegion = Context.CurRegion;
767 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000768 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000769 Sizes.clear();
770 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000771 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000772 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
773 auto *V = dyn_cast<Value>(Unknown->getValue());
774 if (auto *Load = dyn_cast<LoadInst>(V)) {
775 if (Context.CurRegion.contains(Load) &&
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000776 isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000777 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000778 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000779 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000780 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000781 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000782 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000783 Context, /*Assert=*/true, DelinearizedSize,
784 Context.Accesses[BasePointer].front().first, BaseValue);
785 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000786
Tobias Grosserd68ba422015-11-24 05:00:36 +0000787 // No array shape derived.
788 if (Sizes.empty()) {
789 if (AllowNonAffine)
790 return true;
791
Tobias Grosser230acc42014-09-13 14:47:55 +0000792 for (const auto &Pair : Context.Accesses[BasePointer]) {
793 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000794 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000795
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000796 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000797 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
798 BaseValue);
799 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000800 return false;
801 }
802 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000803 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000804 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000805 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000806}
807
Tobias Grosserd68ba422015-11-24 05:00:36 +0000808// We first store the resulting memory accesses in TempMemoryAccesses. Only
809// if the access functions for all memory accesses have been successfully
810// delinearized we continue. Otherwise, we either report a failure or, if
811// non-affine accesses are allowed, we drop the information. In case the
812// information is dropped the memory accesses need to be overapproximated
813// when translated to a polyhedral representation.
814bool ScopDetection::computeAccessFunctions(
815 DetectionContext &Context, const SCEVUnknown *BasePointer,
816 std::shared_ptr<ArrayShape> Shape) const {
817 Value *BaseValue = BasePointer->getValue();
818 bool BasePtrHasNonAffine = false;
819 MapInsnToMemAcc TempMemoryAccesses;
820 for (const auto &Pair : Context.Accesses[BasePointer]) {
821 const Instruction *Insn = Pair.first;
822 auto *AF = Pair.second;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000823 AF = SCEVRemoveMax::rewrite(AF, *SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000824 bool IsNonAffine = false;
825 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
826 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000827 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000828
829 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000830 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000831 Acc->DelinearizedSubscripts.push_back(Pair.second);
832 else
833 IsNonAffine = true;
834 } else {
835 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
836 Shape->DelinearizedSizes);
837 if (Acc->DelinearizedSubscripts.size() == 0)
838 IsNonAffine = true;
839 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000840 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000841 IsNonAffine = true;
842 }
843
844 // (Possibly) report non affine access
845 if (IsNonAffine) {
846 BasePtrHasNonAffine = true;
847 if (!AllowNonAffine)
848 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
849 Insn, BaseValue);
850 if (!KeepGoing && !AllowNonAffine)
851 return false;
852 }
853 }
854
855 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000856 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
857 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000858
859 return true;
860}
861
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000862bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
863 const SCEVUnknown *BasePointer,
864 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000865 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
866
867 auto Terms = getDelinearizationTerms(Context, BasePointer);
868
869 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
870 Context.ElementSize[BasePointer]);
871
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000872 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
873 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000874 return false;
875
876 return computeAccessFunctions(Context, BasePointer, Shape);
877}
878
879bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000880 // TODO: If we have an unknown access and other non-affine accesses we do
881 // not try to delinearize them for now.
882 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
883 return AllowNonAffine;
884
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000885 for (auto &Pair : Context.NonAffineAccesses) {
886 auto *BasePointer = Pair.first;
887 auto *Scope = Pair.second;
888 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000889 if (KeepGoing)
890 continue;
891 else
892 return false;
893 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000894 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000895 return true;
896}
897
Johannes Doerfertcea61932016-02-21 19:13:19 +0000898bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
899 const SCEVUnknown *BP,
900 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000901
Johannes Doerfertcea61932016-02-21 19:13:19 +0000902 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000903 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000904
Johannes Doerfertcea61932016-02-21 19:13:19 +0000905 auto *BV = BP->getValue();
906 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000907 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000908
Johannes Doerfertcea61932016-02-21 19:13:19 +0000909 // FIXME: Think about allowing IntToPtrInst
910 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
911 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
912
Tobias Grosser458fb782014-01-28 12:58:58 +0000913 // Check that the base address of the access is invariant in the current
914 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000915 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000916 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000917
Johannes Doerfertcea61932016-02-21 19:13:19 +0000918 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000919
Johannes Doerfertcea61932016-02-21 19:13:19 +0000920 const SCEV *Size;
921 if (!isa<MemIntrinsic>(Inst)) {
922 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000923 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000924 auto *SizeTy =
925 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
926 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000927 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000928
Johannes Doerfertcea61932016-02-21 19:13:19 +0000929 if (Context.ElementSize[BP]) {
930 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
931 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
932 Inst, BV);
933
934 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
935 } else {
936 Context.ElementSize[BP] = Size;
937 }
938
939 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000940 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000941 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000942 for (const Loop *L : Loops)
943 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000944 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000945
Michael Kruse09eb4452016-03-03 22:10:47 +0000946 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000947 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000948 // Do not try to delinearize memory intrinsics and force them to be affine.
949 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
950 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
951 BV);
952 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
953 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000954
Johannes Doerfertcea61932016-02-21 19:13:19 +0000955 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000956 Context.NonAffineAccesses.insert(
957 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000958 } else if (!AllowNonAffine && !IsAffine) {
959 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
960 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000961 }
Tobias Grosser75805372011-04-29 06:27:02 +0000962
Tobias Grosser1eedb672014-09-24 21:04:29 +0000963 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000964 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000965
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000966 // Check if the base pointer of the memory access does alias with
967 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000968 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000969 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000970 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000971 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000972
Tobias Grosser1eedb672014-09-24 21:04:29 +0000973 if (!AS.isMustAlias()) {
974 if (PollyUseRuntimeAliasChecks) {
975 bool CanBuildRunTimeCheck = true;
976 // The run-time alias check places code that involves the base pointer at
977 // the beginning of the SCoP. This breaks if the base pointer is defined
978 // inside the scop. Hence, we can only create a run-time check if we are
979 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000980 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000981 for (const auto &Ptr : AS) {
982 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000983 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000984 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000985 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE, *DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000986 Context.RequiredILS.insert(Load);
987 continue;
988 }
989
Tobias Grosser1eedb672014-09-24 21:04:29 +0000990 CanBuildRunTimeCheck = false;
991 break;
992 }
993 }
994
995 if (CanBuildRunTimeCheck)
996 return true;
997 }
Michael Kruse70131d32016-01-27 17:09:17 +0000998 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000999 }
Tobias Grosser75805372011-04-29 06:27:02 +00001000
1001 return true;
1002}
1003
Johannes Doerfertcea61932016-02-21 19:13:19 +00001004bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1005 DetectionContext &Context) const {
1006 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +00001007 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001008 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
1009 const SCEVUnknown *BasePointer;
1010
1011 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
1012
1013 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1014}
1015
Tobias Grosser75805372011-04-29 06:27:02 +00001016bool ScopDetection::isValidInstruction(Instruction &Inst,
1017 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001018 for (auto &Op : Inst.operands()) {
1019 auto *OpInst = dyn_cast<Instruction>(&Op);
1020
1021 if (!OpInst)
1022 continue;
1023
1024 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
1025 return false;
1026 }
1027
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001028 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1029 return false;
1030
Tobias Grosser75805372011-04-29 06:27:02 +00001031 // We only check the call instruction but not invoke instruction.
1032 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001033 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001034 return true;
1035
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001036 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001037 }
1038
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001039 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001040 if (!isa<AllocaInst>(Inst))
1041 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001042
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001043 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001044 }
1045
1046 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001047 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001048 Context.hasStores |= isa<StoreInst>(MemInst);
1049 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001050 if (!MemInst.isSimple())
1051 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1052 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001053
Michael Kruse70131d32016-01-27 17:09:17 +00001054 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001055 }
Tobias Grosser75805372011-04-29 06:27:02 +00001056
1057 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001058 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001059}
1060
Tobias Grosser349d1c32016-09-20 17:05:22 +00001061/// Check whether @p L has exiting blocks.
1062///
1063/// @param L The loop of interest
1064///
1065/// @return True if the loop has exiting blocks, false otherwise.
1066static bool hasExitingBlocks(Loop *L) {
1067 SmallVector<BasicBlock *, 4> ExitingBlocks;
1068 L->getExitingBlocks(ExitingBlocks);
1069 return !ExitingBlocks.empty();
1070}
1071
Johannes Doerfertd020b772015-08-27 06:53:52 +00001072bool ScopDetection::canUseISLTripCount(Loop *L,
1073 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001074 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1075 // need to overapproximate it as a boxed loop.
1076 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001077 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001078 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001079 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001080 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001081 return false;
1082 }
1083
Johannes Doerfertd020b772015-08-27 06:53:52 +00001084 // We can use ISL to compute the trip count of L.
1085 return true;
1086}
1087
Tobias Grosser75805372011-04-29 06:27:02 +00001088bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001089 // Loops that contain part but not all of the blocks of a region cannot be
1090 // handled by the schedule generation. Such loop constructs can happen
1091 // because a region can contain BBs that have no path to the exit block
1092 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1093 // loop.
1094 //
1095 // _______________
1096 // | Loop Header | <-----------.
1097 // --------------- |
1098 // | |
1099 // _______________ ______________
1100 // | RegionEntry |-----> | RegionExit |----->
1101 // --------------- --------------
1102 // |
1103 // _______________
1104 // | EndlessLoop | <--.
1105 // --------------- |
1106 // | |
1107 // \------------/
1108 //
1109 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1110 // neither entirely contained in the region RegionEntry->RegionExit
1111 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1112 // in the loop.
1113 // The block EndlessLoop is contained in the region because Region::contains
1114 // tests whether it is not dominated by RegionExit. This is probably to not
1115 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1116 // end can also be formed by an UnreachableInst. This case is already caught
1117 // by isErrorBlock(). We hence only have to reject endless loops here.
1118 if (!hasExitingBlocks(L))
1119 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1120
Johannes Doerfertf61df692015-10-04 14:56:08 +00001121 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001122 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001123
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001124 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001125 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001126 while (R != &Context.CurRegion && !R->contains(L))
1127 R = R->getParent();
1128
1129 if (addOverApproximatedRegion(R, Context))
1130 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001131 }
Tobias Grosser75805372011-04-29 06:27:02 +00001132
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001133 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001134 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001135}
1136
Tobias Grosserc80d6972016-09-02 06:33:33 +00001137/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001138/// count that is not known to be less than @MinProfitableTrips.
1139ScopDetection::LoopStats
1140ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001141 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001142 auto *TripCount = SE.getBackedgeTakenCount(L);
1143
Tobias Grosserb45ae562016-11-26 07:37:46 +00001144 int NumLoops = 1;
1145 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001146 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001147 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001148 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1149 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001150
Tobias Grosserb45ae562016-11-26 07:37:46 +00001151 for (auto &SubLoop : *L) {
1152 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1153 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001154 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001155 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001156
Tobias Grosserb45ae562016-11-26 07:37:46 +00001157 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001158}
1159
Tobias Grosserb45ae562016-11-26 07:37:46 +00001160ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001161ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1162 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001163 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001164 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001165
Tobias Grossercd01a362017-02-17 08:12:36 +00001166 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001167 L = L ? R->outermostLoopInRegion(L) : nullptr;
1168 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001169
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001170 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001171 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001172
1173 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001174 if (R->contains(SubLoop)) {
1175 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001176 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001177 LoopNum += Stats.NumLoops;
1178 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1179 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001180
Tobias Grosserb45ae562016-11-26 07:37:46 +00001181 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001182}
1183
Tobias Grosser75805372011-04-29 06:27:02 +00001184Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001185 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001186 std::unique_ptr<Region> LastValidRegion;
1187 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001188
1189 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1190
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001191 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001192 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001193 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001194 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1195 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001196 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001197 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001198
Johannes Doerfert717b8662015-09-08 21:44:27 +00001199 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001200 // If the exit is valid check all blocks
1201 // - if true, a valid region was found => store it + keep expanding
1202 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001203 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1204 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001205 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001206 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001207 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001208
Tobias Grosserd7e58642013-04-10 06:55:45 +00001209 // Store this region, because it is the greatest valid (encountered so
1210 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001211 if (LastValidRegion) {
1212 removeCachedResults(*LastValidRegion);
1213 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1214 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001215 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001216
1217 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001218 ExpandedRegion =
1219 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001220
1221 } else {
1222 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001223 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001224 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001225 ExpandedRegion =
1226 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001227 }
Tobias Grosser75805372011-04-29 06:27:02 +00001228 }
1229
Tobias Grosser378a9f22013-11-16 19:34:11 +00001230 DEBUG({
1231 if (LastValidRegion)
1232 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1233 else
1234 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1235 });
Tobias Grosser75805372011-04-29 06:27:02 +00001236
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001237 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001238}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001239static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001240 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001241 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001242 return false;
1243
1244 return true;
1245}
Tobias Grosser75805372011-04-29 06:27:02 +00001246
Tobias Grosserb45ae562016-11-26 07:37:46 +00001247void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001248 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001249 if (ValidRegions.count(SubRegion.get())) {
1250 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001251 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001252 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001253 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001254}
1255
Johannes Doerferte46925f2015-10-01 10:59:14 +00001256void ScopDetection::removeCachedResults(const Region &R) {
1257 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001258}
1259
Tobias Grosser75805372011-04-29 06:27:02 +00001260void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001261 const auto &It = DetectionContextMap.insert(std::make_pair(
1262 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001263 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001264
1265 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001266 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001267 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001268 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001269 RegionIsValid = isValidRegion(Context);
1270
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001271 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001272
Johannes Doerferte46925f2015-10-01 10:59:14 +00001273 if (HasErrors) {
1274 removeCachedResults(R);
1275 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001276 ValidRegions.insert(&R);
1277 return;
1278 }
1279
David Blaikieb035f6d2014-04-15 18:45:27 +00001280 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001281 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001282
1283 // Try to expand regions.
1284 //
1285 // As the region tree normally only contains canonical regions, non canonical
1286 // regions that form a Scop are not found. Therefore, those non canonical
1287 // regions are checked by expanding the canonical ones.
1288
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001289 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001290
David Blaikieb035f6d2014-04-15 18:45:27 +00001291 for (auto &SubRegion : R)
1292 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001293
Tobias Grosser26108892014-04-02 20:18:19 +00001294 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001295 // Skip invalid regions. Regions may become invalid, if they are element of
1296 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001297 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001298 continue;
1299
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001300 // Skip regions that had errors.
1301 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1302 if (HadErrors)
1303 continue;
1304
Tobias Grosser75805372011-04-29 06:27:02 +00001305 Region *ExpandedR = expandRegion(*CurrentRegion);
1306
1307 if (!ExpandedR)
1308 continue;
1309
1310 R.addSubRegion(ExpandedR, true);
1311 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001312 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001313 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001314 }
1315}
1316
1317bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001318 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001319
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001320 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001321 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001322 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1323 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001324 return false;
1325 }
1326
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001327 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001328 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1329
1330 // Also check exception blocks (and possibly register them as non-affine
1331 // regions). Even though exception blocks are not modeled, we use them
1332 // to forward-propagate domain constraints during ScopInfo construction.
1333 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1334 return false;
1335
1336 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001337 continue;
1338
Tobias Grosser1d191902014-03-03 13:13:55 +00001339 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001340 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001341 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001342 }
Tobias Grosser75805372011-04-29 06:27:02 +00001343
Sebastian Pope8863b82014-05-12 19:02:02 +00001344 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001345 return false;
1346
Tobias Grosser75805372011-04-29 06:27:02 +00001347 return true;
1348}
1349
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001350bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1351 int NumLoops) const {
1352 int InstCount = 0;
1353
Tobias Grosserb316dc12016-09-08 14:08:05 +00001354 if (NumLoops == 0)
1355 return false;
1356
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001357 for (auto *BB : Context.CurRegion.blocks())
1358 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001359 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001360
1361 InstCount = InstCount / NumLoops;
1362
1363 return InstCount >= ProfitabilityMinPerLoopInstructions;
1364}
1365
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001366bool ScopDetection::hasPossiblyDistributableLoop(
1367 DetectionContext &Context) const {
1368 for (auto *BB : Context.CurRegion.blocks()) {
1369 auto *L = LI->getLoopFor(BB);
1370 if (!Context.CurRegion.contains(L))
1371 continue;
1372 if (Context.BoxedLoopsSet.count(L))
1373 continue;
1374 unsigned StmtsWithStoresInLoops = 0;
1375 for (auto *LBB : L->blocks()) {
1376 bool MemStore = false;
1377 for (auto &I : *LBB)
1378 MemStore |= isa<StoreInst>(&I);
1379 StmtsWithStoresInLoops += MemStore;
1380 }
1381 return (StmtsWithStoresInLoops > 1);
1382 }
1383 return false;
1384}
1385
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001386bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1387 Region &CurRegion = Context.CurRegion;
1388
1389 if (PollyProcessUnprofitable)
1390 return true;
1391
1392 // We can probably not do a lot on scops that only write or only read
1393 // data.
1394 if (!Context.hasStores || !Context.hasLoads)
1395 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1396
Tobias Grossercd01a362017-02-17 08:12:36 +00001397 int NumLoops =
1398 countBeneficialLoops(&CurRegion, *SE, *LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001399 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001400
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001401 // Scops with at least two loops may allow either loop fusion or tiling and
1402 // are consequently interesting to look at.
1403 if (NumAffineLoops >= 2)
1404 return true;
1405
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001406 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1407 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1408 return true;
1409
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001410 // Scops that contain a loop with a non-trivial amount of computation per
1411 // loop-iteration are interesting as we may be able to parallelize such
1412 // loops. Individual loops that have only a small amount of computation
1413 // per-iteration are performance-wise very fragile as any change to the
1414 // loop induction variables may affect performance. To not cause spurious
1415 // performance regressions, we do not consider such loops.
1416 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1417 return true;
1418
1419 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001420}
1421
Tobias Grosser75805372011-04-29 06:27:02 +00001422bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001423 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001424
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001425 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001426
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001427 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001428 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001429 return false;
1430 }
1431
Tobias Grosser134a5722017-03-07 15:50:43 +00001432 DebugLoc DbgLoc;
1433 if (isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
1434 DEBUG(dbgs() << "Unreachable in exit\n");
1435 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1436 CurRegion.getExit(), DbgLoc);
1437 }
1438
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001439 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001440 DEBUG({
1441 dbgs() << "Region entry does not match -polly-region-only";
1442 dbgs() << "\n";
1443 });
1444 return false;
1445 }
1446
Tobias Grosserd654c252012-04-10 18:12:19 +00001447 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001448 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001449 if (CurRegion.getEntry() ==
1450 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1451 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001452
Hongbin Zheng94868e62012-04-07 12:29:17 +00001453 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001454 return false;
1455
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001456 if (!isReducibleRegion(CurRegion, DbgLoc))
1457 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1458 &CurRegion, DbgLoc);
1459
Tobias Grosser75805372011-04-29 06:27:02 +00001460 DEBUG(dbgs() << "OK\n");
1461 return true;
1462}
1463
Tobias Grosser629109b2016-08-03 12:00:07 +00001464void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001465 F->addFnAttr(PollySkipFnAttr);
1466}
1467
Tobias Grosser75805372011-04-29 06:27:02 +00001468bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001469 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001470}
1471
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001472void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001473 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001474 unsigned LineEntry, LineExit;
1475 std::string FileName;
1476
Tobias Grosser00dc3092014-03-02 12:02:46 +00001477 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001478 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1479 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001480 }
1481}
1482
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001483void ScopDetection::emitMissedRemarks(const Function &F) {
1484 for (auto &DIt : DetectionContextMap) {
1485 auto &DC = DIt.getSecond();
1486 if (DC.Log.hasErrors())
1487 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001488 }
1489}
1490
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001491bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001492 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001493 ///
1494 /// WHITE - Unvisited BB in DFS walk.
1495 /// GREY - BBs which are currently on the DFS stack for processing.
1496 /// BLACK - Visited and completely processed BB.
1497 enum Color { WHITE, GREY, BLACK };
1498
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001499 BasicBlock *REntry = R.getEntry();
1500 BasicBlock *RExit = R.getExit();
1501 // Map to match the color of a BasicBlock during the DFS walk.
1502 DenseMap<const BasicBlock *, Color> BBColorMap;
1503 // Stack keeping track of current BB and index of next child to be processed.
1504 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1505
1506 unsigned AdjacentBlockIndex = 0;
1507 BasicBlock *CurrBB, *SuccBB;
1508 CurrBB = REntry;
1509
1510 // Initialize the map for all BB with WHITE color.
1511 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001512 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001513
1514 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001515 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001516 DFSStack.push(std::make_pair(CurrBB, 0));
1517
1518 while (!DFSStack.empty()) {
1519 // Get next BB on stack to be processed.
1520 CurrBB = DFSStack.top().first;
1521 AdjacentBlockIndex = DFSStack.top().second;
1522 DFSStack.pop();
1523
1524 // Loop to iterate over the successors of current BB.
1525 const TerminatorInst *TInst = CurrBB->getTerminator();
1526 unsigned NSucc = TInst->getNumSuccessors();
1527 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1528 ++I, ++AdjacentBlockIndex) {
1529 SuccBB = TInst->getSuccessor(I);
1530
1531 // Checks for region exit block and self-loops in BB.
1532 if (SuccBB == RExit || SuccBB == CurrBB)
1533 continue;
1534
1535 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001536 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001537 // Push the current BB and the index of the next child to be visited.
1538 DFSStack.push(std::make_pair(CurrBB, I + 1));
1539 // Push the next BB to be processed.
1540 DFSStack.push(std::make_pair(SuccBB, 0));
1541 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001542 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001543 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001544 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001545 // GREY indicates a loop in the control flow.
1546 // If the destination dominates the source, it is a natural loop
1547 // else, an irreducible control flow in the region is detected.
1548 if (!DT->dominates(SuccBB, CurrBB)) {
1549 // Get debug info of instruction which causes irregular control flow.
1550 DbgLoc = TInst->getDebugLoc();
1551 return false;
1552 }
1553 }
1554 }
1555
1556 // If all children of current BB have been processed,
1557 // then mark that BB as fully processed.
1558 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001559 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001560 }
1561
1562 return true;
1563}
1564
Tobias Grosserb45ae562016-11-26 07:37:46 +00001565void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1566 bool OnlyProfitable) {
1567 if (!OnlyProfitable) {
1568 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001569 MaxNumLoopsInScop =
1570 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001571 if (Stats.MaxDepth == 1)
1572 NumScopsDepthOne++;
1573 else if (Stats.MaxDepth == 2)
1574 NumScopsDepthTwo++;
1575 else if (Stats.MaxDepth == 3)
1576 NumScopsDepthThree++;
1577 else if (Stats.MaxDepth == 4)
1578 NumScopsDepthFour++;
1579 else if (Stats.MaxDepth == 5)
1580 NumScopsDepthFive++;
1581 else
1582 NumScopsDepthLarger++;
1583 } else {
1584 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001585 MaxNumLoopsInProfScop =
1586 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001587 if (Stats.MaxDepth == 1)
1588 NumProfScopsDepthOne++;
1589 else if (Stats.MaxDepth == 2)
1590 NumProfScopsDepthTwo++;
1591 else if (Stats.MaxDepth == 3)
1592 NumProfScopsDepthThree++;
1593 else if (Stats.MaxDepth == 4)
1594 NumProfScopsDepthFour++;
1595 else if (Stats.MaxDepth == 5)
1596 NumProfScopsDepthFive++;
1597 else
1598 NumProfScopsDepthLarger++;
1599 }
1600}
1601
Tobias Grosser75805372011-04-29 06:27:02 +00001602bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001603 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001604 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001605 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001606 return false;
1607
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001608 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001609 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001610 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001611 Region *TopRegion = RI->getTopLevelRegion();
1612
Tobias Grosser2ff87232011-10-23 11:17:06 +00001613 releaseMemory();
1614
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001615 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001616 return false;
1617
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001618 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001619 return false;
1620
1621 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001622
Tobias Grosserb45ae562016-11-26 07:37:46 +00001623 NumScopRegions += ValidRegions.size();
1624
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001625 // Prune non-profitable regions.
1626 for (auto &DIt : DetectionContextMap) {
1627 auto &DC = DIt.getSecond();
1628 if (DC.Log.hasErrors())
1629 continue;
1630 if (!ValidRegions.count(&DC.CurRegion))
1631 continue;
Tobias Grossercd01a362017-02-17 08:12:36 +00001632 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, *SE, *LI, 0);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001633 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
1634 if (isProfitableRegion(DC)) {
1635 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001636 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001637 }
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001638
1639 ValidRegions.remove(&DC.CurRegion);
1640 }
1641
Tobias Grosserb45ae562016-11-26 07:37:46 +00001642 NumProfScopRegions += ValidRegions.size();
Tobias Grossercd01a362017-02-17 08:12:36 +00001643 NumLoopsOverall += countBeneficialLoops(TopRegion, *SE, *LI, 0).NumLoops;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001644
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001645 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001646 if (PollyTrackFailures)
1647 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001648
Johannes Doerferta05214f2014-10-15 23:24:28 +00001649 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001650 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001651
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001652 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001653 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001654 return false;
1655}
1656
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001657ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001658ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001659 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001660 if (DCMIt == DetectionContextMap.end())
1661 return nullptr;
1662 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001663}
1664
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001665const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1666 const DetectionContext *DC = getDetectionContext(R);
1667 return DC ? &DC->Log : nullptr;
1668}
1669
Tobias Grosser75805372011-04-29 06:27:02 +00001670void polly::ScopDetection::verifyRegion(const Region &R) const {
1671 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001672
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001673 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001674 isValidRegion(Context);
1675}
1676
1677void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001678 if (!VerifyScops)
1679 return;
1680
Tobias Grosser26108892014-04-02 20:18:19 +00001681 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001682 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001683}
1684
1685void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001686 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001687 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001688 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001689 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001690 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001691 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001692 AU.setPreservesAll();
1693}
1694
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001695void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001696 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001697 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001698
1699 OS << "\n";
1700}
1701
1702void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001703 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001704 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001705
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001706 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001707}
1708
1709char ScopDetection::ID = 0;
1710
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001711Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1712
Tobias Grosser73600b82011-10-08 00:30:40 +00001713INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1714 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001715 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001716INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001717INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001718INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001719INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001720INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001721INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1722 "Polly - Detect static control parts (SCoPs)", false, false)