blob: 44b17824981deda0024317a3af55c2f487a879b7 [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 Grosser8bd7f3c2017-03-09 11:36:00 +0000347 const DataLayout &DL =
348 CurRegion.getEntry()->getParent()->getParent()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000349
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000350 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
351 return false;
352
Tobias Grosser1c787e02017-03-02 12:15:37 +0000353 for (LoadInst *Load : RequiredILS) {
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000354 if (!isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000355 return false;
356
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000357 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
358
359 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
360 Load->getAlignment(), DL))
361 continue;
362
Tobias Grosser1c787e02017-03-02 12:15:37 +0000363 if (NonAffineRegion->contains(Load) &&
364 Load->getParent() != NonAffineRegion->getEntry())
365 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000366 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000367 }
368
Johannes Doerfert09e36972015-10-07 20:17:36 +0000369 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
370
371 return true;
372}
373
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000374bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
375 Loop *Scope) const {
376 SetVector<Value *> Values;
377 findValues(S0, *SE, Values);
378 if (S1)
379 findValues(S1, *SE, Values);
380
381 SmallPtrSet<Value *, 8> PtrVals;
382 for (auto *V : Values) {
383 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
384 V = P2I->getOperand(0);
385
386 if (!V->getType()->isPointerTy())
387 continue;
388
389 auto *PtrSCEV = SE->getSCEVAtScope(V, Scope);
390 if (isa<SCEVConstant>(PtrSCEV))
391 continue;
392
393 auto *BasePtr = dyn_cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
394 if (!BasePtr)
395 return true;
396
397 auto *BasePtrVal = BasePtr->getValue();
398 if (PtrVals.insert(BasePtrVal).second) {
399 for (auto *PtrVal : PtrVals)
400 if (PtrVal != BasePtrVal && !AA->isNoAlias(PtrVal, BasePtrVal))
401 return true;
402 }
403 }
404
405 return false;
406}
407
Michael Kruse09eb4452016-03-03 22:10:47 +0000408bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000409 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000410
411 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000412 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000413 return false;
414
415 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
416 return false;
417
418 return true;
419}
420
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000421bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000422 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000423 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000424 Loop *L = LI->getLoopFor(&BB);
425 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000426
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000427 if (IsLoopBranch && L->isLoopLatch(&BB))
428 return false;
429
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000430 // Check for invalid usage of different pointers in one expression.
431 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
432 return false;
433
Michael Kruse09eb4452016-03-03 22:10:47 +0000434 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000435 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000436
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000437 if (AllowNonAffineSubRegions &&
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000438 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
439 return true;
440
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000441 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
442 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000443}
444
445bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000446 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000447 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000448
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000449 // Constant integer conditions are always affine.
450 if (isa<ConstantInt>(Condition))
451 return true;
452
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000453 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
454 auto Opcode = BinOp->getOpcode();
455 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
456 Value *Op0 = BinOp->getOperand(0);
457 Value *Op1 = BinOp->getOperand(1);
458 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
459 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
460 }
461 }
462
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000463 // Non constant conditions of branches need to be ICmpInst.
464 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000465 if (!IsLoopBranch && AllowNonAffineSubRegions &&
466 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
467 return true;
468 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000469 }
Tobias Grosser75805372011-04-29 06:27:02 +0000470
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000471 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000472
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000473 // Are both operands of the ICmp affine?
474 if (isa<UndefValue>(ICmp->getOperand(0)) ||
475 isa<UndefValue>(ICmp->getOperand(1)))
476 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000477
Tobias Grossera2f8fa32016-11-13 19:27:04 +0000478 Loop *L = LI->getLoopFor(&BB);
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000479 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
480 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000481
Johannes Doerfertbda81432016-12-02 17:55:41 +0000482 // If unsigned operations are not allowed try to approximate the region.
483 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
484 return !IsLoopBranch && AllowNonAffineSubRegions &&
485 addOverApproximatedRegion(RI->getRegionFor(&BB), Context);
486
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000487 // Check for invalid usage of different pointers in one expression.
488 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
489 involvesMultiplePtrs(RHS, nullptr, L))
490 return false;
491
492 // Check for invalid usage of different pointers in a relational comparison.
493 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
494 return false;
495
Michael Kruse09eb4452016-03-03 22:10:47 +0000496 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000497 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000498
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000499 if (!IsLoopBranch && AllowNonAffineSubRegions &&
500 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
501 return true;
502
503 if (IsLoopBranch)
504 return false;
505
506 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
507 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000508}
509
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000510bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000511 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000512 DetectionContext &Context) const {
513 Region &CurRegion = Context.CurRegion;
514
515 TerminatorInst *TI = BB.getTerminator();
516
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000517 if (AllowUnreachable && isa<UnreachableInst>(TI))
518 return true;
519
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000520 // Return instructions are only valid if the region is the top level region.
521 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
522 return true;
523
524 Value *Condition = getConditionFromTerminator(TI);
525
526 if (!Condition)
527 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
528
529 // UndefValue is not allowed as condition.
530 if (isa<UndefValue>(Condition))
531 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
532
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000533 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000534 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000535
536 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
537 assert(SI && "Terminator was neither branch nor switch");
538
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000539 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000540}
541
Johannes Doerfertcea61932016-02-21 19:13:19 +0000542bool ScopDetection::isValidCallInst(CallInst &CI,
543 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000544 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000545 return false;
546
547 if (CI.doesNotAccessMemory())
548 return true;
549
Johannes Doerfertcea61932016-02-21 19:13:19 +0000550 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000551 if (isValidIntrinsicInst(*II, Context))
552 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000553
Tobias Grosser75805372011-04-29 06:27:02 +0000554 Function *CalledFunction = CI.getCalledFunction();
555
556 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000557 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000558 return false;
559
Tobias Grosser898a6362016-03-23 06:40:15 +0000560 if (AllowModrefCall) {
561 switch (AA->getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000562 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000563 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000564 case FMRB_DoesNotAccessMemory:
565 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000566 // Implicitly disable delinearization since we have an unknown
567 // accesses with an unknown access function.
568 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000569 Context.AST.add(&CI);
570 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000571 case FMRB_OnlyReadsArgumentPointees:
572 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000573 for (const auto &Arg : CI.arg_operands()) {
574 if (!Arg->getType()->isPointerTy())
575 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000576
Tobias Grosser898a6362016-03-23 06:40:15 +0000577 // Bail if a pointer argument has a base address not known to
578 // ScalarEvolution. Note that a zero pointer is acceptable.
579 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
580 if (ArgSCEV->isZero())
581 continue;
582
583 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
584 if (!BP)
585 return false;
586
587 // Implicitly disable delinearization since we have an unknown
588 // accesses with an unknown access function.
589 Context.HasUnknownAccess = true;
590 }
591
592 Context.AST.add(&CI);
593 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000594 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000595 case FMRB_OnlyAccessesInaccessibleMem:
596 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000597 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000598 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000599 }
600
Johannes Doerfertcea61932016-02-21 19:13:19 +0000601 return false;
602}
603
604bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
605 DetectionContext &Context) const {
606 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000607 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000608
Johannes Doerfertcea61932016-02-21 19:13:19 +0000609 // The closest loop surrounding the call instruction.
610 Loop *L = LI->getLoopFor(II.getParent());
611
612 // The access function and base pointer for memory intrinsics.
613 const SCEV *AF;
614 const SCEVUnknown *BP;
615
616 switch (II.getIntrinsicID()) {
617 // Memory intrinsics that can be represented are supported.
618 case llvm::Intrinsic::memmove:
619 case llvm::Intrinsic::memcpy:
620 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000621 if (!AF->isZero()) {
622 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
623 // Bail if the source pointer is not valid.
624 if (!isValidAccess(&II, AF, BP, Context))
625 return false;
626 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000627 // Fall through
628 case llvm::Intrinsic::memset:
629 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000630 if (!AF->isZero()) {
631 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
632 // Bail if the destination pointer is not valid.
633 if (!isValidAccess(&II, AF, BP, Context))
634 return false;
635 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000636
637 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000638 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000639 Context))
640 return false;
641
642 return true;
643 default:
644 break;
645 }
646
Tobias Grosser75805372011-04-29 06:27:02 +0000647 return false;
648}
649
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000650bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
651 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000652 // A reference to function argument or constant value is invariant.
653 if (isa<Argument>(Val) || isa<Constant>(Val))
654 return true;
655
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000656 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000657 if (!I)
658 return false;
659
660 if (!Reg.contains(I))
661 return true;
662
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000663 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
664 // is not hoistable, it will be rejected later, but here we assume it is and
665 // that makes the value invariant.
666 if (auto LI = dyn_cast<LoadInst>(I)) {
667 Ctx.RequiredILS.insert(LI);
668 return true;
669 }
670
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000671 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000672}
673
Tobias Grosserc80d6972016-09-02 06:33:33 +0000674/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000675/// register the '...' components.
676///
677/// Array access expressions as they are generated by gfortran contain smax(0,
678/// size) expressions that confuse the 'normal' delinearization algorithm.
679/// However, if we extract such expressions before the normal delinearization
680/// takes place they can actually help to identify array size expressions in
681/// fortran accesses. For the subsequently following delinearization the smax(0,
682/// size) component can be replaced by just 'size'. This is correct as we will
683/// always add and verify the assumption that for all subscript expressions
684/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
685/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000686class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000687public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000688 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
689 std::vector<const SCEV *> *Terms = nullptr) {
690 SCEVRemoveMax Rewriter(SE, Terms);
691 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000692 }
693
694 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000695 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000696
697 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000698 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000699 auto Res = visit(Expr->getOperand(1));
700 if (Terms)
701 (*Terms).push_back(Res);
702 return Res;
703 }
704
705 return Expr;
706 }
707
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000708private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000709 std::vector<const SCEV *> *Terms;
710};
711
Tobias Grosserd68ba422015-11-24 05:00:36 +0000712SmallVector<const SCEV *, 4>
713ScopDetection::getDelinearizationTerms(DetectionContext &Context,
714 const SCEVUnknown *BasePointer) const {
715 SmallVector<const SCEV *, 4> Terms;
716 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000717 std::vector<const SCEV *> MaxTerms;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000718 SCEVRemoveMax::rewrite(Pair.second, *SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000719 if (MaxTerms.size() > 0) {
720 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
721 continue;
722 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000723 // In case the outermost expression is a plain add, we check if any of its
724 // terms has the form 4 * %inst * %param * %param ..., aka a term that
725 // contains a product between a parameter and an instruction that is
726 // inside the scop. Such instructions, if allowed at all, are instructions
727 // SCEV can not represent, but Polly is still looking through. As a
728 // result, these instructions can depend on induction variables and are
729 // most likely no array sizes. However, terms that are multiplied with
730 // them are likely candidates for array sizes.
731 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
732 for (auto Op : AF->operands()) {
733 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
734 SE->collectParametricTerms(AF2, Terms);
735 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
736 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000737
Tobias Grosserd68ba422015-11-24 05:00:36 +0000738 for (auto *MulOp : AF2->operands()) {
739 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
740 Operands.push_back(Const);
741 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
742 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
743 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000744 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000745
746 } else {
747 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000748 }
749 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000750 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000751 if (Operands.size())
752 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000753 }
754 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000755 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000756 if (Terms.empty())
757 SE->collectParametricTerms(Pair.second, Terms);
758 }
759 return Terms;
760}
Sebastian Pope8863b82014-05-12 19:02:02 +0000761
Tobias Grosserd68ba422015-11-24 05:00:36 +0000762bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
763 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000764 const SCEVUnknown *BasePointer,
765 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000766 Value *BaseValue = BasePointer->getValue();
767 Region &CurRegion = Context.CurRegion;
768 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000769 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000770 Sizes.clear();
771 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000772 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000773 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
774 auto *V = dyn_cast<Value>(Unknown->getValue());
775 if (auto *Load = dyn_cast<LoadInst>(V)) {
776 if (Context.CurRegion.contains(Load) &&
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000777 isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000778 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000779 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000780 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000781 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000782 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000783 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000784 Context, /*Assert=*/true, DelinearizedSize,
785 Context.Accesses[BasePointer].front().first, BaseValue);
786 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000787
Tobias Grosserd68ba422015-11-24 05:00:36 +0000788 // No array shape derived.
789 if (Sizes.empty()) {
790 if (AllowNonAffine)
791 return true;
792
Tobias Grosser230acc42014-09-13 14:47:55 +0000793 for (const auto &Pair : Context.Accesses[BasePointer]) {
794 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000795 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000796
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000797 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000798 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
799 BaseValue);
800 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000801 return false;
802 }
803 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000804 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000805 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000806 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000807}
808
Tobias Grosserd68ba422015-11-24 05:00:36 +0000809// We first store the resulting memory accesses in TempMemoryAccesses. Only
810// if the access functions for all memory accesses have been successfully
811// delinearized we continue. Otherwise, we either report a failure or, if
812// non-affine accesses are allowed, we drop the information. In case the
813// information is dropped the memory accesses need to be overapproximated
814// when translated to a polyhedral representation.
815bool ScopDetection::computeAccessFunctions(
816 DetectionContext &Context, const SCEVUnknown *BasePointer,
817 std::shared_ptr<ArrayShape> Shape) const {
818 Value *BaseValue = BasePointer->getValue();
819 bool BasePtrHasNonAffine = false;
820 MapInsnToMemAcc TempMemoryAccesses;
821 for (const auto &Pair : Context.Accesses[BasePointer]) {
822 const Instruction *Insn = Pair.first;
823 auto *AF = Pair.second;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000824 AF = SCEVRemoveMax::rewrite(AF, *SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000825 bool IsNonAffine = false;
826 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
827 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000828 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000829
830 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000831 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000832 Acc->DelinearizedSubscripts.push_back(Pair.second);
833 else
834 IsNonAffine = true;
835 } else {
836 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
837 Shape->DelinearizedSizes);
838 if (Acc->DelinearizedSubscripts.size() == 0)
839 IsNonAffine = true;
840 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000841 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000842 IsNonAffine = true;
843 }
844
845 // (Possibly) report non affine access
846 if (IsNonAffine) {
847 BasePtrHasNonAffine = true;
848 if (!AllowNonAffine)
849 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
850 Insn, BaseValue);
851 if (!KeepGoing && !AllowNonAffine)
852 return false;
853 }
854 }
855
856 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000857 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
858 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000859
860 return true;
861}
862
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000863bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
864 const SCEVUnknown *BasePointer,
865 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000866 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
867
868 auto Terms = getDelinearizationTerms(Context, BasePointer);
869
870 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
871 Context.ElementSize[BasePointer]);
872
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000873 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
874 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000875 return false;
876
877 return computeAccessFunctions(Context, BasePointer, Shape);
878}
879
880bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000881 // TODO: If we have an unknown access and other non-affine accesses we do
882 // not try to delinearize them for now.
883 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
884 return AllowNonAffine;
885
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000886 for (auto &Pair : Context.NonAffineAccesses) {
887 auto *BasePointer = Pair.first;
888 auto *Scope = Pair.second;
889 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000890 if (KeepGoing)
891 continue;
892 else
893 return false;
894 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000895 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000896 return true;
897}
898
Johannes Doerfertcea61932016-02-21 19:13:19 +0000899bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
900 const SCEVUnknown *BP,
901 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000902
Johannes Doerfertcea61932016-02-21 19:13:19 +0000903 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000904 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000905
Johannes Doerfertcea61932016-02-21 19:13:19 +0000906 auto *BV = BP->getValue();
907 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000908 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000909
Johannes Doerfertcea61932016-02-21 19:13:19 +0000910 // FIXME: Think about allowing IntToPtrInst
911 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
912 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
913
Tobias Grosser458fb782014-01-28 12:58:58 +0000914 // Check that the base address of the access is invariant in the current
915 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000916 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000917 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000918
Johannes Doerfertcea61932016-02-21 19:13:19 +0000919 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000920
Johannes Doerfertcea61932016-02-21 19:13:19 +0000921 const SCEV *Size;
922 if (!isa<MemIntrinsic>(Inst)) {
923 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000924 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000925 auto *SizeTy =
926 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
927 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000928 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000929
Johannes Doerfertcea61932016-02-21 19:13:19 +0000930 if (Context.ElementSize[BP]) {
931 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
932 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
933 Inst, BV);
934
935 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
936 } else {
937 Context.ElementSize[BP] = Size;
938 }
939
940 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000941 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000942 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000943 for (const Loop *L : Loops)
944 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000945 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000946
Michael Kruse09eb4452016-03-03 22:10:47 +0000947 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000948 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000949 // Do not try to delinearize memory intrinsics and force them to be affine.
950 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
951 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
952 BV);
953 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
954 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000955
Johannes Doerfertcea61932016-02-21 19:13:19 +0000956 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000957 Context.NonAffineAccesses.insert(
958 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000959 } else if (!AllowNonAffine && !IsAffine) {
960 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
961 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000962 }
Tobias Grosser75805372011-04-29 06:27:02 +0000963
Tobias Grosser1eedb672014-09-24 21:04:29 +0000964 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000965 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000966
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000967 // Check if the base pointer of the memory access does alias with
968 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000969 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000970 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000971 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000972 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000973
Tobias Grosser1eedb672014-09-24 21:04:29 +0000974 if (!AS.isMustAlias()) {
975 if (PollyUseRuntimeAliasChecks) {
976 bool CanBuildRunTimeCheck = true;
977 // The run-time alias check places code that involves the base pointer at
978 // the beginning of the SCoP. This breaks if the base pointer is defined
979 // inside the scop. Hence, we can only create a run-time check if we are
980 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000981 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000982 for (const auto &Ptr : AS) {
983 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000984 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000985 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000986 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE, *DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000987 Context.RequiredILS.insert(Load);
988 continue;
989 }
990
Tobias Grosser1eedb672014-09-24 21:04:29 +0000991 CanBuildRunTimeCheck = false;
992 break;
993 }
994 }
995
996 if (CanBuildRunTimeCheck)
997 return true;
998 }
Michael Kruse70131d32016-01-27 17:09:17 +0000999 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001000 }
Tobias Grosser75805372011-04-29 06:27:02 +00001001
1002 return true;
1003}
1004
Johannes Doerfertcea61932016-02-21 19:13:19 +00001005bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1006 DetectionContext &Context) const {
1007 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +00001008 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001009 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
1010 const SCEVUnknown *BasePointer;
1011
1012 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
1013
1014 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1015}
1016
Tobias Grosser75805372011-04-29 06:27:02 +00001017bool ScopDetection::isValidInstruction(Instruction &Inst,
1018 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001019 for (auto &Op : Inst.operands()) {
1020 auto *OpInst = dyn_cast<Instruction>(&Op);
1021
1022 if (!OpInst)
1023 continue;
1024
1025 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
1026 return false;
1027 }
1028
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001029 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1030 return false;
1031
Tobias Grosser75805372011-04-29 06:27:02 +00001032 // We only check the call instruction but not invoke instruction.
1033 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001034 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001035 return true;
1036
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001037 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001038 }
1039
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001040 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001041 if (!isa<AllocaInst>(Inst))
1042 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001043
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001044 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001045 }
1046
1047 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001048 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001049 Context.hasStores |= isa<StoreInst>(MemInst);
1050 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001051 if (!MemInst.isSimple())
1052 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1053 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001054
Michael Kruse70131d32016-01-27 17:09:17 +00001055 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001056 }
Tobias Grosser75805372011-04-29 06:27:02 +00001057
1058 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001059 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001060}
1061
Tobias Grosser349d1c32016-09-20 17:05:22 +00001062/// Check whether @p L has exiting blocks.
1063///
1064/// @param L The loop of interest
1065///
1066/// @return True if the loop has exiting blocks, false otherwise.
1067static bool hasExitingBlocks(Loop *L) {
1068 SmallVector<BasicBlock *, 4> ExitingBlocks;
1069 L->getExitingBlocks(ExitingBlocks);
1070 return !ExitingBlocks.empty();
1071}
1072
Johannes Doerfertd020b772015-08-27 06:53:52 +00001073bool ScopDetection::canUseISLTripCount(Loop *L,
1074 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001075 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1076 // need to overapproximate it as a boxed loop.
1077 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001078 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001079 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001080 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001081 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001082 return false;
1083 }
1084
Johannes Doerfertd020b772015-08-27 06:53:52 +00001085 // We can use ISL to compute the trip count of L.
1086 return true;
1087}
1088
Tobias Grosser75805372011-04-29 06:27:02 +00001089bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001090 // Loops that contain part but not all of the blocks of a region cannot be
1091 // handled by the schedule generation. Such loop constructs can happen
1092 // because a region can contain BBs that have no path to the exit block
1093 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1094 // loop.
1095 //
1096 // _______________
1097 // | Loop Header | <-----------.
1098 // --------------- |
1099 // | |
1100 // _______________ ______________
1101 // | RegionEntry |-----> | RegionExit |----->
1102 // --------------- --------------
1103 // |
1104 // _______________
1105 // | EndlessLoop | <--.
1106 // --------------- |
1107 // | |
1108 // \------------/
1109 //
1110 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1111 // neither entirely contained in the region RegionEntry->RegionExit
1112 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1113 // in the loop.
1114 // The block EndlessLoop is contained in the region because Region::contains
1115 // tests whether it is not dominated by RegionExit. This is probably to not
1116 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1117 // end can also be formed by an UnreachableInst. This case is already caught
1118 // by isErrorBlock(). We hence only have to reject endless loops here.
1119 if (!hasExitingBlocks(L))
1120 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1121
Johannes Doerfertf61df692015-10-04 14:56:08 +00001122 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001123 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001124
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001125 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001126 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001127 while (R != &Context.CurRegion && !R->contains(L))
1128 R = R->getParent();
1129
1130 if (addOverApproximatedRegion(R, Context))
1131 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001132 }
Tobias Grosser75805372011-04-29 06:27:02 +00001133
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001134 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001135 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001136}
1137
Tobias Grosserc80d6972016-09-02 06:33:33 +00001138/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001139/// count that is not known to be less than @MinProfitableTrips.
1140ScopDetection::LoopStats
1141ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001142 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001143 auto *TripCount = SE.getBackedgeTakenCount(L);
1144
Tobias Grosserb45ae562016-11-26 07:37:46 +00001145 int NumLoops = 1;
1146 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001147 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001148 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001149 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1150 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001151
Tobias Grosserb45ae562016-11-26 07:37:46 +00001152 for (auto &SubLoop : *L) {
1153 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1154 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001155 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001156 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001157
Tobias Grosserb45ae562016-11-26 07:37:46 +00001158 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001159}
1160
Tobias Grosserb45ae562016-11-26 07:37:46 +00001161ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001162ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1163 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001164 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001165 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001166
Tobias Grossercd01a362017-02-17 08:12:36 +00001167 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001168 L = L ? R->outermostLoopInRegion(L) : nullptr;
1169 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001170
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001171 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001172 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001173
1174 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001175 if (R->contains(SubLoop)) {
1176 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001177 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001178 LoopNum += Stats.NumLoops;
1179 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1180 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001181
Tobias Grosserb45ae562016-11-26 07:37:46 +00001182 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001183}
1184
Tobias Grosser75805372011-04-29 06:27:02 +00001185Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001186 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001187 std::unique_ptr<Region> LastValidRegion;
1188 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001189
1190 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1191
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001192 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001193 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001194 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001195 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1196 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001197 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001198 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001199
Johannes Doerfert717b8662015-09-08 21:44:27 +00001200 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001201 // If the exit is valid check all blocks
1202 // - if true, a valid region was found => store it + keep expanding
1203 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001204 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1205 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001206 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001207 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001208 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001209
Tobias Grosserd7e58642013-04-10 06:55:45 +00001210 // Store this region, because it is the greatest valid (encountered so
1211 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001212 if (LastValidRegion) {
1213 removeCachedResults(*LastValidRegion);
1214 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1215 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001216 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001217
1218 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001219 ExpandedRegion =
1220 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001221
1222 } else {
1223 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001224 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001225 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001226 ExpandedRegion =
1227 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001228 }
Tobias Grosser75805372011-04-29 06:27:02 +00001229 }
1230
Tobias Grosser378a9f22013-11-16 19:34:11 +00001231 DEBUG({
1232 if (LastValidRegion)
1233 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1234 else
1235 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1236 });
Tobias Grosser75805372011-04-29 06:27:02 +00001237
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001238 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001239}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001240static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001241 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001242 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001243 return false;
1244
1245 return true;
1246}
Tobias Grosser75805372011-04-29 06:27:02 +00001247
Tobias Grosserb45ae562016-11-26 07:37:46 +00001248void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001249 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001250 if (ValidRegions.count(SubRegion.get())) {
1251 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001252 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001253 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001254 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001255}
1256
Johannes Doerferte46925f2015-10-01 10:59:14 +00001257void ScopDetection::removeCachedResults(const Region &R) {
1258 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001259}
1260
Tobias Grosser75805372011-04-29 06:27:02 +00001261void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001262 const auto &It = DetectionContextMap.insert(std::make_pair(
1263 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001264 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001265
1266 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001267 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001268 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001269 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001270 RegionIsValid = isValidRegion(Context);
1271
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001272 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001273
Johannes Doerferte46925f2015-10-01 10:59:14 +00001274 if (HasErrors) {
1275 removeCachedResults(R);
1276 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001277 ValidRegions.insert(&R);
1278 return;
1279 }
1280
David Blaikieb035f6d2014-04-15 18:45:27 +00001281 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001282 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001283
1284 // Try to expand regions.
1285 //
1286 // As the region tree normally only contains canonical regions, non canonical
1287 // regions that form a Scop are not found. Therefore, those non canonical
1288 // regions are checked by expanding the canonical ones.
1289
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001290 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001291
David Blaikieb035f6d2014-04-15 18:45:27 +00001292 for (auto &SubRegion : R)
1293 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001294
Tobias Grosser26108892014-04-02 20:18:19 +00001295 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001296 // Skip invalid regions. Regions may become invalid, if they are element of
1297 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001298 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001299 continue;
1300
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001301 // Skip regions that had errors.
1302 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1303 if (HadErrors)
1304 continue;
1305
Tobias Grosser75805372011-04-29 06:27:02 +00001306 Region *ExpandedR = expandRegion(*CurrentRegion);
1307
1308 if (!ExpandedR)
1309 continue;
1310
1311 R.addSubRegion(ExpandedR, true);
1312 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001313 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001314 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001315 }
1316}
1317
1318bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001319 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001320
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001321 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001322 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001323 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1324 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001325 return false;
1326 }
1327
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001328 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001329 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1330
1331 // Also check exception blocks (and possibly register them as non-affine
1332 // regions). Even though exception blocks are not modeled, we use them
1333 // to forward-propagate domain constraints during ScopInfo construction.
1334 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1335 return false;
1336
1337 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001338 continue;
1339
Tobias Grosser1d191902014-03-03 13:13:55 +00001340 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001341 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001342 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001343 }
Tobias Grosser75805372011-04-29 06:27:02 +00001344
Sebastian Pope8863b82014-05-12 19:02:02 +00001345 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001346 return false;
1347
Tobias Grosser75805372011-04-29 06:27:02 +00001348 return true;
1349}
1350
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001351bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1352 int NumLoops) const {
1353 int InstCount = 0;
1354
Tobias Grosserb316dc12016-09-08 14:08:05 +00001355 if (NumLoops == 0)
1356 return false;
1357
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001358 for (auto *BB : Context.CurRegion.blocks())
1359 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001360 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001361
1362 InstCount = InstCount / NumLoops;
1363
1364 return InstCount >= ProfitabilityMinPerLoopInstructions;
1365}
1366
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001367bool ScopDetection::hasPossiblyDistributableLoop(
1368 DetectionContext &Context) const {
1369 for (auto *BB : Context.CurRegion.blocks()) {
1370 auto *L = LI->getLoopFor(BB);
1371 if (!Context.CurRegion.contains(L))
1372 continue;
1373 if (Context.BoxedLoopsSet.count(L))
1374 continue;
1375 unsigned StmtsWithStoresInLoops = 0;
1376 for (auto *LBB : L->blocks()) {
1377 bool MemStore = false;
1378 for (auto &I : *LBB)
1379 MemStore |= isa<StoreInst>(&I);
1380 StmtsWithStoresInLoops += MemStore;
1381 }
1382 return (StmtsWithStoresInLoops > 1);
1383 }
1384 return false;
1385}
1386
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001387bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1388 Region &CurRegion = Context.CurRegion;
1389
1390 if (PollyProcessUnprofitable)
1391 return true;
1392
1393 // We can probably not do a lot on scops that only write or only read
1394 // data.
1395 if (!Context.hasStores || !Context.hasLoads)
1396 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1397
Tobias Grossercd01a362017-02-17 08:12:36 +00001398 int NumLoops =
1399 countBeneficialLoops(&CurRegion, *SE, *LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001400 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001401
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001402 // Scops with at least two loops may allow either loop fusion or tiling and
1403 // are consequently interesting to look at.
1404 if (NumAffineLoops >= 2)
1405 return true;
1406
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001407 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1408 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1409 return true;
1410
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001411 // Scops that contain a loop with a non-trivial amount of computation per
1412 // loop-iteration are interesting as we may be able to parallelize such
1413 // loops. Individual loops that have only a small amount of computation
1414 // per-iteration are performance-wise very fragile as any change to the
1415 // loop induction variables may affect performance. To not cause spurious
1416 // performance regressions, we do not consider such loops.
1417 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1418 return true;
1419
1420 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001421}
1422
Tobias Grosser75805372011-04-29 06:27:02 +00001423bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001424 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001425
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001426 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001427
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001428 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001429 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001430 return false;
1431 }
1432
Tobias Grosser134a5722017-03-07 15:50:43 +00001433 DebugLoc DbgLoc;
1434 if (isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
1435 DEBUG(dbgs() << "Unreachable in exit\n");
1436 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1437 CurRegion.getExit(), DbgLoc);
1438 }
1439
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001440 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001441 DEBUG({
1442 dbgs() << "Region entry does not match -polly-region-only";
1443 dbgs() << "\n";
1444 });
1445 return false;
1446 }
1447
Tobias Grosserd654c252012-04-10 18:12:19 +00001448 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001449 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001450 if (CurRegion.getEntry() ==
1451 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1452 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001453
Hongbin Zheng94868e62012-04-07 12:29:17 +00001454 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001455 return false;
1456
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001457 if (!isReducibleRegion(CurRegion, DbgLoc))
1458 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1459 &CurRegion, DbgLoc);
1460
Tobias Grosser75805372011-04-29 06:27:02 +00001461 DEBUG(dbgs() << "OK\n");
1462 return true;
1463}
1464
Tobias Grosser629109b2016-08-03 12:00:07 +00001465void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001466 F->addFnAttr(PollySkipFnAttr);
1467}
1468
Tobias Grosser75805372011-04-29 06:27:02 +00001469bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001470 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001471}
1472
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001473void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001474 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001475 unsigned LineEntry, LineExit;
1476 std::string FileName;
1477
Tobias Grosser00dc3092014-03-02 12:02:46 +00001478 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001479 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1480 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001481 }
1482}
1483
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001484void ScopDetection::emitMissedRemarks(const Function &F) {
1485 for (auto &DIt : DetectionContextMap) {
1486 auto &DC = DIt.getSecond();
1487 if (DC.Log.hasErrors())
1488 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001489 }
1490}
1491
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001492bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001493 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001494 ///
1495 /// WHITE - Unvisited BB in DFS walk.
1496 /// GREY - BBs which are currently on the DFS stack for processing.
1497 /// BLACK - Visited and completely processed BB.
1498 enum Color { WHITE, GREY, BLACK };
1499
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001500 BasicBlock *REntry = R.getEntry();
1501 BasicBlock *RExit = R.getExit();
1502 // Map to match the color of a BasicBlock during the DFS walk.
1503 DenseMap<const BasicBlock *, Color> BBColorMap;
1504 // Stack keeping track of current BB and index of next child to be processed.
1505 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1506
1507 unsigned AdjacentBlockIndex = 0;
1508 BasicBlock *CurrBB, *SuccBB;
1509 CurrBB = REntry;
1510
1511 // Initialize the map for all BB with WHITE color.
1512 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001513 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001514
1515 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001516 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001517 DFSStack.push(std::make_pair(CurrBB, 0));
1518
1519 while (!DFSStack.empty()) {
1520 // Get next BB on stack to be processed.
1521 CurrBB = DFSStack.top().first;
1522 AdjacentBlockIndex = DFSStack.top().second;
1523 DFSStack.pop();
1524
1525 // Loop to iterate over the successors of current BB.
1526 const TerminatorInst *TInst = CurrBB->getTerminator();
1527 unsigned NSucc = TInst->getNumSuccessors();
1528 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1529 ++I, ++AdjacentBlockIndex) {
1530 SuccBB = TInst->getSuccessor(I);
1531
1532 // Checks for region exit block and self-loops in BB.
1533 if (SuccBB == RExit || SuccBB == CurrBB)
1534 continue;
1535
1536 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001537 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001538 // Push the current BB and the index of the next child to be visited.
1539 DFSStack.push(std::make_pair(CurrBB, I + 1));
1540 // Push the next BB to be processed.
1541 DFSStack.push(std::make_pair(SuccBB, 0));
1542 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001543 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001544 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001545 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001546 // GREY indicates a loop in the control flow.
1547 // If the destination dominates the source, it is a natural loop
1548 // else, an irreducible control flow in the region is detected.
1549 if (!DT->dominates(SuccBB, CurrBB)) {
1550 // Get debug info of instruction which causes irregular control flow.
1551 DbgLoc = TInst->getDebugLoc();
1552 return false;
1553 }
1554 }
1555 }
1556
1557 // If all children of current BB have been processed,
1558 // then mark that BB as fully processed.
1559 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001560 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001561 }
1562
1563 return true;
1564}
1565
Tobias Grosserb45ae562016-11-26 07:37:46 +00001566void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1567 bool OnlyProfitable) {
1568 if (!OnlyProfitable) {
1569 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001570 MaxNumLoopsInScop =
1571 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001572 if (Stats.MaxDepth == 1)
1573 NumScopsDepthOne++;
1574 else if (Stats.MaxDepth == 2)
1575 NumScopsDepthTwo++;
1576 else if (Stats.MaxDepth == 3)
1577 NumScopsDepthThree++;
1578 else if (Stats.MaxDepth == 4)
1579 NumScopsDepthFour++;
1580 else if (Stats.MaxDepth == 5)
1581 NumScopsDepthFive++;
1582 else
1583 NumScopsDepthLarger++;
1584 } else {
1585 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001586 MaxNumLoopsInProfScop =
1587 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001588 if (Stats.MaxDepth == 1)
1589 NumProfScopsDepthOne++;
1590 else if (Stats.MaxDepth == 2)
1591 NumProfScopsDepthTwo++;
1592 else if (Stats.MaxDepth == 3)
1593 NumProfScopsDepthThree++;
1594 else if (Stats.MaxDepth == 4)
1595 NumProfScopsDepthFour++;
1596 else if (Stats.MaxDepth == 5)
1597 NumProfScopsDepthFive++;
1598 else
1599 NumProfScopsDepthLarger++;
1600 }
1601}
1602
Tobias Grosser75805372011-04-29 06:27:02 +00001603bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001604 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001605 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001606 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001607 return false;
1608
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001609 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001610 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001611 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001612 Region *TopRegion = RI->getTopLevelRegion();
1613
Tobias Grosser2ff87232011-10-23 11:17:06 +00001614 releaseMemory();
1615
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001616 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001617 return false;
1618
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001619 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001620 return false;
1621
1622 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001623
Tobias Grosserb45ae562016-11-26 07:37:46 +00001624 NumScopRegions += ValidRegions.size();
1625
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001626 // Prune non-profitable regions.
1627 for (auto &DIt : DetectionContextMap) {
1628 auto &DC = DIt.getSecond();
1629 if (DC.Log.hasErrors())
1630 continue;
1631 if (!ValidRegions.count(&DC.CurRegion))
1632 continue;
Tobias Grossercd01a362017-02-17 08:12:36 +00001633 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, *SE, *LI, 0);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001634 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
1635 if (isProfitableRegion(DC)) {
1636 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001637 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001638 }
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001639
1640 ValidRegions.remove(&DC.CurRegion);
1641 }
1642
Tobias Grosserb45ae562016-11-26 07:37:46 +00001643 NumProfScopRegions += ValidRegions.size();
Tobias Grossercd01a362017-02-17 08:12:36 +00001644 NumLoopsOverall += countBeneficialLoops(TopRegion, *SE, *LI, 0).NumLoops;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001645
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001646 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001647 if (PollyTrackFailures)
1648 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001649
Johannes Doerferta05214f2014-10-15 23:24:28 +00001650 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001651 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001652
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001653 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001654 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001655 return false;
1656}
1657
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001658ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001659ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001660 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001661 if (DCMIt == DetectionContextMap.end())
1662 return nullptr;
1663 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001664}
1665
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001666const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1667 const DetectionContext *DC = getDetectionContext(R);
1668 return DC ? &DC->Log : nullptr;
1669}
1670
Tobias Grosser75805372011-04-29 06:27:02 +00001671void polly::ScopDetection::verifyRegion(const Region &R) const {
1672 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001673
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001674 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001675 isValidRegion(Context);
1676}
1677
1678void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001679 if (!VerifyScops)
1680 return;
1681
Tobias Grosser26108892014-04-02 20:18:19 +00001682 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001683 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001684}
1685
1686void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001687 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001688 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001689 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001690 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001691 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001692 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001693 AU.setPreservesAll();
1694}
1695
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001696void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001697 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001698 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001699
1700 OS << "\n";
1701}
1702
1703void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001704 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001705 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001706
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001707 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001708}
1709
1710char ScopDetection::ID = 0;
1711
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001712Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1713
Tobias Grosser73600b82011-10-08 00:30:40 +00001714INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1715 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001716 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001717INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001718INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001719INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001720INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001721INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001722INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1723 "Polly - Detect static control parts (SCoPs)", false, false)