blob: b8df3940a247e711b8e2c45fbf7ea9e8aa6026ca [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- ScopDetection.cpp - Detect Scops --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
16// Every Scop fullfills these restrictions:
17//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000050#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +000056#include "llvm/Analysis/Loads.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000059#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000060#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000061#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000062#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000064#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000065#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000066#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000068#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000069
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosserc1a269b2015-12-21 21:00:43 +000075// This option is set to a very high value, as analyzing such loops increases
76// compile time on several cases. For experiments that enable this option,
77// a value of around 40 has been working to avoid run-time regressions with
78// Polly while still exposing interesting optimization opportunities.
79static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80 "polly-detect-profitability-min-per-loop-insts",
81 cl::desc("The minimal number of per-loop instructions before a single loop "
82 "region is considered profitable"),
83 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84
Tobias Grosser575aca82015-10-06 16:10:29 +000085bool polly::PollyProcessUnprofitable;
86static cl::opt<bool, true> XPollyProcessUnprofitable(
87 "polly-process-unprofitable",
88 cl::desc(
89 "Process scops that are unlikely to benefit from Polly optimizations."),
90 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000092
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyFunction(
94 "polly-only-func",
95 cl::desc("Only run on functions that contain a certain string"),
96 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000098
Tobias Grosser483a90d2014-07-09 10:50:10 +000099static cl::opt<std::string> OnlyRegion(
100 "polly-only-region",
101 cl::desc("Only run on certain regions (The provided identifier must "
102 "appear in the name of the region's entry block"),
103 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
104 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000105
Tobias Grosser60cd9322011-11-10 12:47:26 +0000106static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 IgnoreAliasing("polly-ignore-aliasing",
108 cl::desc("Ignore possible aliasing of the array bases"),
109 cl::Hidden, cl::init(false), cl::ZeroOrMore,
110 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000111
Johannes Doerfertbda81432016-12-02 17:55:41 +0000112bool polly::PollyAllowUnsignedOperations;
113static cl::opt<bool, true> XPollyAllowUnsignedOperations(
114 "polly-allow-unsigned-operations",
115 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
116 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Johannes Doerfertb164c792014-09-18 11:17:17 +0000119bool polly::PollyUseRuntimeAliasChecks;
120static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
121 "polly-use-runtime-alias-checks",
122 cl::desc("Use runtime alias checks to resolve possible aliasing."),
123 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
124 cl::init(true), cl::cat(PollyCategory));
125
Tobias Grosser637bd632013-05-07 07:31:10 +0000126static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000127 ReportLevel("polly-report",
128 cl::desc("Print information about the activities of Polly"),
129 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000130
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000131static cl::opt<bool> AllowDifferentTypes(
132 "polly-allow-differing-element-types",
133 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000134 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000135
Tobias Grosser531891e2012-11-01 16:45:20 +0000136static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000137 AllowNonAffine("polly-allow-nonaffine",
138 cl::desc("Allow non affine access functions in arrays"),
139 cl::Hidden, cl::init(false), cl::ZeroOrMore,
140 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000141
Tobias Grosser898a6362016-03-23 06:40:15 +0000142static cl::opt<bool>
143 AllowModrefCall("polly-allow-modref-calls",
144 cl::desc("Allow functions with known modref behavior"),
145 cl::Hidden, cl::init(false), cl::ZeroOrMore,
146 cl::cat(PollyCategory));
147
Johannes Doerfertba65c162015-02-24 11:45:21 +0000148static cl::opt<bool> AllowNonAffineSubRegions(
149 "polly-allow-nonaffine-branches",
150 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000151 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000152
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000153static cl::opt<bool>
154 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
155 cl::desc("Allow non affine conditions for loops"),
156 cl::Hidden, cl::init(false), cl::ZeroOrMore,
157 cl::cat(PollyCategory));
158
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000159static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000160 TrackFailures("polly-detect-track-failures",
161 cl::desc("Track failure strings in detecting scop regions"),
162 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000163 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000164
Andreas Simbuerger04472402014-05-24 09:25:10 +0000165static cl::opt<bool> KeepGoing("polly-detect-keep-going",
166 cl::desc("Do not fail on the first error."),
167 cl::Hidden, cl::ZeroOrMore, cl::init(false),
168 cl::cat(PollyCategory));
169
Sebastian Pop18016682014-04-08 21:20:44 +0000170static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000171 PollyDelinearizeX("polly-delinearize",
172 cl::desc("Delinearize array access functions"),
173 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000174 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000175
Tobias Grossera1689932014-02-18 18:49:49 +0000176static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000177 VerifyScops("polly-detect-verify",
178 cl::desc("Verify the detected SCoPs after each transformation"),
179 cl::Hidden, cl::init(false), cl::ZeroOrMore,
180 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000181
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000182bool polly::PollyInvariantLoadHoisting;
183static cl::opt<bool, true> XPollyInvariantLoadHoisting(
184 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
185 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000186 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000187
Tobias Grosserc80d6972016-09-02 06:33:33 +0000188/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000189static const unsigned MIN_LOOP_TRIP_COUNT = 8;
190
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000191bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000192bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000193StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000194
Tobias Grosser75805372011-04-29 06:27:02 +0000195//===----------------------------------------------------------------------===//
196// Statistics.
197
Tobias Grosserb45ae562016-11-26 07:37:46 +0000198STATISTIC(NumScopRegions, "Number of scops");
199STATISTIC(NumLoopsInScop, "Number of loops in scops");
200STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
201STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
202STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
203STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
204STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
205STATISTIC(NumScopsDepthLarger,
206 "Number of scops with maximal loop depth 6 and larger");
207STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
208STATISTIC(NumLoopsInProfScop,
209 "Number of loops in scops (profitable scops only)");
210STATISTIC(NumLoopsOverall, "Number of total loops");
211STATISTIC(NumProfScopsDepthOne,
212 "Number of scops with maximal loop depth 1 (profitable scops only)");
213STATISTIC(NumProfScopsDepthTwo,
214 "Number of scops with maximal loop depth 2 (profitable scops only)");
215STATISTIC(NumProfScopsDepthThree,
216 "Number of scops with maximal loop depth 3 (profitable scops only)");
217STATISTIC(NumProfScopsDepthFour,
218 "Number of scops with maximal loop depth 4 (profitable scops only)");
219STATISTIC(NumProfScopsDepthFive,
220 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000221STATISTIC(NumProfScopsDepthLarger,
222 "Number of scops with maximal loop depth 6 and larger "
223 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000224STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
225STATISTIC(MaxNumLoopsInProfScop,
226 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000227
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000228static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
229 bool OnlyProfitable);
230
Tobias Grosser8519f892013-12-18 10:49:53 +0000231class DiagnosticScopFound : public DiagnosticInfo {
232private:
233 static int PluginDiagnosticKind;
234
235 Function &F;
236 std::string FileName;
237 unsigned EntryLine, ExitLine;
238
239public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000240 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
241 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000242 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000243 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000244
245 virtual void print(DiagnosticPrinter &DP) const;
246
247 static bool classof(const DiagnosticInfo *DI) {
248 return DI->getKind() == PluginDiagnosticKind;
249 }
250};
251
Tobias Grosserdb6db502016-04-01 07:15:19 +0000252int DiagnosticScopFound::PluginDiagnosticKind =
253 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000254
Tobias Grosser8519f892013-12-18 10:49:53 +0000255void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000256 DP << "Polly detected an optimizable loop region (scop) in function '" << F
257 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000258
259 if (FileName.empty()) {
260 DP << "Scop location is unknown. Compile with debug info "
261 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000262 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000263 }
264
265 DP << FileName << ":" << EntryLine << ": Start of scop\n";
266 DP << FileName << ":" << ExitLine << ": End of scop";
267}
268
Tobias Grosser75805372011-04-29 06:27:02 +0000269//===----------------------------------------------------------------------===//
270// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000271
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000272ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
273 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
274 AliasAnalysis &AA)
275 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA) {
276
277 if (!PollyProcessUnprofitable && LI.empty())
278 return;
279
280 Region *TopRegion = RI.getTopLevelRegion();
281
282 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
283 return;
284
285 if (!isValidFunction(F))
286 return;
287
288 findScops(*TopRegion);
289
290 NumScopRegions += ValidRegions.size();
291
292 // Prune non-profitable regions.
293 for (auto &DIt : DetectionContextMap) {
294 auto &DC = DIt.getSecond();
295 if (DC.Log.hasErrors())
296 continue;
297 if (!ValidRegions.count(&DC.CurRegion))
298 continue;
299 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
300 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
301 if (isProfitableRegion(DC)) {
302 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
303 continue;
304 }
305
306 ValidRegions.remove(&DC.CurRegion);
307 }
308
309 NumProfScopRegions += ValidRegions.size();
310 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
311
312 // Only makes sense when we tracked errors.
313 if (PollyTrackFailures)
314 emitMissedRemarks(F);
315
316 if (ReportLevel)
317 printLocations(F);
318
319 assert(ValidRegions.size() <= DetectionContextMap.size() &&
320 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000321}
322
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000323template <class RR, typename... Args>
324inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
325 Args &&... Arguments) const {
326
327 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000328 RejectLog &Log = Context.Log;
329 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000330
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000331 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000332 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000333
334 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000335 DEBUG(dbgs() << "\n");
336 } else {
337 assert(!Assert && "Verification of detected scop failed");
338 }
339
340 return false;
341}
342
Tobias Grossera1689932014-02-18 18:49:49 +0000343bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
344 if (!ValidRegions.count(&R))
345 return false;
346
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000347 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000348 DetectionContextMap.erase(getBBPairForRegion(&R));
349 const auto &It = DetectionContextMap.insert(std::make_pair(
350 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000351 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000352 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000353 return isValidRegion(Context);
354 }
Tobias Grossera1689932014-02-18 18:49:49 +0000355
356 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000357}
358
Tobias Grosser4f129a62011-10-08 00:30:55 +0000359std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000360 // Get the first error we found. Even in keep-going mode, this is the first
361 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000362 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000363
364 // This can happen when we marked a region invalid, but didn't track
365 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000366 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000367 return "";
368
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000369 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000370 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000371}
372
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000373bool ScopDetection::addOverApproximatedRegion(Region *AR,
374 DetectionContext &Context) const {
375
376 // If we already know about Ar we can exit.
377 if (!Context.NonAffineSubRegionSet.insert(AR))
378 return true;
379
380 // All loops in the region have to be overapproximated too if there
381 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000382
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000383 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000384 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000385 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000386 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000387 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000388
389 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000390}
391
Johannes Doerfert09e36972015-10-07 20:17:36 +0000392bool ScopDetection::onlyValidRequiredInvariantLoads(
393 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
394 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000395 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000396
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000397 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
398 return false;
399
Tobias Grosser1c787e02017-03-02 12:15:37 +0000400 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000401 // If we already know a load has been accepted as required invariant, we
402 // already run the validation below once and consequently don't need to
403 // run it again. Hence, we return early. For certain test cases (e.g.,
404 // COSMO this avoids us spending 50% of scop-detection time in this
405 // very function (and its children).
406 if (Context.RequiredILS.count(Load))
407 continue;
408
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000409 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000410 return false;
411
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000412 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
413
414 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
415 Load->getAlignment(), DL))
416 continue;
417
Tobias Grosser1c787e02017-03-02 12:15:37 +0000418 if (NonAffineRegion->contains(Load) &&
419 Load->getParent() != NonAffineRegion->getEntry())
420 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000421 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000422 }
423
Johannes Doerfert09e36972015-10-07 20:17:36 +0000424 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
425
426 return true;
427}
428
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000429bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
430 Loop *Scope) const {
431 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000432 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000433 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000434 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000435
436 SmallPtrSet<Value *, 8> PtrVals;
437 for (auto *V : Values) {
438 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
439 V = P2I->getOperand(0);
440
441 if (!V->getType()->isPointerTy())
442 continue;
443
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000444 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000445 if (isa<SCEVConstant>(PtrSCEV))
446 continue;
447
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000448 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000449 if (!BasePtr)
450 return true;
451
452 auto *BasePtrVal = BasePtr->getValue();
453 if (PtrVals.insert(BasePtrVal).second) {
454 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000455 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000456 return true;
457 }
458 }
459
460 return false;
461}
462
Michael Kruse09eb4452016-03-03 22:10:47 +0000463bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000464 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000465
466 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000467 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000468 return false;
469
470 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
471 return false;
472
473 return true;
474}
475
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000476bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000477 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000478 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000479 Loop *L = LI.getLoopFor(&BB);
480 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000481
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000482 if (IsLoopBranch && L->isLoopLatch(&BB))
483 return false;
484
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000485 // Check for invalid usage of different pointers in one expression.
486 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
487 return false;
488
Michael Kruse09eb4452016-03-03 22:10:47 +0000489 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000490 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000491
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000492 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000493 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000494 return true;
495
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000496 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
497 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000498}
499
500bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000501 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000502 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000503
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000504 // Constant integer conditions are always affine.
505 if (isa<ConstantInt>(Condition))
506 return true;
507
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000508 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
509 auto Opcode = BinOp->getOpcode();
510 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
511 Value *Op0 = BinOp->getOperand(0);
512 Value *Op1 = BinOp->getOperand(1);
513 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
514 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
515 }
516 }
517
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000518 // Non constant conditions of branches need to be ICmpInst.
519 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000520 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000521 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000522 return true;
523 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000524 }
Tobias Grosser75805372011-04-29 06:27:02 +0000525
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000526 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000527
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000528 // Are both operands of the ICmp affine?
529 if (isa<UndefValue>(ICmp->getOperand(0)) ||
530 isa<UndefValue>(ICmp->getOperand(1)))
531 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000532
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000533 Loop *L = LI.getLoopFor(&BB);
534 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
535 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000536
Johannes Doerfertbda81432016-12-02 17:55:41 +0000537 // If unsigned operations are not allowed try to approximate the region.
538 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
539 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000540 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000541
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000542 // Check for invalid usage of different pointers in one expression.
543 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
544 involvesMultiplePtrs(RHS, nullptr, L))
545 return false;
546
547 // Check for invalid usage of different pointers in a relational comparison.
548 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
549 return false;
550
Michael Kruse09eb4452016-03-03 22:10:47 +0000551 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000552 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000553
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000554 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000555 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000556 return true;
557
558 if (IsLoopBranch)
559 return false;
560
561 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
562 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000563}
564
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000565bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000566 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000567 DetectionContext &Context) const {
568 Region &CurRegion = Context.CurRegion;
569
570 TerminatorInst *TI = BB.getTerminator();
571
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000572 if (AllowUnreachable && isa<UnreachableInst>(TI))
573 return true;
574
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000575 // Return instructions are only valid if the region is the top level region.
576 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
577 return true;
578
579 Value *Condition = getConditionFromTerminator(TI);
580
581 if (!Condition)
582 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
583
584 // UndefValue is not allowed as condition.
585 if (isa<UndefValue>(Condition))
586 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
587
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000588 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000589 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000590
591 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
592 assert(SI && "Terminator was neither branch nor switch");
593
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000594 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000595}
596
Johannes Doerfertcea61932016-02-21 19:13:19 +0000597bool ScopDetection::isValidCallInst(CallInst &CI,
598 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000599 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000600 return false;
601
602 if (CI.doesNotAccessMemory())
603 return true;
604
Johannes Doerfertcea61932016-02-21 19:13:19 +0000605 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000606 if (isValidIntrinsicInst(*II, Context))
607 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000608
Tobias Grosser75805372011-04-29 06:27:02 +0000609 Function *CalledFunction = CI.getCalledFunction();
610
611 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000612 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000613 return false;
614
Tobias Grosser898a6362016-03-23 06:40:15 +0000615 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000616 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000617 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000618 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000619 case FMRB_DoesNotAccessMemory:
620 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000621 // Implicitly disable delinearization since we have an unknown
622 // accesses with an unknown access function.
623 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000624 Context.AST.add(&CI);
625 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000626 case FMRB_OnlyReadsArgumentPointees:
627 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000628 for (const auto &Arg : CI.arg_operands()) {
629 if (!Arg->getType()->isPointerTy())
630 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000631
Tobias Grosser898a6362016-03-23 06:40:15 +0000632 // Bail if a pointer argument has a base address not known to
633 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000634 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000635 if (ArgSCEV->isZero())
636 continue;
637
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000638 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000639 if (!BP)
640 return false;
641
642 // Implicitly disable delinearization since we have an unknown
643 // accesses with an unknown access function.
644 Context.HasUnknownAccess = true;
645 }
646
647 Context.AST.add(&CI);
648 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000649 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000650 case FMRB_OnlyAccessesInaccessibleMem:
651 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000652 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000653 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000654 }
655
Johannes Doerfertcea61932016-02-21 19:13:19 +0000656 return false;
657}
658
659bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
660 DetectionContext &Context) const {
661 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000662 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000663
Johannes Doerfertcea61932016-02-21 19:13:19 +0000664 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000665 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000666
667 // The access function and base pointer for memory intrinsics.
668 const SCEV *AF;
669 const SCEVUnknown *BP;
670
671 switch (II.getIntrinsicID()) {
672 // Memory intrinsics that can be represented are supported.
673 case llvm::Intrinsic::memmove:
674 case llvm::Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000675 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000676 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000677 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000678 // Bail if the source pointer is not valid.
679 if (!isValidAccess(&II, AF, BP, Context))
680 return false;
681 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000682 // Fall through
683 case llvm::Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000684 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000685 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000686 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000687 // Bail if the destination pointer is not valid.
688 if (!isValidAccess(&II, AF, BP, Context))
689 return false;
690 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000691
692 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000693 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000694 Context))
695 return false;
696
697 return true;
698 default:
699 break;
700 }
701
Tobias Grosser75805372011-04-29 06:27:02 +0000702 return false;
703}
704
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000705bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
706 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000707 // A reference to function argument or constant value is invariant.
708 if (isa<Argument>(Val) || isa<Constant>(Val))
709 return true;
710
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000711 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000712 if (!I)
713 return false;
714
715 if (!Reg.contains(I))
716 return true;
717
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000718 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
719 // is not hoistable, it will be rejected later, but here we assume it is and
720 // that makes the value invariant.
721 if (auto LI = dyn_cast<LoadInst>(I)) {
722 Ctx.RequiredILS.insert(LI);
723 return true;
724 }
725
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000726 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000727}
728
Tobias Grosserc80d6972016-09-02 06:33:33 +0000729/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000730/// register the '...' components.
731///
732/// Array access expressions as they are generated by gfortran contain smax(0,
733/// size) expressions that confuse the 'normal' delinearization algorithm.
734/// However, if we extract such expressions before the normal delinearization
735/// takes place they can actually help to identify array size expressions in
736/// fortran accesses. For the subsequently following delinearization the smax(0,
737/// size) component can be replaced by just 'size'. This is correct as we will
738/// always add and verify the assumption that for all subscript expressions
739/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
740/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000741class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000742public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000743 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
744 std::vector<const SCEV *> *Terms = nullptr) {
745 SCEVRemoveMax Rewriter(SE, Terms);
746 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000747 }
748
749 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000750 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000751
752 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000753 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000754 auto Res = visit(Expr->getOperand(1));
755 if (Terms)
756 (*Terms).push_back(Res);
757 return Res;
758 }
759
760 return Expr;
761 }
762
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000763private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000764 std::vector<const SCEV *> *Terms;
765};
766
Tobias Grosserd68ba422015-11-24 05:00:36 +0000767SmallVector<const SCEV *, 4>
768ScopDetection::getDelinearizationTerms(DetectionContext &Context,
769 const SCEVUnknown *BasePointer) const {
770 SmallVector<const SCEV *, 4> Terms;
771 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000772 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000773 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000774 if (MaxTerms.size() > 0) {
775 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
776 continue;
777 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000778 // In case the outermost expression is a plain add, we check if any of its
779 // terms has the form 4 * %inst * %param * %param ..., aka a term that
780 // contains a product between a parameter and an instruction that is
781 // inside the scop. Such instructions, if allowed at all, are instructions
782 // SCEV can not represent, but Polly is still looking through. As a
783 // result, these instructions can depend on induction variables and are
784 // most likely no array sizes. However, terms that are multiplied with
785 // them are likely candidates for array sizes.
786 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
787 for (auto Op : AF->operands()) {
788 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000789 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000790 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
791 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000792
Tobias Grosserd68ba422015-11-24 05:00:36 +0000793 for (auto *MulOp : AF2->operands()) {
794 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
795 Operands.push_back(Const);
796 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
797 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
798 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000799 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000800
801 } else {
802 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000803 }
804 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000805 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000806 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000807 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000808 }
809 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000810 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000811 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000812 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000813 }
814 return Terms;
815}
Sebastian Pope8863b82014-05-12 19:02:02 +0000816
Tobias Grosserd68ba422015-11-24 05:00:36 +0000817bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
818 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000819 const SCEVUnknown *BasePointer,
820 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000821 Value *BaseValue = BasePointer->getValue();
822 Region &CurRegion = Context.CurRegion;
823 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000824 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000825 Sizes.clear();
826 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000827 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000828 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
829 auto *V = dyn_cast<Value>(Unknown->getValue());
830 if (auto *Load = dyn_cast<LoadInst>(V)) {
831 if (Context.CurRegion.contains(Load) &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000832 isHoistableLoad(Load, CurRegion, LI, SE, DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000833 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000834 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000835 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000836 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000837 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000838 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000839 Context, /*Assert=*/true, DelinearizedSize,
840 Context.Accesses[BasePointer].front().first, BaseValue);
841 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000842
Tobias Grosserd68ba422015-11-24 05:00:36 +0000843 // No array shape derived.
844 if (Sizes.empty()) {
845 if (AllowNonAffine)
846 return true;
847
Tobias Grosser230acc42014-09-13 14:47:55 +0000848 for (const auto &Pair : Context.Accesses[BasePointer]) {
849 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000850 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000851
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000852 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000853 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
854 BaseValue);
855 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000856 return false;
857 }
858 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000859 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000860 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000861 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000862}
863
Tobias Grosserd68ba422015-11-24 05:00:36 +0000864// We first store the resulting memory accesses in TempMemoryAccesses. Only
865// if the access functions for all memory accesses have been successfully
866// delinearized we continue. Otherwise, we either report a failure or, if
867// non-affine accesses are allowed, we drop the information. In case the
868// information is dropped the memory accesses need to be overapproximated
869// when translated to a polyhedral representation.
870bool ScopDetection::computeAccessFunctions(
871 DetectionContext &Context, const SCEVUnknown *BasePointer,
872 std::shared_ptr<ArrayShape> Shape) const {
873 Value *BaseValue = BasePointer->getValue();
874 bool BasePtrHasNonAffine = false;
875 MapInsnToMemAcc TempMemoryAccesses;
876 for (const auto &Pair : Context.Accesses[BasePointer]) {
877 const Instruction *Insn = Pair.first;
878 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000879 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000880 bool IsNonAffine = false;
881 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
882 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000883 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000884
885 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000886 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000887 Acc->DelinearizedSubscripts.push_back(Pair.second);
888 else
889 IsNonAffine = true;
890 } else {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000891 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
892 Shape->DelinearizedSizes);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000893 if (Acc->DelinearizedSubscripts.size() == 0)
894 IsNonAffine = true;
895 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000896 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000897 IsNonAffine = true;
898 }
899
900 // (Possibly) report non affine access
901 if (IsNonAffine) {
902 BasePtrHasNonAffine = true;
903 if (!AllowNonAffine)
904 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
905 Insn, BaseValue);
906 if (!KeepGoing && !AllowNonAffine)
907 return false;
908 }
909 }
910
911 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000912 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
913 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000914
915 return true;
916}
917
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000918bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
919 const SCEVUnknown *BasePointer,
920 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000921 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
922
923 auto Terms = getDelinearizationTerms(Context, BasePointer);
924
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000925 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
926 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000927
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000928 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
929 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000930 return false;
931
932 return computeAccessFunctions(Context, BasePointer, Shape);
933}
934
935bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000936 // TODO: If we have an unknown access and other non-affine accesses we do
937 // not try to delinearize them for now.
938 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
939 return AllowNonAffine;
940
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000941 for (auto &Pair : Context.NonAffineAccesses) {
942 auto *BasePointer = Pair.first;
943 auto *Scope = Pair.second;
944 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000945 if (KeepGoing)
946 continue;
947 else
948 return false;
949 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000950 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000951 return true;
952}
953
Johannes Doerfertcea61932016-02-21 19:13:19 +0000954bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
955 const SCEVUnknown *BP,
956 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000957
Johannes Doerfertcea61932016-02-21 19:13:19 +0000958 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000959 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000960
Johannes Doerfertcea61932016-02-21 19:13:19 +0000961 auto *BV = BP->getValue();
962 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000963 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000964
Johannes Doerfertcea61932016-02-21 19:13:19 +0000965 // FIXME: Think about allowing IntToPtrInst
966 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
967 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
968
Tobias Grosser458fb782014-01-28 12:58:58 +0000969 // Check that the base address of the access is invariant in the current
970 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000971 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000972 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000973
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000974 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000975
Johannes Doerfertcea61932016-02-21 19:13:19 +0000976 const SCEV *Size;
977 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000978 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000979 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000980 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000981 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
982 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000983 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000984
Johannes Doerfertcea61932016-02-21 19:13:19 +0000985 if (Context.ElementSize[BP]) {
986 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
987 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
988 Inst, BV);
989
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000990 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000991 } else {
992 Context.ElementSize[BP] = Size;
993 }
994
995 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000996 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000997 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000998 for (const Loop *L : Loops)
999 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001000 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001001
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001002 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001003 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001004 // Do not try to delinearize memory intrinsics and force them to be affine.
1005 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1006 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1007 BV);
1008 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1009 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001010
Johannes Doerfertcea61932016-02-21 19:13:19 +00001011 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001012 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001013 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001014 } else if (!AllowNonAffine && !IsAffine) {
1015 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1016 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001017 }
Tobias Grosser75805372011-04-29 06:27:02 +00001018
Tobias Grosser1eedb672014-09-24 21:04:29 +00001019 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001020 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001021
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001022 // Check if the base pointer of the memory access does alias with
1023 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001024 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001025 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001026 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +00001027 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +00001028
Tobias Grosser1eedb672014-09-24 21:04:29 +00001029 if (!AS.isMustAlias()) {
1030 if (PollyUseRuntimeAliasChecks) {
1031 bool CanBuildRunTimeCheck = true;
1032 // The run-time alias check places code that involves the base pointer at
1033 // the beginning of the SCoP. This breaks if the base pointer is defined
1034 // inside the scop. Hence, we can only create a run-time check if we are
1035 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001036 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +00001037 for (const auto &Ptr : AS) {
1038 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001039 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001040 auto *Load = dyn_cast<LoadInst>(Inst);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001041 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001042 Context.RequiredILS.insert(Load);
1043 continue;
1044 }
1045
Tobias Grosser1eedb672014-09-24 21:04:29 +00001046 CanBuildRunTimeCheck = false;
1047 break;
1048 }
1049 }
1050
1051 if (CanBuildRunTimeCheck)
1052 return true;
1053 }
Michael Kruse70131d32016-01-27 17:09:17 +00001054 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001055 }
Tobias Grosser75805372011-04-29 06:27:02 +00001056
1057 return true;
1058}
1059
Johannes Doerfertcea61932016-02-21 19:13:19 +00001060bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1061 DetectionContext &Context) const {
1062 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001063 Loop *L = LI.getLoopFor(Inst->getParent());
1064 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001065 const SCEVUnknown *BasePointer;
1066
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001067 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001068
1069 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1070}
1071
Tobias Grosser75805372011-04-29 06:27:02 +00001072bool ScopDetection::isValidInstruction(Instruction &Inst,
1073 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001074 for (auto &Op : Inst.operands()) {
1075 auto *OpInst = dyn_cast<Instruction>(&Op);
1076
1077 if (!OpInst)
1078 continue;
1079
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001080 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT))
Tobias Grosserb12b0062015-11-11 12:44:18 +00001081 return false;
1082 }
1083
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001084 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1085 return false;
1086
Tobias Grosser75805372011-04-29 06:27:02 +00001087 // We only check the call instruction but not invoke instruction.
1088 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001089 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001090 return true;
1091
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001092 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001093 }
1094
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001095 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001096 if (!isa<AllocaInst>(Inst))
1097 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001098
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001099 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001100 }
1101
1102 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001103 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001104 Context.hasStores |= isa<StoreInst>(MemInst);
1105 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001106 if (!MemInst.isSimple())
1107 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1108 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001109
Michael Kruse70131d32016-01-27 17:09:17 +00001110 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001111 }
Tobias Grosser75805372011-04-29 06:27:02 +00001112
1113 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001114 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001115}
1116
Tobias Grosser349d1c32016-09-20 17:05:22 +00001117/// Check whether @p L has exiting blocks.
1118///
1119/// @param L The loop of interest
1120///
1121/// @return True if the loop has exiting blocks, false otherwise.
1122static bool hasExitingBlocks(Loop *L) {
1123 SmallVector<BasicBlock *, 4> ExitingBlocks;
1124 L->getExitingBlocks(ExitingBlocks);
1125 return !ExitingBlocks.empty();
1126}
1127
Johannes Doerfertd020b772015-08-27 06:53:52 +00001128bool ScopDetection::canUseISLTripCount(Loop *L,
1129 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001130 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1131 // need to overapproximate it as a boxed loop.
1132 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001133 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001134 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001135 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001136 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001137 return false;
1138 }
1139
Johannes Doerfertd020b772015-08-27 06:53:52 +00001140 // We can use ISL to compute the trip count of L.
1141 return true;
1142}
1143
Tobias Grosser75805372011-04-29 06:27:02 +00001144bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001145 // Loops that contain part but not all of the blocks of a region cannot be
1146 // handled by the schedule generation. Such loop constructs can happen
1147 // because a region can contain BBs that have no path to the exit block
1148 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1149 // loop.
1150 //
1151 // _______________
1152 // | Loop Header | <-----------.
1153 // --------------- |
1154 // | |
1155 // _______________ ______________
1156 // | RegionEntry |-----> | RegionExit |----->
1157 // --------------- --------------
1158 // |
1159 // _______________
1160 // | EndlessLoop | <--.
1161 // --------------- |
1162 // | |
1163 // \------------/
1164 //
1165 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1166 // neither entirely contained in the region RegionEntry->RegionExit
1167 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1168 // in the loop.
1169 // The block EndlessLoop is contained in the region because Region::contains
1170 // tests whether it is not dominated by RegionExit. This is probably to not
1171 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1172 // end can also be formed by an UnreachableInst. This case is already caught
1173 // by isErrorBlock(). We hence only have to reject endless loops here.
1174 if (!hasExitingBlocks(L))
1175 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1176
Johannes Doerfertf61df692015-10-04 14:56:08 +00001177 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001178 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001179
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001180 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001181 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001182 while (R != &Context.CurRegion && !R->contains(L))
1183 R = R->getParent();
1184
1185 if (addOverApproximatedRegion(R, Context))
1186 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001187 }
Tobias Grosser75805372011-04-29 06:27:02 +00001188
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001189 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001190 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001191}
1192
Tobias Grosserc80d6972016-09-02 06:33:33 +00001193/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001194/// count that is not known to be less than @MinProfitableTrips.
1195ScopDetection::LoopStats
1196ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001197 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001198 auto *TripCount = SE.getBackedgeTakenCount(L);
1199
Tobias Grosserb45ae562016-11-26 07:37:46 +00001200 int NumLoops = 1;
1201 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001202 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001203 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001204 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1205 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001206
Tobias Grosserb45ae562016-11-26 07:37:46 +00001207 for (auto &SubLoop : *L) {
1208 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1209 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001210 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001211 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001212
Tobias Grosserb45ae562016-11-26 07:37:46 +00001213 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001214}
1215
Tobias Grosserb45ae562016-11-26 07:37:46 +00001216ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001217ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1218 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001219 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001220 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001221
Tobias Grossercd01a362017-02-17 08:12:36 +00001222 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001223 L = L ? R->outermostLoopInRegion(L) : nullptr;
1224 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001225
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001226 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001227 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001228
1229 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001230 if (R->contains(SubLoop)) {
1231 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001232 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001233 LoopNum += Stats.NumLoops;
1234 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1235 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001236
Tobias Grosserb45ae562016-11-26 07:37:46 +00001237 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001238}
1239
Tobias Grosser75805372011-04-29 06:27:02 +00001240Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001241 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001242 std::unique_ptr<Region> LastValidRegion;
1243 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001244
1245 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1246
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001247 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001248 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001249 getBBPairForRegion(ExpandedRegion.get()),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001250 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001251 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001252 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001253 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001254
Johannes Doerfert717b8662015-09-08 21:44:27 +00001255 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001256 // If the exit is valid check all blocks
1257 // - if true, a valid region was found => store it + keep expanding
1258 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001259 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1260 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001261 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001262 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001263 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001264
Tobias Grosserd7e58642013-04-10 06:55:45 +00001265 // Store this region, because it is the greatest valid (encountered so
1266 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001267 if (LastValidRegion) {
1268 removeCachedResults(*LastValidRegion);
1269 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1270 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001271 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001272
1273 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001274 ExpandedRegion =
1275 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001276
1277 } else {
1278 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001279 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001280 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001281 ExpandedRegion =
1282 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001283 }
Tobias Grosser75805372011-04-29 06:27:02 +00001284 }
1285
Tobias Grosser378a9f22013-11-16 19:34:11 +00001286 DEBUG({
1287 if (LastValidRegion)
1288 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1289 else
1290 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1291 });
Tobias Grosser75805372011-04-29 06:27:02 +00001292
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001293 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001294}
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001295static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001296 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001297 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001298 return false;
1299
1300 return true;
1301}
Tobias Grosser75805372011-04-29 06:27:02 +00001302
Tobias Grosserb45ae562016-11-26 07:37:46 +00001303void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001304 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001305 if (ValidRegions.count(SubRegion.get())) {
1306 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001307 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001308 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001309 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001310}
1311
Johannes Doerferte46925f2015-10-01 10:59:14 +00001312void ScopDetection::removeCachedResults(const Region &R) {
1313 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001314}
1315
Tobias Grosser75805372011-04-29 06:27:02 +00001316void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001317 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001318 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001319 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001320
1321 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001322 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001323 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001324 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001325 RegionIsValid = isValidRegion(Context);
1326
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001327 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001328
Johannes Doerferte46925f2015-10-01 10:59:14 +00001329 if (HasErrors) {
1330 removeCachedResults(R);
1331 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001332 ValidRegions.insert(&R);
1333 return;
1334 }
1335
David Blaikieb035f6d2014-04-15 18:45:27 +00001336 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001337 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001338
1339 // Try to expand regions.
1340 //
1341 // As the region tree normally only contains canonical regions, non canonical
1342 // regions that form a Scop are not found. Therefore, those non canonical
1343 // regions are checked by expanding the canonical ones.
1344
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001345 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001346
David Blaikieb035f6d2014-04-15 18:45:27 +00001347 for (auto &SubRegion : R)
1348 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001349
Tobias Grosser26108892014-04-02 20:18:19 +00001350 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001351 // Skip invalid regions. Regions may become invalid, if they are element of
1352 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001353 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001354 continue;
1355
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001356 // Skip regions that had errors.
1357 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1358 if (HadErrors)
1359 continue;
1360
Tobias Grosser75805372011-04-29 06:27:02 +00001361 Region *ExpandedR = expandRegion(*CurrentRegion);
1362
1363 if (!ExpandedR)
1364 continue;
1365
1366 R.addSubRegion(ExpandedR, true);
1367 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001368 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001369 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001370 }
1371}
1372
1373bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001374 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001375
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001376 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001377 Loop *L = LI.getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001378 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1379 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001380 return false;
1381 }
1382
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001383 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001384 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001385
1386 // Also check exception blocks (and possibly register them as non-affine
1387 // regions). Even though exception blocks are not modeled, we use them
1388 // to forward-propagate domain constraints during ScopInfo construction.
1389 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1390 return false;
1391
1392 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001393 continue;
1394
Tobias Grosser1d191902014-03-03 13:13:55 +00001395 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001396 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001397 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001398 }
Tobias Grosser75805372011-04-29 06:27:02 +00001399
Sebastian Pope8863b82014-05-12 19:02:02 +00001400 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001401 return false;
1402
Tobias Grosser75805372011-04-29 06:27:02 +00001403 return true;
1404}
1405
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001406bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1407 int NumLoops) const {
1408 int InstCount = 0;
1409
Tobias Grosserb316dc12016-09-08 14:08:05 +00001410 if (NumLoops == 0)
1411 return false;
1412
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001413 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001414 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001415 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001416
1417 InstCount = InstCount / NumLoops;
1418
1419 return InstCount >= ProfitabilityMinPerLoopInstructions;
1420}
1421
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001422bool ScopDetection::hasPossiblyDistributableLoop(
1423 DetectionContext &Context) const {
1424 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001425 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001426 if (!Context.CurRegion.contains(L))
1427 continue;
1428 if (Context.BoxedLoopsSet.count(L))
1429 continue;
1430 unsigned StmtsWithStoresInLoops = 0;
1431 for (auto *LBB : L->blocks()) {
1432 bool MemStore = false;
1433 for (auto &I : *LBB)
1434 MemStore |= isa<StoreInst>(&I);
1435 StmtsWithStoresInLoops += MemStore;
1436 }
1437 return (StmtsWithStoresInLoops > 1);
1438 }
1439 return false;
1440}
1441
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001442bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1443 Region &CurRegion = Context.CurRegion;
1444
1445 if (PollyProcessUnprofitable)
1446 return true;
1447
1448 // We can probably not do a lot on scops that only write or only read
1449 // data.
1450 if (!Context.hasStores || !Context.hasLoads)
1451 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1452
Tobias Grossercd01a362017-02-17 08:12:36 +00001453 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001454 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001455 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001456
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001457 // Scops with at least two loops may allow either loop fusion or tiling and
1458 // are consequently interesting to look at.
1459 if (NumAffineLoops >= 2)
1460 return true;
1461
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001462 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1463 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1464 return true;
1465
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001466 // Scops that contain a loop with a non-trivial amount of computation per
1467 // loop-iteration are interesting as we may be able to parallelize such
1468 // loops. Individual loops that have only a small amount of computation
1469 // per-iteration are performance-wise very fragile as any change to the
1470 // loop induction variables may affect performance. To not cause spurious
1471 // performance regressions, we do not consider such loops.
1472 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1473 return true;
1474
1475 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001476}
1477
Tobias Grosser75805372011-04-29 06:27:02 +00001478bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001479 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001480
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001481 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001482
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001483 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001484 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001485 return false;
1486 }
1487
Tobias Grosser134a5722017-03-07 15:50:43 +00001488 DebugLoc DbgLoc;
1489 if (isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
1490 DEBUG(dbgs() << "Unreachable in exit\n");
1491 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1492 CurRegion.getExit(), DbgLoc);
1493 }
1494
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001495 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001496 DEBUG({
1497 dbgs() << "Region entry does not match -polly-region-only";
1498 dbgs() << "\n";
1499 });
1500 return false;
1501 }
1502
Tobias Grosserd654c252012-04-10 18:12:19 +00001503 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001504 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001505 if (CurRegion.getEntry() ==
1506 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1507 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001508
Hongbin Zheng94868e62012-04-07 12:29:17 +00001509 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001510 return false;
1511
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001512 if (!isReducibleRegion(CurRegion, DbgLoc))
1513 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1514 &CurRegion, DbgLoc);
1515
Tobias Grosser75805372011-04-29 06:27:02 +00001516 DEBUG(dbgs() << "OK\n");
1517 return true;
1518}
1519
Tobias Grosser629109b2016-08-03 12:00:07 +00001520void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001521 F->addFnAttr(PollySkipFnAttr);
1522}
1523
Tobias Grosser75805372011-04-29 06:27:02 +00001524bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001525 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001526}
1527
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001528void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001529 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001530 unsigned LineEntry, LineExit;
1531 std::string FileName;
1532
Tobias Grosser00dc3092014-03-02 12:02:46 +00001533 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001534 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1535 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001536 }
1537}
1538
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001539void ScopDetection::emitMissedRemarks(const Function &F) {
1540 for (auto &DIt : DetectionContextMap) {
1541 auto &DC = DIt.getSecond();
1542 if (DC.Log.hasErrors())
1543 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001544 }
1545}
1546
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001547bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001548 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001549 ///
1550 /// WHITE - Unvisited BB in DFS walk.
1551 /// GREY - BBs which are currently on the DFS stack for processing.
1552 /// BLACK - Visited and completely processed BB.
1553 enum Color { WHITE, GREY, BLACK };
1554
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001555 BasicBlock *REntry = R.getEntry();
1556 BasicBlock *RExit = R.getExit();
1557 // Map to match the color of a BasicBlock during the DFS walk.
1558 DenseMap<const BasicBlock *, Color> BBColorMap;
1559 // Stack keeping track of current BB and index of next child to be processed.
1560 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1561
1562 unsigned AdjacentBlockIndex = 0;
1563 BasicBlock *CurrBB, *SuccBB;
1564 CurrBB = REntry;
1565
1566 // Initialize the map for all BB with WHITE color.
1567 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001568 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001569
1570 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001571 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001572 DFSStack.push(std::make_pair(CurrBB, 0));
1573
1574 while (!DFSStack.empty()) {
1575 // Get next BB on stack to be processed.
1576 CurrBB = DFSStack.top().first;
1577 AdjacentBlockIndex = DFSStack.top().second;
1578 DFSStack.pop();
1579
1580 // Loop to iterate over the successors of current BB.
1581 const TerminatorInst *TInst = CurrBB->getTerminator();
1582 unsigned NSucc = TInst->getNumSuccessors();
1583 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1584 ++I, ++AdjacentBlockIndex) {
1585 SuccBB = TInst->getSuccessor(I);
1586
1587 // Checks for region exit block and self-loops in BB.
1588 if (SuccBB == RExit || SuccBB == CurrBB)
1589 continue;
1590
1591 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001592 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001593 // Push the current BB and the index of the next child to be visited.
1594 DFSStack.push(std::make_pair(CurrBB, I + 1));
1595 // Push the next BB to be processed.
1596 DFSStack.push(std::make_pair(SuccBB, 0));
1597 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001598 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001599 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001600 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001601 // GREY indicates a loop in the control flow.
1602 // If the destination dominates the source, it is a natural loop
1603 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001604 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001605 // Get debug info of instruction which causes irregular control flow.
1606 DbgLoc = TInst->getDebugLoc();
1607 return false;
1608 }
1609 }
1610 }
1611
1612 // If all children of current BB have been processed,
1613 // then mark that BB as fully processed.
1614 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001615 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001616 }
1617
1618 return true;
1619}
1620
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001621static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1622 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001623 if (!OnlyProfitable) {
1624 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001625 MaxNumLoopsInScop =
1626 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001627 if (Stats.MaxDepth == 1)
1628 NumScopsDepthOne++;
1629 else if (Stats.MaxDepth == 2)
1630 NumScopsDepthTwo++;
1631 else if (Stats.MaxDepth == 3)
1632 NumScopsDepthThree++;
1633 else if (Stats.MaxDepth == 4)
1634 NumScopsDepthFour++;
1635 else if (Stats.MaxDepth == 5)
1636 NumScopsDepthFive++;
1637 else
1638 NumScopsDepthLarger++;
1639 } else {
1640 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001641 MaxNumLoopsInProfScop =
1642 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001643 if (Stats.MaxDepth == 1)
1644 NumProfScopsDepthOne++;
1645 else if (Stats.MaxDepth == 2)
1646 NumProfScopsDepthTwo++;
1647 else if (Stats.MaxDepth == 3)
1648 NumProfScopsDepthThree++;
1649 else if (Stats.MaxDepth == 4)
1650 NumProfScopsDepthFour++;
1651 else if (Stats.MaxDepth == 5)
1652 NumProfScopsDepthFive++;
1653 else
1654 NumProfScopsDepthLarger++;
1655 }
1656}
1657
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001658ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001659ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001660 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001661 if (DCMIt == DetectionContextMap.end())
1662 return nullptr;
1663 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001664}
1665
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001666const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1667 const DetectionContext *DC = getDetectionContext(R);
1668 return DC ? &DC->Log : nullptr;
1669}
1670
Tobias Grosser75805372011-04-29 06:27:02 +00001671void polly::ScopDetection::verifyRegion(const Region &R) const {
1672 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001673
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001674 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001675 isValidRegion(Context);
1676}
1677
1678void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001679 if (!VerifyScops)
1680 return;
1681
Tobias Grosser26108892014-04-02 20:18:19 +00001682 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001683 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001684}
1685
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001686bool ScopDetectionWrapperPass::runOnFunction(llvm::Function &F) {
1687 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1688 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1689 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1690 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1691 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1692 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA));
1693 return false;
1694}
1695
1696void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001697 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001698 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001699 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001700 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001701 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001702 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001703 AU.setPreservesAll();
1704}
1705
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001706void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1707 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001708 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001709
1710 OS << "\n";
1711}
1712
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001713ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1714 // Disable runtime alias checks if we ignore aliasing all together.
1715 if (IgnoreAliasing)
1716 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001717}
1718
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001719void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001720
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001721char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001722
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001723AnalysisKey ScopAnalysis::Key;
1724
1725ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1726 auto &LI = FAM.getResult<LoopAnalysis>(F);
1727 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1728 auto &AA = FAM.getResult<AAManager>(F);
1729 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1730 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1731 return {F, DT, SE, LI, RI, AA};
1732}
1733
1734PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1735 FunctionAnalysisManager &FAM) {
1736 auto &SD = FAM.getResult<ScopAnalysis>(F);
1737 for (const Region *R : SD.ValidRegions)
1738 Stream << "Valid Region for Scop: " << R->getNameStr() << '\n';
1739
1740 Stream << "\n";
1741 return PreservedAnalyses::all();
1742}
1743
1744Pass *polly::createScopDetectionWrapperPassPass() {
1745 return new ScopDetectionWrapperPass();
1746}
1747
1748INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001749 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001750 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001751INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001752INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001753INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001754INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001755INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001756INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001757 "Polly - Detect static control parts (SCoPs)", false, false)