blob: 0d364145d309cb5dcff13f3eb4a639588b0f707f [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//
Michael Krusea6d48f52017-06-08 12:06:15 +000016// Every Scop fulfills these restrictions:
Tobias Grosser75805372011-04-29 06:27:02 +000017//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias 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 Grosserd8945ba2017-05-19 12:13:02 +000099static cl::opt<bool>
100 AllowFullFunction("polly-detect-full-functions",
101 cl::desc("Allow the detection of full functions"),
102 cl::init(false), cl::cat(PollyCategory));
103
Tobias Grosser483a90d2014-07-09 10:50:10 +0000104static cl::opt<std::string> OnlyRegion(
105 "polly-only-region",
106 cl::desc("Only run on certain regions (The provided identifier must "
107 "appear in the name of the region's entry block"),
108 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
109 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000110
Tobias Grosser60cd9322011-11-10 12:47:26 +0000111static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000112 IgnoreAliasing("polly-ignore-aliasing",
113 cl::desc("Ignore possible aliasing of the array bases"),
114 cl::Hidden, cl::init(false), cl::ZeroOrMore,
115 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000116
Johannes Doerfertbda81432016-12-02 17:55:41 +0000117bool polly::PollyAllowUnsignedOperations;
118static cl::opt<bool, true> XPollyAllowUnsignedOperations(
119 "polly-allow-unsigned-operations",
120 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
121 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
122 cl::init(true), cl::cat(PollyCategory));
123
Johannes Doerfertb164c792014-09-18 11:17:17 +0000124bool polly::PollyUseRuntimeAliasChecks;
125static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
126 "polly-use-runtime-alias-checks",
127 cl::desc("Use runtime alias checks to resolve possible aliasing."),
128 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
129 cl::init(true), cl::cat(PollyCategory));
130
Tobias Grosser637bd632013-05-07 07:31:10 +0000131static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000132 ReportLevel("polly-report",
133 cl::desc("Print information about the activities of Polly"),
134 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000135
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000136static cl::opt<bool> AllowDifferentTypes(
137 "polly-allow-differing-element-types",
138 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000139 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000140
Tobias Grosser531891e2012-11-01 16:45:20 +0000141static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000142 AllowNonAffine("polly-allow-nonaffine",
143 cl::desc("Allow non affine access functions in arrays"),
144 cl::Hidden, cl::init(false), cl::ZeroOrMore,
145 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000146
Tobias Grosser898a6362016-03-23 06:40:15 +0000147static cl::opt<bool>
148 AllowModrefCall("polly-allow-modref-calls",
149 cl::desc("Allow functions with known modref behavior"),
150 cl::Hidden, cl::init(false), cl::ZeroOrMore,
151 cl::cat(PollyCategory));
152
Johannes Doerfertba65c162015-02-24 11:45:21 +0000153static cl::opt<bool> AllowNonAffineSubRegions(
154 "polly-allow-nonaffine-branches",
155 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000156 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000157
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000158static cl::opt<bool>
159 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
160 cl::desc("Allow non affine conditions for loops"),
161 cl::Hidden, cl::init(false), cl::ZeroOrMore,
162 cl::cat(PollyCategory));
163
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000164static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000165 TrackFailures("polly-detect-track-failures",
166 cl::desc("Track failure strings in detecting scop regions"),
167 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000168 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000169
Andreas Simbuerger04472402014-05-24 09:25:10 +0000170static cl::opt<bool> KeepGoing("polly-detect-keep-going",
171 cl::desc("Do not fail on the first error."),
172 cl::Hidden, cl::ZeroOrMore, cl::init(false),
173 cl::cat(PollyCategory));
174
Sebastian Pop18016682014-04-08 21:20:44 +0000175static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000176 PollyDelinearizeX("polly-delinearize",
177 cl::desc("Delinearize array access functions"),
178 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000179 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000180
Tobias Grossera1689932014-02-18 18:49:49 +0000181static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000182 VerifyScops("polly-detect-verify",
183 cl::desc("Verify the detected SCoPs after each transformation"),
184 cl::Hidden, cl::init(false), cl::ZeroOrMore,
185 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000186
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000187bool polly::PollyInvariantLoadHoisting;
188static cl::opt<bool, true> XPollyInvariantLoadHoisting(
189 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
190 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000191 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000192
Tobias Grosserc80d6972016-09-02 06:33:33 +0000193/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000194static const unsigned MIN_LOOP_TRIP_COUNT = 8;
195
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000196bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000197bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000198StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000199
Tobias Grosser75805372011-04-29 06:27:02 +0000200//===----------------------------------------------------------------------===//
201// Statistics.
202
Tobias Grosserb45ae562016-11-26 07:37:46 +0000203STATISTIC(NumScopRegions, "Number of scops");
204STATISTIC(NumLoopsInScop, "Number of loops in scops");
205STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
206STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
207STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
208STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
209STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
210STATISTIC(NumScopsDepthLarger,
211 "Number of scops with maximal loop depth 6 and larger");
212STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
213STATISTIC(NumLoopsInProfScop,
214 "Number of loops in scops (profitable scops only)");
215STATISTIC(NumLoopsOverall, "Number of total loops");
216STATISTIC(NumProfScopsDepthOne,
217 "Number of scops with maximal loop depth 1 (profitable scops only)");
218STATISTIC(NumProfScopsDepthTwo,
219 "Number of scops with maximal loop depth 2 (profitable scops only)");
220STATISTIC(NumProfScopsDepthThree,
221 "Number of scops with maximal loop depth 3 (profitable scops only)");
222STATISTIC(NumProfScopsDepthFour,
223 "Number of scops with maximal loop depth 4 (profitable scops only)");
224STATISTIC(NumProfScopsDepthFive,
225 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000226STATISTIC(NumProfScopsDepthLarger,
227 "Number of scops with maximal loop depth 6 and larger "
228 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000229STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
230STATISTIC(MaxNumLoopsInProfScop,
231 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000232
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000233static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
234 bool OnlyProfitable);
235
Tobias Grosser8519f892013-12-18 10:49:53 +0000236class DiagnosticScopFound : public DiagnosticInfo {
237private:
238 static int PluginDiagnosticKind;
239
240 Function &F;
241 std::string FileName;
242 unsigned EntryLine, ExitLine;
243
244public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000245 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
246 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000247 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000248 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000249
250 virtual void print(DiagnosticPrinter &DP) const;
251
252 static bool classof(const DiagnosticInfo *DI) {
253 return DI->getKind() == PluginDiagnosticKind;
254 }
255};
256
Tobias Grosserdb6db502016-04-01 07:15:19 +0000257int DiagnosticScopFound::PluginDiagnosticKind =
258 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000259
Tobias Grosser8519f892013-12-18 10:49:53 +0000260void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000261 DP << "Polly detected an optimizable loop region (scop) in function '" << F
262 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000263
264 if (FileName.empty()) {
265 DP << "Scop location is unknown. Compile with debug info "
266 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000267 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000268 }
269
270 DP << FileName << ":" << EntryLine << ": Start of scop\n";
271 DP << FileName << ":" << ExitLine << ": End of scop";
272}
273
Tobias Grosser75805372011-04-29 06:27:02 +0000274//===----------------------------------------------------------------------===//
275// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000276
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000277ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
278 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
279 AliasAnalysis &AA)
280 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA) {
281
282 if (!PollyProcessUnprofitable && LI.empty())
283 return;
284
285 Region *TopRegion = RI.getTopLevelRegion();
286
287 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
288 return;
289
290 if (!isValidFunction(F))
291 return;
292
293 findScops(*TopRegion);
294
295 NumScopRegions += ValidRegions.size();
296
297 // Prune non-profitable regions.
298 for (auto &DIt : DetectionContextMap) {
299 auto &DC = DIt.getSecond();
300 if (DC.Log.hasErrors())
301 continue;
302 if (!ValidRegions.count(&DC.CurRegion))
303 continue;
304 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
305 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
306 if (isProfitableRegion(DC)) {
307 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
308 continue;
309 }
310
311 ValidRegions.remove(&DC.CurRegion);
312 }
313
314 NumProfScopRegions += ValidRegions.size();
315 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
316
317 // Only makes sense when we tracked errors.
318 if (PollyTrackFailures)
319 emitMissedRemarks(F);
320
321 if (ReportLevel)
322 printLocations(F);
323
324 assert(ValidRegions.size() <= DetectionContextMap.size() &&
325 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000326}
327
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000328template <class RR, typename... Args>
329inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
330 Args &&... Arguments) const {
331
332 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000333 RejectLog &Log = Context.Log;
334 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000335
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000336 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000337 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000338
339 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000340 DEBUG(dbgs() << "\n");
341 } else {
342 assert(!Assert && "Verification of detected scop failed");
343 }
344
345 return false;
346}
347
Tobias Grossera1689932014-02-18 18:49:49 +0000348bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
349 if (!ValidRegions.count(&R))
350 return false;
351
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000352 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000353 DetectionContextMap.erase(getBBPairForRegion(&R));
354 const auto &It = DetectionContextMap.insert(std::make_pair(
355 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000356 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000357 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000358 return isValidRegion(Context);
359 }
Tobias Grossera1689932014-02-18 18:49:49 +0000360
361 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000362}
363
Tobias Grosser4f129a62011-10-08 00:30:55 +0000364std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000365 // Get the first error we found. Even in keep-going mode, this is the first
366 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000367 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000368
369 // This can happen when we marked a region invalid, but didn't track
370 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000371 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000372 return "";
373
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000374 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000375 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000376}
377
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000378bool ScopDetection::addOverApproximatedRegion(Region *AR,
379 DetectionContext &Context) const {
380
381 // If we already know about Ar we can exit.
382 if (!Context.NonAffineSubRegionSet.insert(AR))
383 return true;
384
385 // All loops in the region have to be overapproximated too if there
386 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000387
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000388 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000389 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000390 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000391 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000392 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000393
394 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000395}
396
Johannes Doerfert09e36972015-10-07 20:17:36 +0000397bool ScopDetection::onlyValidRequiredInvariantLoads(
398 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
399 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000400 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000401
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000402 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
403 return false;
404
Tobias Grosser1c787e02017-03-02 12:15:37 +0000405 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000406 // If we already know a load has been accepted as required invariant, we
407 // already run the validation below once and consequently don't need to
408 // run it again. Hence, we return early. For certain test cases (e.g.,
409 // COSMO this avoids us spending 50% of scop-detection time in this
410 // very function (and its children).
411 if (Context.RequiredILS.count(Load))
412 continue;
413
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000414 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000415 return false;
416
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000417 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
418
419 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
420 Load->getAlignment(), DL))
421 continue;
422
Tobias Grosser1c787e02017-03-02 12:15:37 +0000423 if (NonAffineRegion->contains(Load) &&
424 Load->getParent() != NonAffineRegion->getEntry())
425 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000426 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000427 }
428
Johannes Doerfert09e36972015-10-07 20:17:36 +0000429 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
430
431 return true;
432}
433
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000434bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
435 Loop *Scope) const {
436 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000437 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000438 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000439 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000440
441 SmallPtrSet<Value *, 8> PtrVals;
442 for (auto *V : Values) {
443 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
444 V = P2I->getOperand(0);
445
446 if (!V->getType()->isPointerTy())
447 continue;
448
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000449 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000450 if (isa<SCEVConstant>(PtrSCEV))
451 continue;
452
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000453 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000454 if (!BasePtr)
455 return true;
456
457 auto *BasePtrVal = BasePtr->getValue();
458 if (PtrVals.insert(BasePtrVal).second) {
459 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000460 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000461 return true;
462 }
463 }
464
465 return false;
466}
467
Michael Kruse09eb4452016-03-03 22:10:47 +0000468bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000469 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000470
471 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000472 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000473 return false;
474
475 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
476 return false;
477
478 return true;
479}
480
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000481bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000482 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000483 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000484 Loop *L = LI.getLoopFor(&BB);
485 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000486
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000487 if (IsLoopBranch && L->isLoopLatch(&BB))
488 return false;
489
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000490 // Check for invalid usage of different pointers in one expression.
491 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
492 return false;
493
Michael Kruse09eb4452016-03-03 22:10:47 +0000494 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000495 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000496
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000497 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000498 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000499 return true;
500
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000501 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
502 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000503}
504
505bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000506 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000507 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000508
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000509 // Constant integer conditions are always affine.
510 if (isa<ConstantInt>(Condition))
511 return true;
512
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000513 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
514 auto Opcode = BinOp->getOpcode();
515 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
516 Value *Op0 = BinOp->getOperand(0);
517 Value *Op1 = BinOp->getOperand(1);
518 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
519 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
520 }
521 }
522
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000523 // Non constant conditions of branches need to be ICmpInst.
524 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000525 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000526 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000527 return true;
528 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000529 }
Tobias Grosser75805372011-04-29 06:27:02 +0000530
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000531 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000532
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000533 // Are both operands of the ICmp affine?
534 if (isa<UndefValue>(ICmp->getOperand(0)) ||
535 isa<UndefValue>(ICmp->getOperand(1)))
536 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000537
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000538 Loop *L = LI.getLoopFor(&BB);
539 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
540 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000541
Johannes Doerfertbda81432016-12-02 17:55:41 +0000542 // If unsigned operations are not allowed try to approximate the region.
543 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
544 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000545 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000546
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000547 // Check for invalid usage of different pointers in one expression.
548 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
549 involvesMultiplePtrs(RHS, nullptr, L))
550 return false;
551
552 // Check for invalid usage of different pointers in a relational comparison.
553 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
554 return false;
555
Michael Kruse09eb4452016-03-03 22:10:47 +0000556 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000557 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000558
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000559 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000560 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000561 return true;
562
563 if (IsLoopBranch)
564 return false;
565
566 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
567 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000568}
569
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000570bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000571 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000572 DetectionContext &Context) const {
573 Region &CurRegion = Context.CurRegion;
574
575 TerminatorInst *TI = BB.getTerminator();
576
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000577 if (AllowUnreachable && isa<UnreachableInst>(TI))
578 return true;
579
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000580 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000581 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000582 return true;
583
584 Value *Condition = getConditionFromTerminator(TI);
585
586 if (!Condition)
587 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
588
589 // UndefValue is not allowed as condition.
590 if (isa<UndefValue>(Condition))
591 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
592
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000593 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000594 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000595
596 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
597 assert(SI && "Terminator was neither branch nor switch");
598
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000599 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000600}
601
Johannes Doerfertcea61932016-02-21 19:13:19 +0000602bool ScopDetection::isValidCallInst(CallInst &CI,
603 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000604 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000605 return false;
606
607 if (CI.doesNotAccessMemory())
608 return true;
609
Johannes Doerfertcea61932016-02-21 19:13:19 +0000610 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000611 if (isValidIntrinsicInst(*II, Context))
612 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000613
Tobias Grosser75805372011-04-29 06:27:02 +0000614 Function *CalledFunction = CI.getCalledFunction();
615
616 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000617 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000618 return false;
619
Tobias Grosser898a6362016-03-23 06:40:15 +0000620 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000621 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000622 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000623 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000624 case FMRB_DoesNotAccessMemory:
625 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000626 // Implicitly disable delinearization since we have an unknown
627 // accesses with an unknown access function.
628 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000629 Context.AST.add(&CI);
630 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000631 case FMRB_OnlyReadsArgumentPointees:
632 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000633 for (const auto &Arg : CI.arg_operands()) {
634 if (!Arg->getType()->isPointerTy())
635 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000636
Tobias Grosser898a6362016-03-23 06:40:15 +0000637 // Bail if a pointer argument has a base address not known to
638 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000639 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000640 if (ArgSCEV->isZero())
641 continue;
642
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000643 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000644 if (!BP)
645 return false;
646
647 // Implicitly disable delinearization since we have an unknown
648 // accesses with an unknown access function.
649 Context.HasUnknownAccess = true;
650 }
651
652 Context.AST.add(&CI);
653 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000654 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000655 case FMRB_OnlyAccessesInaccessibleMem:
656 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000657 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000658 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000659 }
660
Johannes Doerfertcea61932016-02-21 19:13:19 +0000661 return false;
662}
663
664bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
665 DetectionContext &Context) const {
666 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000667 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000668
Johannes Doerfertcea61932016-02-21 19:13:19 +0000669 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000670 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000671
672 // The access function and base pointer for memory intrinsics.
673 const SCEV *AF;
674 const SCEVUnknown *BP;
675
676 switch (II.getIntrinsicID()) {
677 // Memory intrinsics that can be represented are supported.
678 case llvm::Intrinsic::memmove:
679 case llvm::Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000680 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000681 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000682 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000683 // Bail if the source pointer is not valid.
684 if (!isValidAccess(&II, AF, BP, Context))
685 return false;
686 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000687 // Fall through
688 case llvm::Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000689 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000690 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000691 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000692 // Bail if the destination pointer is not valid.
693 if (!isValidAccess(&II, AF, BP, Context))
694 return false;
695 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000696
697 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000698 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000699 Context))
700 return false;
701
702 return true;
703 default:
704 break;
705 }
706
Tobias Grosser75805372011-04-29 06:27:02 +0000707 return false;
708}
709
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000710bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
711 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000712 // A reference to function argument or constant value is invariant.
713 if (isa<Argument>(Val) || isa<Constant>(Val))
714 return true;
715
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000716 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000717 if (!I)
718 return false;
719
720 if (!Reg.contains(I))
721 return true;
722
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000723 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
724 // is not hoistable, it will be rejected later, but here we assume it is and
725 // that makes the value invariant.
726 if (auto LI = dyn_cast<LoadInst>(I)) {
727 Ctx.RequiredILS.insert(LI);
728 return true;
729 }
730
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000731 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000732}
733
Tobias Grosserc80d6972016-09-02 06:33:33 +0000734/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000735/// register the '...' components.
736///
Michael Krusea6d48f52017-06-08 12:06:15 +0000737/// Array access expressions as they are generated by GFortran contain smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000738/// size) expressions that confuse the 'normal' delinearization algorithm.
739/// However, if we extract such expressions before the normal delinearization
740/// takes place they can actually help to identify array size expressions in
Michael Krusea6d48f52017-06-08 12:06:15 +0000741/// Fortran accesses. For the subsequently following delinearization the smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000742/// size) component can be replaced by just 'size'. This is correct as we will
743/// always add and verify the assumption that for all subscript expressions
744/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
745/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000746class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000747public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000748 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
749 std::vector<const SCEV *> *Terms = nullptr) {
750 SCEVRemoveMax Rewriter(SE, Terms);
751 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000752 }
753
754 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000755 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000756
757 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000758 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000759 auto Res = visit(Expr->getOperand(1));
760 if (Terms)
761 (*Terms).push_back(Res);
762 return Res;
763 }
764
765 return Expr;
766 }
767
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000768private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000769 std::vector<const SCEV *> *Terms;
770};
771
Tobias Grosserd68ba422015-11-24 05:00:36 +0000772SmallVector<const SCEV *, 4>
773ScopDetection::getDelinearizationTerms(DetectionContext &Context,
774 const SCEVUnknown *BasePointer) const {
775 SmallVector<const SCEV *, 4> Terms;
776 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000777 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000778 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000779 if (MaxTerms.size() > 0) {
780 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
781 continue;
782 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000783 // In case the outermost expression is a plain add, we check if any of its
784 // terms has the form 4 * %inst * %param * %param ..., aka a term that
785 // contains a product between a parameter and an instruction that is
786 // inside the scop. Such instructions, if allowed at all, are instructions
787 // SCEV can not represent, but Polly is still looking through. As a
788 // result, these instructions can depend on induction variables and are
789 // most likely no array sizes. However, terms that are multiplied with
790 // them are likely candidates for array sizes.
791 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
792 for (auto Op : AF->operands()) {
793 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000794 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000795 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
796 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000797
Tobias Grosserd68ba422015-11-24 05:00:36 +0000798 for (auto *MulOp : AF2->operands()) {
799 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
800 Operands.push_back(Const);
801 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
802 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
803 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000804 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000805
806 } else {
807 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000808 }
809 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000810 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000811 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000812 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000813 }
814 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000815 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000816 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000817 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000818 }
819 return Terms;
820}
Sebastian Pope8863b82014-05-12 19:02:02 +0000821
Tobias Grosserd68ba422015-11-24 05:00:36 +0000822bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
823 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000824 const SCEVUnknown *BasePointer,
825 Loop *Scope) const {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000826 // If no sizes were found, all sizes are trivially valid. We allow this case
827 // to make it possible to pass known-affine accesses to the delinearization to
828 // try to recover some interesting multi-dimensional accesses, but to still
829 // allow the already known to be affine access in case the delinearization
830 // fails. In such situations, the delinearization will just return a Sizes
831 // array of size zero.
832 if (Sizes.size() == 0)
833 return true;
834
Tobias Grosserd68ba422015-11-24 05:00:36 +0000835 Value *BaseValue = BasePointer->getValue();
836 Region &CurRegion = Context.CurRegion;
837 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000838 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000839 Sizes.clear();
840 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000841 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000842 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
843 auto *V = dyn_cast<Value>(Unknown->getValue());
844 if (auto *Load = dyn_cast<LoadInst>(V)) {
845 if (Context.CurRegion.contains(Load) &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000846 isHoistableLoad(Load, CurRegion, LI, SE, DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000847 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000848 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000849 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000850 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000851 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000852 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000853 Context, /*Assert=*/true, DelinearizedSize,
854 Context.Accesses[BasePointer].front().first, BaseValue);
855 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000856
Tobias Grosserd68ba422015-11-24 05:00:36 +0000857 // No array shape derived.
858 if (Sizes.empty()) {
859 if (AllowNonAffine)
860 return true;
861
Tobias Grosser230acc42014-09-13 14:47:55 +0000862 for (const auto &Pair : Context.Accesses[BasePointer]) {
863 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000864 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000865
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000866 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000867 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
868 BaseValue);
869 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000870 return false;
871 }
872 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000873 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000874 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000875 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000876}
877
Tobias Grosserd68ba422015-11-24 05:00:36 +0000878// We first store the resulting memory accesses in TempMemoryAccesses. Only
879// if the access functions for all memory accesses have been successfully
880// delinearized we continue. Otherwise, we either report a failure or, if
881// non-affine accesses are allowed, we drop the information. In case the
882// information is dropped the memory accesses need to be overapproximated
883// when translated to a polyhedral representation.
884bool ScopDetection::computeAccessFunctions(
885 DetectionContext &Context, const SCEVUnknown *BasePointer,
886 std::shared_ptr<ArrayShape> Shape) const {
887 Value *BaseValue = BasePointer->getValue();
888 bool BasePtrHasNonAffine = false;
889 MapInsnToMemAcc TempMemoryAccesses;
890 for (const auto &Pair : Context.Accesses[BasePointer]) {
891 const Instruction *Insn = Pair.first;
892 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000893 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000894 bool IsNonAffine = false;
895 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
896 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000897 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000898
899 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000900 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000901 Acc->DelinearizedSubscripts.push_back(Pair.second);
902 else
903 IsNonAffine = true;
904 } else {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000905 if (Shape->DelinearizedSizes.size() == 0) {
906 Acc->DelinearizedSubscripts.push_back(AF);
907 } else {
908 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
909 Shape->DelinearizedSizes);
910 if (Acc->DelinearizedSubscripts.size() == 0)
911 IsNonAffine = true;
912 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000913 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000914 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000915 IsNonAffine = true;
916 }
917
918 // (Possibly) report non affine access
919 if (IsNonAffine) {
920 BasePtrHasNonAffine = true;
921 if (!AllowNonAffine)
922 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
923 Insn, BaseValue);
924 if (!KeepGoing && !AllowNonAffine)
925 return false;
926 }
927 }
928
929 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000930 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
931 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000932
933 return true;
934}
935
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000936bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
937 const SCEVUnknown *BasePointer,
938 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000939 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
940
941 auto Terms = getDelinearizationTerms(Context, BasePointer);
942
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000943 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
944 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000945
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000946 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
947 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000948 return false;
949
950 return computeAccessFunctions(Context, BasePointer, Shape);
951}
952
953bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000954 // TODO: If we have an unknown access and other non-affine accesses we do
955 // not try to delinearize them for now.
956 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
957 return AllowNonAffine;
958
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000959 for (auto &Pair : Context.NonAffineAccesses) {
960 auto *BasePointer = Pair.first;
961 auto *Scope = Pair.second;
962 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000963 if (KeepGoing)
964 continue;
965 else
966 return false;
967 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000968 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000969 return true;
970}
971
Johannes Doerfertcea61932016-02-21 19:13:19 +0000972bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
973 const SCEVUnknown *BP,
974 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000975
Johannes Doerfertcea61932016-02-21 19:13:19 +0000976 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000977 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000978
Johannes Doerfertcea61932016-02-21 19:13:19 +0000979 auto *BV = BP->getValue();
980 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000981 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000982
Johannes Doerfertcea61932016-02-21 19:13:19 +0000983 // FIXME: Think about allowing IntToPtrInst
984 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
985 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
986
Tobias Grosser458fb782014-01-28 12:58:58 +0000987 // Check that the base address of the access is invariant in the current
988 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000989 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000990 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000991
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000992 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000993
Johannes Doerfertcea61932016-02-21 19:13:19 +0000994 const SCEV *Size;
995 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000996 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000997 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000998 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000999 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1000 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001001 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +00001002
Johannes Doerfertcea61932016-02-21 19:13:19 +00001003 if (Context.ElementSize[BP]) {
1004 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1005 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1006 Inst, BV);
1007
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001008 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001009 } else {
1010 Context.ElementSize[BP] = Size;
1011 }
1012
1013 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001014 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001015 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001016 for (const Loop *L : Loops)
1017 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001018 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001019
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001020 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001021 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001022 // Do not try to delinearize memory intrinsics and force them to be affine.
1023 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1024 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1025 BV);
1026 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1027 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001028
Tobias Grosser1e55db32017-05-27 15:18:53 +00001029 if (!IsAffine || hasIVParams(AF))
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001030 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001031 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001032 } else if (!AllowNonAffine && !IsAffine) {
1033 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1034 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001035 }
Tobias Grosser75805372011-04-29 06:27:02 +00001036
Tobias Grosser1eedb672014-09-24 21:04:29 +00001037 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001038 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001039
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001040 // Check if the base pointer of the memory access does alias with
1041 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001042 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001043 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001044 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +00001045 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +00001046
Tobias Grosser1eedb672014-09-24 21:04:29 +00001047 if (!AS.isMustAlias()) {
1048 if (PollyUseRuntimeAliasChecks) {
1049 bool CanBuildRunTimeCheck = true;
1050 // The run-time alias check places code that involves the base pointer at
1051 // the beginning of the SCoP. This breaks if the base pointer is defined
1052 // inside the scop. Hence, we can only create a run-time check if we are
1053 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001054 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +00001055 for (const auto &Ptr : AS) {
1056 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001057 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001058 auto *Load = dyn_cast<LoadInst>(Inst);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001059 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001060 Context.RequiredILS.insert(Load);
1061 continue;
1062 }
1063
Tobias Grosser1eedb672014-09-24 21:04:29 +00001064 CanBuildRunTimeCheck = false;
1065 break;
1066 }
1067 }
1068
1069 if (CanBuildRunTimeCheck)
1070 return true;
1071 }
Michael Kruse70131d32016-01-27 17:09:17 +00001072 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001073 }
Tobias Grosser75805372011-04-29 06:27:02 +00001074
1075 return true;
1076}
1077
Johannes Doerfertcea61932016-02-21 19:13:19 +00001078bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1079 DetectionContext &Context) const {
1080 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001081 Loop *L = LI.getLoopFor(Inst->getParent());
1082 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001083 const SCEVUnknown *BasePointer;
1084
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001085 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001086
1087 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1088}
1089
Tobias Grosser75805372011-04-29 06:27:02 +00001090bool ScopDetection::isValidInstruction(Instruction &Inst,
1091 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001092 for (auto &Op : Inst.operands()) {
1093 auto *OpInst = dyn_cast<Instruction>(&Op);
1094
1095 if (!OpInst)
1096 continue;
1097
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001098 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT))
Tobias Grosserb12b0062015-11-11 12:44:18 +00001099 return false;
1100 }
1101
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001102 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1103 return false;
1104
Tobias Grosser75805372011-04-29 06:27:02 +00001105 // We only check the call instruction but not invoke instruction.
1106 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001107 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001108 return true;
1109
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001110 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001111 }
1112
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001113 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001114 if (!isa<AllocaInst>(Inst))
1115 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001116
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001117 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001118 }
1119
1120 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001121 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001122 Context.hasStores |= isa<StoreInst>(MemInst);
1123 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001124 if (!MemInst.isSimple())
1125 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1126 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001127
Michael Kruse70131d32016-01-27 17:09:17 +00001128 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001129 }
Tobias Grosser75805372011-04-29 06:27:02 +00001130
1131 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001132 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001133}
1134
Tobias Grosser349d1c32016-09-20 17:05:22 +00001135/// Check whether @p L has exiting blocks.
1136///
1137/// @param L The loop of interest
1138///
1139/// @return True if the loop has exiting blocks, false otherwise.
1140static bool hasExitingBlocks(Loop *L) {
1141 SmallVector<BasicBlock *, 4> ExitingBlocks;
1142 L->getExitingBlocks(ExitingBlocks);
1143 return !ExitingBlocks.empty();
1144}
1145
Johannes Doerfertd020b772015-08-27 06:53:52 +00001146bool ScopDetection::canUseISLTripCount(Loop *L,
1147 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001148 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1149 // need to overapproximate it as a boxed loop.
1150 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001151 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001152 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001153 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001154 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001155 return false;
1156 }
1157
Johannes Doerfertd020b772015-08-27 06:53:52 +00001158 // We can use ISL to compute the trip count of L.
1159 return true;
1160}
1161
Tobias Grosser75805372011-04-29 06:27:02 +00001162bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001163 // Loops that contain part but not all of the blocks of a region cannot be
1164 // handled by the schedule generation. Such loop constructs can happen
1165 // because a region can contain BBs that have no path to the exit block
1166 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1167 // loop.
1168 //
1169 // _______________
1170 // | Loop Header | <-----------.
1171 // --------------- |
1172 // | |
1173 // _______________ ______________
1174 // | RegionEntry |-----> | RegionExit |----->
1175 // --------------- --------------
1176 // |
1177 // _______________
1178 // | EndlessLoop | <--.
1179 // --------------- |
1180 // | |
1181 // \------------/
1182 //
1183 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1184 // neither entirely contained in the region RegionEntry->RegionExit
1185 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1186 // in the loop.
1187 // The block EndlessLoop is contained in the region because Region::contains
1188 // tests whether it is not dominated by RegionExit. This is probably to not
1189 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1190 // end can also be formed by an UnreachableInst. This case is already caught
1191 // by isErrorBlock(). We hence only have to reject endless loops here.
1192 if (!hasExitingBlocks(L))
1193 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1194
Johannes Doerfertf61df692015-10-04 14:56:08 +00001195 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001196 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001197
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001198 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001199 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001200 while (R != &Context.CurRegion && !R->contains(L))
1201 R = R->getParent();
1202
1203 if (addOverApproximatedRegion(R, Context))
1204 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001205 }
Tobias Grosser75805372011-04-29 06:27:02 +00001206
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001207 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001208 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001209}
1210
Tobias Grosserc80d6972016-09-02 06:33:33 +00001211/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001212/// count that is not known to be less than @MinProfitableTrips.
1213ScopDetection::LoopStats
1214ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001215 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001216 auto *TripCount = SE.getBackedgeTakenCount(L);
1217
Tobias Grosserb45ae562016-11-26 07:37:46 +00001218 int NumLoops = 1;
1219 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001220 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001221 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001222 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1223 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001224
Tobias Grosserb45ae562016-11-26 07:37:46 +00001225 for (auto &SubLoop : *L) {
1226 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1227 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001228 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001229 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001230
Tobias Grosserb45ae562016-11-26 07:37:46 +00001231 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001232}
1233
Tobias Grosserb45ae562016-11-26 07:37:46 +00001234ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001235ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1236 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001237 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001238 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001239
Tobias Grossercd01a362017-02-17 08:12:36 +00001240 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001241 L = L ? R->outermostLoopInRegion(L) : nullptr;
1242 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001243
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001244 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001245 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001246
1247 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001248 if (R->contains(SubLoop)) {
1249 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001250 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001251 LoopNum += Stats.NumLoops;
1252 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1253 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001254
Tobias Grosserb45ae562016-11-26 07:37:46 +00001255 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001256}
1257
Tobias Grosser75805372011-04-29 06:27:02 +00001258Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001259 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001260 std::unique_ptr<Region> LastValidRegion;
1261 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001262
1263 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1264
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001265 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001266 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001267 getBBPairForRegion(ExpandedRegion.get()),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001268 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001269 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001270 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001271 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001272
Johannes Doerfert717b8662015-09-08 21:44:27 +00001273 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001274 // If the exit is valid check all blocks
1275 // - if true, a valid region was found => store it + keep expanding
1276 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001277 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1278 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001279 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001280 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001281 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001282
Tobias Grosserd7e58642013-04-10 06:55:45 +00001283 // Store this region, because it is the greatest valid (encountered so
1284 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001285 if (LastValidRegion) {
1286 removeCachedResults(*LastValidRegion);
1287 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1288 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001289 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001290
1291 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001292 ExpandedRegion =
1293 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001294
1295 } else {
1296 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001297 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001298 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001299 ExpandedRegion =
1300 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001301 }
Tobias Grosser75805372011-04-29 06:27:02 +00001302 }
1303
Tobias Grosser378a9f22013-11-16 19:34:11 +00001304 DEBUG({
1305 if (LastValidRegion)
1306 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1307 else
1308 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1309 });
Tobias Grosser75805372011-04-29 06:27:02 +00001310
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001311 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001312}
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001313static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001314 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001315 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001316 return false;
1317
1318 return true;
1319}
Tobias Grosser75805372011-04-29 06:27:02 +00001320
Tobias Grosserb45ae562016-11-26 07:37:46 +00001321void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001322 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001323 if (ValidRegions.count(SubRegion.get())) {
1324 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001325 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001326 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001327 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001328}
1329
Johannes Doerferte46925f2015-10-01 10:59:14 +00001330void ScopDetection::removeCachedResults(const Region &R) {
1331 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001332}
1333
Tobias Grosser75805372011-04-29 06:27:02 +00001334void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001335 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001336 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001337 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001338
1339 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001340 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001341 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001342 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001343 RegionIsValid = isValidRegion(Context);
1344
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001345 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001346
Johannes Doerferte46925f2015-10-01 10:59:14 +00001347 if (HasErrors) {
1348 removeCachedResults(R);
1349 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001350 ValidRegions.insert(&R);
1351 return;
1352 }
1353
David Blaikieb035f6d2014-04-15 18:45:27 +00001354 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001355 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001356
1357 // Try to expand regions.
1358 //
1359 // As the region tree normally only contains canonical regions, non canonical
1360 // regions that form a Scop are not found. Therefore, those non canonical
1361 // regions are checked by expanding the canonical ones.
1362
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001363 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001364
David Blaikieb035f6d2014-04-15 18:45:27 +00001365 for (auto &SubRegion : R)
1366 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001367
Tobias Grosser26108892014-04-02 20:18:19 +00001368 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001369 // Skip invalid regions. Regions may become invalid, if they are element of
1370 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001371 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001372 continue;
1373
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001374 // Skip regions that had errors.
1375 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1376 if (HadErrors)
1377 continue;
1378
Tobias Grosser75805372011-04-29 06:27:02 +00001379 Region *ExpandedR = expandRegion(*CurrentRegion);
1380
1381 if (!ExpandedR)
1382 continue;
1383
1384 R.addSubRegion(ExpandedR, true);
1385 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001386 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001387 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001388 }
1389}
1390
1391bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001392 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001393
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001394 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001395 Loop *L = LI.getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001396 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1397 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001398 return false;
1399 }
1400
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001401 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001402 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001403
1404 // Also check exception blocks (and possibly register them as non-affine
1405 // regions). Even though exception blocks are not modeled, we use them
1406 // to forward-propagate domain constraints during ScopInfo construction.
1407 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1408 return false;
1409
1410 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001411 continue;
1412
Tobias Grosser1d191902014-03-03 13:13:55 +00001413 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001414 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001415 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001416 }
Tobias Grosser75805372011-04-29 06:27:02 +00001417
Sebastian Pope8863b82014-05-12 19:02:02 +00001418 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001419 return false;
1420
Tobias Grosser75805372011-04-29 06:27:02 +00001421 return true;
1422}
1423
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001424bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1425 int NumLoops) const {
1426 int InstCount = 0;
1427
Tobias Grosserb316dc12016-09-08 14:08:05 +00001428 if (NumLoops == 0)
1429 return false;
1430
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001431 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001432 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001433 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001434
1435 InstCount = InstCount / NumLoops;
1436
1437 return InstCount >= ProfitabilityMinPerLoopInstructions;
1438}
1439
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001440bool ScopDetection::hasPossiblyDistributableLoop(
1441 DetectionContext &Context) const {
1442 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001443 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001444 if (!Context.CurRegion.contains(L))
1445 continue;
1446 if (Context.BoxedLoopsSet.count(L))
1447 continue;
1448 unsigned StmtsWithStoresInLoops = 0;
1449 for (auto *LBB : L->blocks()) {
1450 bool MemStore = false;
1451 for (auto &I : *LBB)
1452 MemStore |= isa<StoreInst>(&I);
1453 StmtsWithStoresInLoops += MemStore;
1454 }
1455 return (StmtsWithStoresInLoops > 1);
1456 }
1457 return false;
1458}
1459
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001460bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1461 Region &CurRegion = Context.CurRegion;
1462
1463 if (PollyProcessUnprofitable)
1464 return true;
1465
1466 // We can probably not do a lot on scops that only write or only read
1467 // data.
1468 if (!Context.hasStores || !Context.hasLoads)
1469 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1470
Tobias Grossercd01a362017-02-17 08:12:36 +00001471 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001472 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001473 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001474
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001475 // Scops with at least two loops may allow either loop fusion or tiling and
1476 // are consequently interesting to look at.
1477 if (NumAffineLoops >= 2)
1478 return true;
1479
Michael Krusea6d48f52017-06-08 12:06:15 +00001480 // A loop with multiple non-trivial blocks might be amendable to distribution.
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001481 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1482 return true;
1483
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001484 // Scops that contain a loop with a non-trivial amount of computation per
1485 // loop-iteration are interesting as we may be able to parallelize such
1486 // loops. Individual loops that have only a small amount of computation
1487 // per-iteration are performance-wise very fragile as any change to the
1488 // loop induction variables may affect performance. To not cause spurious
1489 // performance regressions, we do not consider such loops.
1490 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1491 return true;
1492
1493 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001494}
1495
Tobias Grosser75805372011-04-29 06:27:02 +00001496bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001497 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001498
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001499 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001500
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001501 if (!AllowFullFunction && CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001502 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001503 return false;
1504 }
1505
Tobias Grosser134a5722017-03-07 15:50:43 +00001506 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001507 if (CurRegion.getExit() &&
1508 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Tobias Grosser134a5722017-03-07 15:50:43 +00001509 DEBUG(dbgs() << "Unreachable in exit\n");
1510 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1511 CurRegion.getExit(), DbgLoc);
1512 }
1513
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001514 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001515 DEBUG({
1516 dbgs() << "Region entry does not match -polly-region-only";
1517 dbgs() << "\n";
1518 });
1519 return false;
1520 }
1521
Tobias Grosserd654c252012-04-10 18:12:19 +00001522 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001523 // to insert alloca instruction there when translate scalar to array.
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001524 if (!AllowFullFunction &&
1525 CurRegion.getEntry() ==
1526 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001527 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001528
Hongbin Zheng94868e62012-04-07 12:29:17 +00001529 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001530 return false;
1531
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001532 if (!isReducibleRegion(CurRegion, DbgLoc))
1533 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1534 &CurRegion, DbgLoc);
1535
Tobias Grosser75805372011-04-29 06:27:02 +00001536 DEBUG(dbgs() << "OK\n");
1537 return true;
1538}
1539
Tobias Grosser629109b2016-08-03 12:00:07 +00001540void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001541 F->addFnAttr(PollySkipFnAttr);
1542}
1543
Tobias Grosser75805372011-04-29 06:27:02 +00001544bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001545 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001546}
1547
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001548void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001549 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001550 unsigned LineEntry, LineExit;
1551 std::string FileName;
1552
Tobias Grosser00dc3092014-03-02 12:02:46 +00001553 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001554 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1555 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001556 }
1557}
1558
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001559void ScopDetection::emitMissedRemarks(const Function &F) {
1560 for (auto &DIt : DetectionContextMap) {
1561 auto &DC = DIt.getSecond();
1562 if (DC.Log.hasErrors())
1563 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001564 }
1565}
1566
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001567bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001568 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001569 ///
1570 /// WHITE - Unvisited BB in DFS walk.
1571 /// GREY - BBs which are currently on the DFS stack for processing.
1572 /// BLACK - Visited and completely processed BB.
1573 enum Color { WHITE, GREY, BLACK };
1574
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001575 BasicBlock *REntry = R.getEntry();
1576 BasicBlock *RExit = R.getExit();
1577 // Map to match the color of a BasicBlock during the DFS walk.
1578 DenseMap<const BasicBlock *, Color> BBColorMap;
1579 // Stack keeping track of current BB and index of next child to be processed.
1580 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1581
1582 unsigned AdjacentBlockIndex = 0;
1583 BasicBlock *CurrBB, *SuccBB;
1584 CurrBB = REntry;
1585
1586 // Initialize the map for all BB with WHITE color.
1587 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001588 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001589
1590 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001591 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001592 DFSStack.push(std::make_pair(CurrBB, 0));
1593
1594 while (!DFSStack.empty()) {
1595 // Get next BB on stack to be processed.
1596 CurrBB = DFSStack.top().first;
1597 AdjacentBlockIndex = DFSStack.top().second;
1598 DFSStack.pop();
1599
1600 // Loop to iterate over the successors of current BB.
1601 const TerminatorInst *TInst = CurrBB->getTerminator();
1602 unsigned NSucc = TInst->getNumSuccessors();
1603 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1604 ++I, ++AdjacentBlockIndex) {
1605 SuccBB = TInst->getSuccessor(I);
1606
1607 // Checks for region exit block and self-loops in BB.
1608 if (SuccBB == RExit || SuccBB == CurrBB)
1609 continue;
1610
1611 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001612 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001613 // Push the current BB and the index of the next child to be visited.
1614 DFSStack.push(std::make_pair(CurrBB, I + 1));
1615 // Push the next BB to be processed.
1616 DFSStack.push(std::make_pair(SuccBB, 0));
1617 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001618 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001619 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001620 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001621 // GREY indicates a loop in the control flow.
1622 // If the destination dominates the source, it is a natural loop
1623 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001624 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001625 // Get debug info of instruction which causes irregular control flow.
1626 DbgLoc = TInst->getDebugLoc();
1627 return false;
1628 }
1629 }
1630 }
1631
1632 // If all children of current BB have been processed,
1633 // then mark that BB as fully processed.
1634 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001635 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001636 }
1637
1638 return true;
1639}
1640
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001641static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1642 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001643 if (!OnlyProfitable) {
1644 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001645 MaxNumLoopsInScop =
1646 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001647 if (Stats.MaxDepth == 1)
1648 NumScopsDepthOne++;
1649 else if (Stats.MaxDepth == 2)
1650 NumScopsDepthTwo++;
1651 else if (Stats.MaxDepth == 3)
1652 NumScopsDepthThree++;
1653 else if (Stats.MaxDepth == 4)
1654 NumScopsDepthFour++;
1655 else if (Stats.MaxDepth == 5)
1656 NumScopsDepthFive++;
1657 else
1658 NumScopsDepthLarger++;
1659 } else {
1660 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001661 MaxNumLoopsInProfScop =
1662 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001663 if (Stats.MaxDepth == 1)
1664 NumProfScopsDepthOne++;
1665 else if (Stats.MaxDepth == 2)
1666 NumProfScopsDepthTwo++;
1667 else if (Stats.MaxDepth == 3)
1668 NumProfScopsDepthThree++;
1669 else if (Stats.MaxDepth == 4)
1670 NumProfScopsDepthFour++;
1671 else if (Stats.MaxDepth == 5)
1672 NumProfScopsDepthFive++;
1673 else
1674 NumProfScopsDepthLarger++;
1675 }
1676}
1677
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001678ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001679ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001680 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001681 if (DCMIt == DetectionContextMap.end())
1682 return nullptr;
1683 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001684}
1685
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001686const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1687 const DetectionContext *DC = getDetectionContext(R);
1688 return DC ? &DC->Log : nullptr;
1689}
1690
Tobias Grosser75805372011-04-29 06:27:02 +00001691void polly::ScopDetection::verifyRegion(const Region &R) const {
1692 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001693
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001694 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001695 isValidRegion(Context);
1696}
1697
1698void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001699 if (!VerifyScops)
1700 return;
1701
Tobias Grosser26108892014-04-02 20:18:19 +00001702 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001703 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001704}
1705
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001706bool ScopDetectionWrapperPass::runOnFunction(llvm::Function &F) {
1707 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1708 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1709 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1710 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1711 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1712 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA));
1713 return false;
1714}
1715
1716void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001717 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001718 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001719 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001720 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001721 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001722 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001723 AU.setPreservesAll();
1724}
1725
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001726void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1727 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001728 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001729
1730 OS << "\n";
1731}
1732
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001733ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1734 // Disable runtime alias checks if we ignore aliasing all together.
1735 if (IgnoreAliasing)
1736 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001737}
1738
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001739void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001740
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001741char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001742
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001743AnalysisKey ScopAnalysis::Key;
1744
1745ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1746 auto &LI = FAM.getResult<LoopAnalysis>(F);
1747 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1748 auto &AA = FAM.getResult<AAManager>(F);
1749 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1750 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1751 return {F, DT, SE, LI, RI, AA};
1752}
1753
1754PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1755 FunctionAnalysisManager &FAM) {
1756 auto &SD = FAM.getResult<ScopAnalysis>(F);
1757 for (const Region *R : SD.ValidRegions)
1758 Stream << "Valid Region for Scop: " << R->getNameStr() << '\n';
1759
1760 Stream << "\n";
1761 return PreservedAnalyses::all();
1762}
1763
1764Pass *polly::createScopDetectionWrapperPassPass() {
1765 return new ScopDetectionWrapperPass();
1766}
1767
1768INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001769 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001770 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001771INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001772INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001773INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001774INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001775INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001776INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001777 "Polly - Detect static control parts (SCoPs)", false, false)