blob: 909c114e6c4172f4232c3bf306afdb4c1434869a [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 Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000057#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000058#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000059#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000060#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000061#include "llvm/IR/DiagnosticInfo.h"
62#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000063#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000064#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000065#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000066#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000067#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000068
Tobias Grosser75805372011-04-29 06:27:02 +000069using namespace llvm;
70using namespace polly;
71
Chandler Carruth95fef942014-04-22 03:30:19 +000072#define DEBUG_TYPE "polly-detect"
73
Tobias Grosserc1a269b2015-12-21 21:00:43 +000074// This option is set to a very high value, as analyzing such loops increases
75// compile time on several cases. For experiments that enable this option,
76// a value of around 40 has been working to avoid run-time regressions with
77// Polly while still exposing interesting optimization opportunities.
78static cl::opt<int> ProfitabilityMinPerLoopInstructions(
79 "polly-detect-profitability-min-per-loop-insts",
80 cl::desc("The minimal number of per-loop instructions before a single loop "
81 "region is considered profitable"),
82 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
83
Tobias Grosser575aca82015-10-06 16:10:29 +000084bool polly::PollyProcessUnprofitable;
85static cl::opt<bool, true> XPollyProcessUnprofitable(
86 "polly-process-unprofitable",
87 cl::desc(
88 "Process scops that are unlikely to benefit from Polly optimizations."),
89 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
90 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000091
Tobias Grosser483a90d2014-07-09 10:50:10 +000092static cl::opt<std::string> OnlyFunction(
93 "polly-only-func",
94 cl::desc("Only run on functions that contain a certain string"),
95 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
96 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000097
Tobias Grosser483a90d2014-07-09 10:50:10 +000098static cl::opt<std::string> OnlyRegion(
99 "polly-only-region",
100 cl::desc("Only run on certain regions (The provided identifier must "
101 "appear in the name of the region's entry block"),
102 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
103 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000104
Tobias Grosser60cd9322011-11-10 12:47:26 +0000105static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000106 IgnoreAliasing("polly-ignore-aliasing",
107 cl::desc("Ignore possible aliasing of the array bases"),
108 cl::Hidden, cl::init(false), cl::ZeroOrMore,
109 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000110
Johannes Doerfertbda81432016-12-02 17:55:41 +0000111bool polly::PollyAllowUnsignedOperations;
112static cl::opt<bool, true> XPollyAllowUnsignedOperations(
113 "polly-allow-unsigned-operations",
114 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
115 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
116 cl::init(true), cl::cat(PollyCategory));
117
Johannes Doerfertb164c792014-09-18 11:17:17 +0000118bool polly::PollyUseRuntimeAliasChecks;
119static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
120 "polly-use-runtime-alias-checks",
121 cl::desc("Use runtime alias checks to resolve possible aliasing."),
122 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
123 cl::init(true), cl::cat(PollyCategory));
124
Tobias Grosser637bd632013-05-07 07:31:10 +0000125static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000126 ReportLevel("polly-report",
127 cl::desc("Print information about the activities of Polly"),
128 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000129
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000130static cl::opt<bool> AllowDifferentTypes(
131 "polly-allow-differing-element-types",
132 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000133 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000134
Tobias Grosser531891e2012-11-01 16:45:20 +0000135static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000136 AllowNonAffine("polly-allow-nonaffine",
137 cl::desc("Allow non affine access functions in arrays"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000140
Tobias Grosser898a6362016-03-23 06:40:15 +0000141static cl::opt<bool>
142 AllowModrefCall("polly-allow-modref-calls",
143 cl::desc("Allow functions with known modref behavior"),
144 cl::Hidden, cl::init(false), cl::ZeroOrMore,
145 cl::cat(PollyCategory));
146
Johannes Doerfertba65c162015-02-24 11:45:21 +0000147static cl::opt<bool> AllowNonAffineSubRegions(
148 "polly-allow-nonaffine-branches",
149 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000150 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000151
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000152static cl::opt<bool>
153 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
154 cl::desc("Allow non affine conditions for loops"),
155 cl::Hidden, cl::init(false), cl::ZeroOrMore,
156 cl::cat(PollyCategory));
157
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000158static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000159 TrackFailures("polly-detect-track-failures",
160 cl::desc("Track failure strings in detecting scop regions"),
161 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000162 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000163
Andreas Simbuerger04472402014-05-24 09:25:10 +0000164static cl::opt<bool> KeepGoing("polly-detect-keep-going",
165 cl::desc("Do not fail on the first error."),
166 cl::Hidden, cl::ZeroOrMore, cl::init(false),
167 cl::cat(PollyCategory));
168
Sebastian Pop18016682014-04-08 21:20:44 +0000169static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000170 PollyDelinearizeX("polly-delinearize",
171 cl::desc("Delinearize array access functions"),
172 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000173 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000174
Tobias Grossera1689932014-02-18 18:49:49 +0000175static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000176 VerifyScops("polly-detect-verify",
177 cl::desc("Verify the detected SCoPs after each transformation"),
178 cl::Hidden, cl::init(false), cl::ZeroOrMore,
179 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000180
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000181bool polly::PollyInvariantLoadHoisting;
182static cl::opt<bool, true> XPollyInvariantLoadHoisting(
183 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
184 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000185 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000186
Tobias Grosserc80d6972016-09-02 06:33:33 +0000187/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000188static const unsigned MIN_LOOP_TRIP_COUNT = 8;
189
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000190bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000191bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000192StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000193
Tobias Grosser75805372011-04-29 06:27:02 +0000194//===----------------------------------------------------------------------===//
195// Statistics.
196
Tobias Grosserb45ae562016-11-26 07:37:46 +0000197STATISTIC(NumScopRegions, "Number of scops");
198STATISTIC(NumLoopsInScop, "Number of loops in scops");
199STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
200STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
201STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
202STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
203STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
204STATISTIC(NumScopsDepthLarger,
205 "Number of scops with maximal loop depth 6 and larger");
206STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
207STATISTIC(NumLoopsInProfScop,
208 "Number of loops in scops (profitable scops only)");
209STATISTIC(NumLoopsOverall, "Number of total loops");
210STATISTIC(NumProfScopsDepthOne,
211 "Number of scops with maximal loop depth 1 (profitable scops only)");
212STATISTIC(NumProfScopsDepthTwo,
213 "Number of scops with maximal loop depth 2 (profitable scops only)");
214STATISTIC(NumProfScopsDepthThree,
215 "Number of scops with maximal loop depth 3 (profitable scops only)");
216STATISTIC(NumProfScopsDepthFour,
217 "Number of scops with maximal loop depth 4 (profitable scops only)");
218STATISTIC(NumProfScopsDepthFive,
219 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000220STATISTIC(NumProfScopsDepthLarger,
221 "Number of scops with maximal loop depth 6 and larger "
222 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000223STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
224STATISTIC(MaxNumLoopsInProfScop,
225 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000226
Tobias Grosser8519f892013-12-18 10:49:53 +0000227class DiagnosticScopFound : public DiagnosticInfo {
228private:
229 static int PluginDiagnosticKind;
230
231 Function &F;
232 std::string FileName;
233 unsigned EntryLine, ExitLine;
234
235public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000236 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
237 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000238 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000239 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000240
241 virtual void print(DiagnosticPrinter &DP) const;
242
243 static bool classof(const DiagnosticInfo *DI) {
244 return DI->getKind() == PluginDiagnosticKind;
245 }
246};
247
Tobias Grosserdb6db502016-04-01 07:15:19 +0000248int DiagnosticScopFound::PluginDiagnosticKind =
249 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000250
Tobias Grosser8519f892013-12-18 10:49:53 +0000251void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000252 DP << "Polly detected an optimizable loop region (scop) in function '" << F
253 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000254
255 if (FileName.empty()) {
256 DP << "Scop location is unknown. Compile with debug info "
257 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000258 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000259 }
260
261 DP << FileName << ":" << EntryLine << ": Start of scop\n";
262 DP << FileName << ":" << ExitLine << ": End of scop";
263}
264
Tobias Grosser75805372011-04-29 06:27:02 +0000265//===----------------------------------------------------------------------===//
266// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000267
Johannes Doerfertb164c792014-09-18 11:17:17 +0000268ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000269 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000270 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000271 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000272}
273
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000274template <class RR, typename... Args>
275inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
276 Args &&... Arguments) const {
277
278 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000279 RejectLog &Log = Context.Log;
280 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000281
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000282 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000283 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000284
285 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000286 DEBUG(dbgs() << "\n");
287 } else {
288 assert(!Assert && "Verification of detected scop failed");
289 }
290
291 return false;
292}
293
Tobias Grossera1689932014-02-18 18:49:49 +0000294bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
295 if (!ValidRegions.count(&R))
296 return false;
297
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000298 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000299 DetectionContextMap.erase(getBBPairForRegion(&R));
300 const auto &It = DetectionContextMap.insert(std::make_pair(
301 getBBPairForRegion(&R),
302 DetectionContext(const_cast<Region &>(R), *AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000303 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000304 return isValidRegion(Context);
305 }
Tobias Grossera1689932014-02-18 18:49:49 +0000306
307 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000308}
309
Tobias Grosser4f129a62011-10-08 00:30:55 +0000310std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000311 // Get the first error we found. Even in keep-going mode, this is the first
312 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000313 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000314
315 // This can happen when we marked a region invalid, but didn't track
316 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000317 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000318 return "";
319
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000320 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000321 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000322}
323
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000324bool ScopDetection::addOverApproximatedRegion(Region *AR,
325 DetectionContext &Context) const {
326
327 // If we already know about Ar we can exit.
328 if (!Context.NonAffineSubRegionSet.insert(AR))
329 return true;
330
331 // All loops in the region have to be overapproximated too if there
332 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000333
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000334 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000335 Loop *L = LI->getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000336 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000337 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000338 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000339
340 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000341}
342
Johannes Doerfert09e36972015-10-07 20:17:36 +0000343bool ScopDetection::onlyValidRequiredInvariantLoads(
344 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
345 Region &CurRegion = Context.CurRegion;
346
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000347 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
348 return false;
349
Tobias Grosser1c787e02017-03-02 12:15:37 +0000350 for (LoadInst *Load : RequiredILS) {
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000351 if (!isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000352 return false;
353
Tobias Grosser1c787e02017-03-02 12:15:37 +0000354 for (auto NonAffineRegion : Context.NonAffineSubRegionSet)
355 if (NonAffineRegion->contains(Load) &&
356 Load->getParent() != NonAffineRegion->getEntry())
357 return false;
358 }
359
Johannes Doerfert09e36972015-10-07 20:17:36 +0000360 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
361
362 return true;
363}
364
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000365bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
366 Loop *Scope) const {
367 SetVector<Value *> Values;
368 findValues(S0, *SE, Values);
369 if (S1)
370 findValues(S1, *SE, Values);
371
372 SmallPtrSet<Value *, 8> PtrVals;
373 for (auto *V : Values) {
374 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
375 V = P2I->getOperand(0);
376
377 if (!V->getType()->isPointerTy())
378 continue;
379
380 auto *PtrSCEV = SE->getSCEVAtScope(V, Scope);
381 if (isa<SCEVConstant>(PtrSCEV))
382 continue;
383
384 auto *BasePtr = dyn_cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
385 if (!BasePtr)
386 return true;
387
388 auto *BasePtrVal = BasePtr->getValue();
389 if (PtrVals.insert(BasePtrVal).second) {
390 for (auto *PtrVal : PtrVals)
391 if (PtrVal != BasePtrVal && !AA->isNoAlias(PtrVal, BasePtrVal))
392 return true;
393 }
394 }
395
396 return false;
397}
398
Michael Kruse09eb4452016-03-03 22:10:47 +0000399bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000400 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000401
402 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000403 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000404 return false;
405
406 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
407 return false;
408
409 return true;
410}
411
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000412bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000413 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000414 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000415 Loop *L = LI->getLoopFor(&BB);
416 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000417
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000418 if (IsLoopBranch && L->isLoopLatch(&BB))
419 return false;
420
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000421 // Check for invalid usage of different pointers in one expression.
422 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
423 return false;
424
Michael Kruse09eb4452016-03-03 22:10:47 +0000425 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000426 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000427
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000428 if (AllowNonAffineSubRegions &&
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000429 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
430 return true;
431
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000432 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
433 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000434}
435
436bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000437 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000438 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000439
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000440 // Constant integer conditions are always affine.
441 if (isa<ConstantInt>(Condition))
442 return true;
443
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000444 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
445 auto Opcode = BinOp->getOpcode();
446 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
447 Value *Op0 = BinOp->getOperand(0);
448 Value *Op1 = BinOp->getOperand(1);
449 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
450 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
451 }
452 }
453
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000454 // Non constant conditions of branches need to be ICmpInst.
455 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000456 if (!IsLoopBranch && AllowNonAffineSubRegions &&
457 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
458 return true;
459 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000460 }
Tobias Grosser75805372011-04-29 06:27:02 +0000461
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000462 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000463
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000464 // Are both operands of the ICmp affine?
465 if (isa<UndefValue>(ICmp->getOperand(0)) ||
466 isa<UndefValue>(ICmp->getOperand(1)))
467 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000468
Tobias Grossera2f8fa32016-11-13 19:27:04 +0000469 Loop *L = LI->getLoopFor(&BB);
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000470 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
471 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000472
Johannes Doerfertbda81432016-12-02 17:55:41 +0000473 // If unsigned operations are not allowed try to approximate the region.
474 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
475 return !IsLoopBranch && AllowNonAffineSubRegions &&
476 addOverApproximatedRegion(RI->getRegionFor(&BB), Context);
477
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000478 // Check for invalid usage of different pointers in one expression.
479 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
480 involvesMultiplePtrs(RHS, nullptr, L))
481 return false;
482
483 // Check for invalid usage of different pointers in a relational comparison.
484 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
485 return false;
486
Michael Kruse09eb4452016-03-03 22:10:47 +0000487 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000488 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000489
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000490 if (!IsLoopBranch && AllowNonAffineSubRegions &&
491 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
492 return true;
493
494 if (IsLoopBranch)
495 return false;
496
497 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
498 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000499}
500
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000501bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000502 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000503 DetectionContext &Context) const {
504 Region &CurRegion = Context.CurRegion;
505
506 TerminatorInst *TI = BB.getTerminator();
507
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000508 if (AllowUnreachable && isa<UnreachableInst>(TI))
509 return true;
510
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000511 // Return instructions are only valid if the region is the top level region.
512 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
513 return true;
514
515 Value *Condition = getConditionFromTerminator(TI);
516
517 if (!Condition)
518 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
519
520 // UndefValue is not allowed as condition.
521 if (isa<UndefValue>(Condition))
522 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
523
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000524 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000525 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000526
527 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
528 assert(SI && "Terminator was neither branch nor switch");
529
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000530 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000531}
532
Johannes Doerfertcea61932016-02-21 19:13:19 +0000533bool ScopDetection::isValidCallInst(CallInst &CI,
534 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000535 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000536 return false;
537
538 if (CI.doesNotAccessMemory())
539 return true;
540
Johannes Doerfertcea61932016-02-21 19:13:19 +0000541 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000542 if (isValidIntrinsicInst(*II, Context))
543 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000544
Tobias Grosser75805372011-04-29 06:27:02 +0000545 Function *CalledFunction = CI.getCalledFunction();
546
547 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000548 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000549 return false;
550
Tobias Grosser898a6362016-03-23 06:40:15 +0000551 if (AllowModrefCall) {
552 switch (AA->getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000553 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000554 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000555 case FMRB_DoesNotAccessMemory:
556 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000557 // Implicitly disable delinearization since we have an unknown
558 // accesses with an unknown access function.
559 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000560 Context.AST.add(&CI);
561 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000562 case FMRB_OnlyReadsArgumentPointees:
563 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000564 for (const auto &Arg : CI.arg_operands()) {
565 if (!Arg->getType()->isPointerTy())
566 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000567
Tobias Grosser898a6362016-03-23 06:40:15 +0000568 // Bail if a pointer argument has a base address not known to
569 // ScalarEvolution. Note that a zero pointer is acceptable.
570 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
571 if (ArgSCEV->isZero())
572 continue;
573
574 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
575 if (!BP)
576 return false;
577
578 // Implicitly disable delinearization since we have an unknown
579 // accesses with an unknown access function.
580 Context.HasUnknownAccess = true;
581 }
582
583 Context.AST.add(&CI);
584 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000585 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000586 case FMRB_OnlyAccessesInaccessibleMem:
587 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000588 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000589 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000590 }
591
Johannes Doerfertcea61932016-02-21 19:13:19 +0000592 return false;
593}
594
595bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
596 DetectionContext &Context) const {
597 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000598 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000599
Johannes Doerfertcea61932016-02-21 19:13:19 +0000600 // The closest loop surrounding the call instruction.
601 Loop *L = LI->getLoopFor(II.getParent());
602
603 // The access function and base pointer for memory intrinsics.
604 const SCEV *AF;
605 const SCEVUnknown *BP;
606
607 switch (II.getIntrinsicID()) {
608 // Memory intrinsics that can be represented are supported.
609 case llvm::Intrinsic::memmove:
610 case llvm::Intrinsic::memcpy:
611 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000612 if (!AF->isZero()) {
613 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
614 // Bail if the source pointer is not valid.
615 if (!isValidAccess(&II, AF, BP, Context))
616 return false;
617 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000618 // Fall through
619 case llvm::Intrinsic::memset:
620 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000621 if (!AF->isZero()) {
622 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
623 // Bail if the destination pointer is not valid.
624 if (!isValidAccess(&II, AF, BP, Context))
625 return false;
626 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000627
628 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000629 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000630 Context))
631 return false;
632
633 return true;
634 default:
635 break;
636 }
637
Tobias Grosser75805372011-04-29 06:27:02 +0000638 return false;
639}
640
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000641bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
642 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000643 // A reference to function argument or constant value is invariant.
644 if (isa<Argument>(Val) || isa<Constant>(Val))
645 return true;
646
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000647 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000648 if (!I)
649 return false;
650
651 if (!Reg.contains(I))
652 return true;
653
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000654 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
655 // is not hoistable, it will be rejected later, but here we assume it is and
656 // that makes the value invariant.
657 if (auto LI = dyn_cast<LoadInst>(I)) {
658 Ctx.RequiredILS.insert(LI);
659 return true;
660 }
661
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000662 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000663}
664
Tobias Grosserc80d6972016-09-02 06:33:33 +0000665/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000666/// register the '...' components.
667///
668/// Array access expressions as they are generated by gfortran contain smax(0,
669/// size) expressions that confuse the 'normal' delinearization algorithm.
670/// However, if we extract such expressions before the normal delinearization
671/// takes place they can actually help to identify array size expressions in
672/// fortran accesses. For the subsequently following delinearization the smax(0,
673/// size) component can be replaced by just 'size'. This is correct as we will
674/// always add and verify the assumption that for all subscript expressions
675/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
676/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000677class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000678public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000679 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
680 std::vector<const SCEV *> *Terms = nullptr) {
681 SCEVRemoveMax Rewriter(SE, Terms);
682 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000683 }
684
685 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000686 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000687
688 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000689 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000690 auto Res = visit(Expr->getOperand(1));
691 if (Terms)
692 (*Terms).push_back(Res);
693 return Res;
694 }
695
696 return Expr;
697 }
698
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000699private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000700 std::vector<const SCEV *> *Terms;
701};
702
Tobias Grosserd68ba422015-11-24 05:00:36 +0000703SmallVector<const SCEV *, 4>
704ScopDetection::getDelinearizationTerms(DetectionContext &Context,
705 const SCEVUnknown *BasePointer) const {
706 SmallVector<const SCEV *, 4> Terms;
707 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000708 std::vector<const SCEV *> MaxTerms;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000709 SCEVRemoveMax::rewrite(Pair.second, *SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000710 if (MaxTerms.size() > 0) {
711 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
712 continue;
713 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000714 // In case the outermost expression is a plain add, we check if any of its
715 // terms has the form 4 * %inst * %param * %param ..., aka a term that
716 // contains a product between a parameter and an instruction that is
717 // inside the scop. Such instructions, if allowed at all, are instructions
718 // SCEV can not represent, but Polly is still looking through. As a
719 // result, these instructions can depend on induction variables and are
720 // most likely no array sizes. However, terms that are multiplied with
721 // them are likely candidates for array sizes.
722 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
723 for (auto Op : AF->operands()) {
724 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
725 SE->collectParametricTerms(AF2, Terms);
726 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
727 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000728
Tobias Grosserd68ba422015-11-24 05:00:36 +0000729 for (auto *MulOp : AF2->operands()) {
730 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
731 Operands.push_back(Const);
732 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
733 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
734 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000735 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000736
737 } else {
738 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000739 }
740 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000741 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000742 if (Operands.size())
743 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000744 }
745 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000746 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000747 if (Terms.empty())
748 SE->collectParametricTerms(Pair.second, Terms);
749 }
750 return Terms;
751}
Sebastian Pope8863b82014-05-12 19:02:02 +0000752
Tobias Grosserd68ba422015-11-24 05:00:36 +0000753bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
754 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000755 const SCEVUnknown *BasePointer,
756 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000757 Value *BaseValue = BasePointer->getValue();
758 Region &CurRegion = Context.CurRegion;
759 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000760 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000761 Sizes.clear();
762 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000763 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000764 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
765 auto *V = dyn_cast<Value>(Unknown->getValue());
766 if (auto *Load = dyn_cast<LoadInst>(V)) {
767 if (Context.CurRegion.contains(Load) &&
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000768 isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000769 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000770 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000771 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000772 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000773 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000774 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000775 Context, /*Assert=*/true, DelinearizedSize,
776 Context.Accesses[BasePointer].front().first, BaseValue);
777 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000778
Tobias Grosserd68ba422015-11-24 05:00:36 +0000779 // No array shape derived.
780 if (Sizes.empty()) {
781 if (AllowNonAffine)
782 return true;
783
Tobias Grosser230acc42014-09-13 14:47:55 +0000784 for (const auto &Pair : Context.Accesses[BasePointer]) {
785 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000786 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000787
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000788 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000789 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
790 BaseValue);
791 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000792 return false;
793 }
794 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000795 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000796 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000797 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000798}
799
Tobias Grosserd68ba422015-11-24 05:00:36 +0000800// We first store the resulting memory accesses in TempMemoryAccesses. Only
801// if the access functions for all memory accesses have been successfully
802// delinearized we continue. Otherwise, we either report a failure or, if
803// non-affine accesses are allowed, we drop the information. In case the
804// information is dropped the memory accesses need to be overapproximated
805// when translated to a polyhedral representation.
806bool ScopDetection::computeAccessFunctions(
807 DetectionContext &Context, const SCEVUnknown *BasePointer,
808 std::shared_ptr<ArrayShape> Shape) const {
809 Value *BaseValue = BasePointer->getValue();
810 bool BasePtrHasNonAffine = false;
811 MapInsnToMemAcc TempMemoryAccesses;
812 for (const auto &Pair : Context.Accesses[BasePointer]) {
813 const Instruction *Insn = Pair.first;
814 auto *AF = Pair.second;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000815 AF = SCEVRemoveMax::rewrite(AF, *SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000816 bool IsNonAffine = false;
817 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
818 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000819 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000820
821 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000822 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000823 Acc->DelinearizedSubscripts.push_back(Pair.second);
824 else
825 IsNonAffine = true;
826 } else {
827 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
828 Shape->DelinearizedSizes);
829 if (Acc->DelinearizedSubscripts.size() == 0)
830 IsNonAffine = true;
831 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000832 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000833 IsNonAffine = true;
834 }
835
836 // (Possibly) report non affine access
837 if (IsNonAffine) {
838 BasePtrHasNonAffine = true;
839 if (!AllowNonAffine)
840 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
841 Insn, BaseValue);
842 if (!KeepGoing && !AllowNonAffine)
843 return false;
844 }
845 }
846
847 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000848 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
849 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000850
851 return true;
852}
853
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000854bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
855 const SCEVUnknown *BasePointer,
856 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000857 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
858
859 auto Terms = getDelinearizationTerms(Context, BasePointer);
860
861 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
862 Context.ElementSize[BasePointer]);
863
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000864 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
865 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000866 return false;
867
868 return computeAccessFunctions(Context, BasePointer, Shape);
869}
870
871bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000872 // TODO: If we have an unknown access and other non-affine accesses we do
873 // not try to delinearize them for now.
874 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
875 return AllowNonAffine;
876
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000877 for (auto &Pair : Context.NonAffineAccesses) {
878 auto *BasePointer = Pair.first;
879 auto *Scope = Pair.second;
880 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000881 if (KeepGoing)
882 continue;
883 else
884 return false;
885 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000886 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000887 return true;
888}
889
Johannes Doerfertcea61932016-02-21 19:13:19 +0000890bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
891 const SCEVUnknown *BP,
892 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000893
Johannes Doerfertcea61932016-02-21 19:13:19 +0000894 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000895 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000896
Johannes Doerfertcea61932016-02-21 19:13:19 +0000897 auto *BV = BP->getValue();
898 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000899 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000900
Johannes Doerfertcea61932016-02-21 19:13:19 +0000901 // FIXME: Think about allowing IntToPtrInst
902 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
903 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
904
Tobias Grosser458fb782014-01-28 12:58:58 +0000905 // Check that the base address of the access is invariant in the current
906 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000907 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000908 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000909
Johannes Doerfertcea61932016-02-21 19:13:19 +0000910 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000911
Johannes Doerfertcea61932016-02-21 19:13:19 +0000912 const SCEV *Size;
913 if (!isa<MemIntrinsic>(Inst)) {
914 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000915 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000916 auto *SizeTy =
917 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
918 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000919 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000920
Johannes Doerfertcea61932016-02-21 19:13:19 +0000921 if (Context.ElementSize[BP]) {
922 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
923 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
924 Inst, BV);
925
926 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
927 } else {
928 Context.ElementSize[BP] = Size;
929 }
930
931 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000932 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000933 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000934 for (const Loop *L : Loops)
935 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000936 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000937
Michael Kruse09eb4452016-03-03 22:10:47 +0000938 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000939 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000940 // Do not try to delinearize memory intrinsics and force them to be affine.
941 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
942 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
943 BV);
944 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
945 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000946
Johannes Doerfertcea61932016-02-21 19:13:19 +0000947 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000948 Context.NonAffineAccesses.insert(
949 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000950 } else if (!AllowNonAffine && !IsAffine) {
951 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
952 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000953 }
Tobias Grosser75805372011-04-29 06:27:02 +0000954
Tobias Grosser1eedb672014-09-24 21:04:29 +0000955 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000956 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000957
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000958 // Check if the base pointer of the memory access does alias with
959 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000960 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000961 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000962 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000963 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000964
Tobias Grosser1eedb672014-09-24 21:04:29 +0000965 if (!AS.isMustAlias()) {
966 if (PollyUseRuntimeAliasChecks) {
967 bool CanBuildRunTimeCheck = true;
968 // The run-time alias check places code that involves the base pointer at
969 // the beginning of the SCoP. This breaks if the base pointer is defined
970 // inside the scop. Hence, we can only create a run-time check if we are
971 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000972 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000973 for (const auto &Ptr : AS) {
974 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000975 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000976 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000977 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE, *DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000978 Context.RequiredILS.insert(Load);
979 continue;
980 }
981
Tobias Grosser1eedb672014-09-24 21:04:29 +0000982 CanBuildRunTimeCheck = false;
983 break;
984 }
985 }
986
987 if (CanBuildRunTimeCheck)
988 return true;
989 }
Michael Kruse70131d32016-01-27 17:09:17 +0000990 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000991 }
Tobias Grosser75805372011-04-29 06:27:02 +0000992
993 return true;
994}
995
Johannes Doerfertcea61932016-02-21 19:13:19 +0000996bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
997 DetectionContext &Context) const {
998 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000999 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001000 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
1001 const SCEVUnknown *BasePointer;
1002
1003 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
1004
1005 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1006}
1007
Tobias Grosser75805372011-04-29 06:27:02 +00001008bool ScopDetection::isValidInstruction(Instruction &Inst,
1009 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001010 for (auto &Op : Inst.operands()) {
1011 auto *OpInst = dyn_cast<Instruction>(&Op);
1012
1013 if (!OpInst)
1014 continue;
1015
1016 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
1017 return false;
1018 }
1019
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001020 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1021 return false;
1022
Tobias Grosser75805372011-04-29 06:27:02 +00001023 // We only check the call instruction but not invoke instruction.
1024 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001025 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001026 return true;
1027
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001028 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001029 }
1030
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001031 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001032 if (!isa<AllocaInst>(Inst))
1033 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001034
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001035 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001036 }
1037
1038 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001039 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001040 Context.hasStores |= isa<StoreInst>(MemInst);
1041 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001042 if (!MemInst.isSimple())
1043 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1044 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001045
Michael Kruse70131d32016-01-27 17:09:17 +00001046 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001047 }
Tobias Grosser75805372011-04-29 06:27:02 +00001048
1049 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001050 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001051}
1052
Tobias Grosser349d1c32016-09-20 17:05:22 +00001053/// Check whether @p L has exiting blocks.
1054///
1055/// @param L The loop of interest
1056///
1057/// @return True if the loop has exiting blocks, false otherwise.
1058static bool hasExitingBlocks(Loop *L) {
1059 SmallVector<BasicBlock *, 4> ExitingBlocks;
1060 L->getExitingBlocks(ExitingBlocks);
1061 return !ExitingBlocks.empty();
1062}
1063
Johannes Doerfertd020b772015-08-27 06:53:52 +00001064bool ScopDetection::canUseISLTripCount(Loop *L,
1065 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001066 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1067 // need to overapproximate it as a boxed loop.
1068 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001069 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001070 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001071 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001072 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001073 return false;
1074 }
1075
Johannes Doerfertd020b772015-08-27 06:53:52 +00001076 // We can use ISL to compute the trip count of L.
1077 return true;
1078}
1079
Tobias Grosser75805372011-04-29 06:27:02 +00001080bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001081 // Loops that contain part but not all of the blocks of a region cannot be
1082 // handled by the schedule generation. Such loop constructs can happen
1083 // because a region can contain BBs that have no path to the exit block
1084 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1085 // loop.
1086 //
1087 // _______________
1088 // | Loop Header | <-----------.
1089 // --------------- |
1090 // | |
1091 // _______________ ______________
1092 // | RegionEntry |-----> | RegionExit |----->
1093 // --------------- --------------
1094 // |
1095 // _______________
1096 // | EndlessLoop | <--.
1097 // --------------- |
1098 // | |
1099 // \------------/
1100 //
1101 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1102 // neither entirely contained in the region RegionEntry->RegionExit
1103 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1104 // in the loop.
1105 // The block EndlessLoop is contained in the region because Region::contains
1106 // tests whether it is not dominated by RegionExit. This is probably to not
1107 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1108 // end can also be formed by an UnreachableInst. This case is already caught
1109 // by isErrorBlock(). We hence only have to reject endless loops here.
1110 if (!hasExitingBlocks(L))
1111 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1112
Johannes Doerfertf61df692015-10-04 14:56:08 +00001113 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001114 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001115
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001116 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001117 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001118 while (R != &Context.CurRegion && !R->contains(L))
1119 R = R->getParent();
1120
1121 if (addOverApproximatedRegion(R, Context))
1122 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001123 }
Tobias Grosser75805372011-04-29 06:27:02 +00001124
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001125 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001126 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001127}
1128
Tobias Grosserc80d6972016-09-02 06:33:33 +00001129/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001130/// count that is not known to be less than @MinProfitableTrips.
1131ScopDetection::LoopStats
1132ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001133 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001134 auto *TripCount = SE.getBackedgeTakenCount(L);
1135
Tobias Grosserb45ae562016-11-26 07:37:46 +00001136 int NumLoops = 1;
1137 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001138 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001139 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001140 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1141 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001142
Tobias Grosserb45ae562016-11-26 07:37:46 +00001143 for (auto &SubLoop : *L) {
1144 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1145 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001146 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001147 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001148
Tobias Grosserb45ae562016-11-26 07:37:46 +00001149 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001150}
1151
Tobias Grosserb45ae562016-11-26 07:37:46 +00001152ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001153ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1154 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001155 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001156 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001157
Tobias Grossercd01a362017-02-17 08:12:36 +00001158 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001159 L = L ? R->outermostLoopInRegion(L) : nullptr;
1160 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001161
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001162 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001163 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001164
1165 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001166 if (R->contains(SubLoop)) {
1167 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001168 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001169 LoopNum += Stats.NumLoops;
1170 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1171 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001172
Tobias Grosserb45ae562016-11-26 07:37:46 +00001173 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001174}
1175
Tobias Grosser75805372011-04-29 06:27:02 +00001176Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001177 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001178 std::unique_ptr<Region> LastValidRegion;
1179 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001180
1181 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1182
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001183 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001184 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001185 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001186 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1187 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001188 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001189 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001190
Johannes Doerfert717b8662015-09-08 21:44:27 +00001191 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001192 // If the exit is valid check all blocks
1193 // - if true, a valid region was found => store it + keep expanding
1194 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001195 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1196 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001197 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001198 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001199 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001200
Tobias Grosserd7e58642013-04-10 06:55:45 +00001201 // Store this region, because it is the greatest valid (encountered so
1202 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001203 if (LastValidRegion) {
1204 removeCachedResults(*LastValidRegion);
1205 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1206 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001207 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001208
1209 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001210 ExpandedRegion =
1211 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001212
1213 } else {
1214 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001215 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001216 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001217 ExpandedRegion =
1218 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001219 }
Tobias Grosser75805372011-04-29 06:27:02 +00001220 }
1221
Tobias Grosser378a9f22013-11-16 19:34:11 +00001222 DEBUG({
1223 if (LastValidRegion)
1224 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1225 else
1226 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1227 });
Tobias Grosser75805372011-04-29 06:27:02 +00001228
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001229 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001230}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001231static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001232 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001233 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001234 return false;
1235
1236 return true;
1237}
Tobias Grosser75805372011-04-29 06:27:02 +00001238
Tobias Grosserb45ae562016-11-26 07:37:46 +00001239void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001240 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001241 if (ValidRegions.count(SubRegion.get())) {
1242 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001243 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001244 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001245 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001246}
1247
Johannes Doerferte46925f2015-10-01 10:59:14 +00001248void ScopDetection::removeCachedResults(const Region &R) {
1249 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001250}
1251
Tobias Grosser75805372011-04-29 06:27:02 +00001252void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001253 const auto &It = DetectionContextMap.insert(std::make_pair(
1254 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001255 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001256
1257 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001258 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001259 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001260 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001261 RegionIsValid = isValidRegion(Context);
1262
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001263 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001264
Johannes Doerferte46925f2015-10-01 10:59:14 +00001265 if (HasErrors) {
1266 removeCachedResults(R);
1267 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001268 ValidRegions.insert(&R);
1269 return;
1270 }
1271
David Blaikieb035f6d2014-04-15 18:45:27 +00001272 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001273 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001274
1275 // Try to expand regions.
1276 //
1277 // As the region tree normally only contains canonical regions, non canonical
1278 // regions that form a Scop are not found. Therefore, those non canonical
1279 // regions are checked by expanding the canonical ones.
1280
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001281 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001282
David Blaikieb035f6d2014-04-15 18:45:27 +00001283 for (auto &SubRegion : R)
1284 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001285
Tobias Grosser26108892014-04-02 20:18:19 +00001286 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001287 // Skip invalid regions. Regions may become invalid, if they are element of
1288 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001289 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001290 continue;
1291
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001292 // Skip regions that had errors.
1293 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1294 if (HadErrors)
1295 continue;
1296
Tobias Grosser75805372011-04-29 06:27:02 +00001297 Region *ExpandedR = expandRegion(*CurrentRegion);
1298
1299 if (!ExpandedR)
1300 continue;
1301
1302 R.addSubRegion(ExpandedR, true);
1303 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001304 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001305 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001306 }
1307}
1308
1309bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001310 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001311
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001312 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001313 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001314 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1315 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001316 return false;
1317 }
1318
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001319 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001320 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1321
1322 // Also check exception blocks (and possibly register them as non-affine
1323 // regions). Even though exception blocks are not modeled, we use them
1324 // to forward-propagate domain constraints during ScopInfo construction.
1325 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1326 return false;
1327
1328 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001329 continue;
1330
Tobias Grosser1d191902014-03-03 13:13:55 +00001331 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001332 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001333 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001334 }
Tobias Grosser75805372011-04-29 06:27:02 +00001335
Sebastian Pope8863b82014-05-12 19:02:02 +00001336 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001337 return false;
1338
Tobias Grosser75805372011-04-29 06:27:02 +00001339 return true;
1340}
1341
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001342bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1343 int NumLoops) const {
1344 int InstCount = 0;
1345
Tobias Grosserb316dc12016-09-08 14:08:05 +00001346 if (NumLoops == 0)
1347 return false;
1348
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001349 for (auto *BB : Context.CurRegion.blocks())
1350 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001351 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001352
1353 InstCount = InstCount / NumLoops;
1354
1355 return InstCount >= ProfitabilityMinPerLoopInstructions;
1356}
1357
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001358bool ScopDetection::hasPossiblyDistributableLoop(
1359 DetectionContext &Context) const {
1360 for (auto *BB : Context.CurRegion.blocks()) {
1361 auto *L = LI->getLoopFor(BB);
1362 if (!Context.CurRegion.contains(L))
1363 continue;
1364 if (Context.BoxedLoopsSet.count(L))
1365 continue;
1366 unsigned StmtsWithStoresInLoops = 0;
1367 for (auto *LBB : L->blocks()) {
1368 bool MemStore = false;
1369 for (auto &I : *LBB)
1370 MemStore |= isa<StoreInst>(&I);
1371 StmtsWithStoresInLoops += MemStore;
1372 }
1373 return (StmtsWithStoresInLoops > 1);
1374 }
1375 return false;
1376}
1377
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001378bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1379 Region &CurRegion = Context.CurRegion;
1380
1381 if (PollyProcessUnprofitable)
1382 return true;
1383
1384 // We can probably not do a lot on scops that only write or only read
1385 // data.
1386 if (!Context.hasStores || !Context.hasLoads)
1387 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1388
Tobias Grossercd01a362017-02-17 08:12:36 +00001389 int NumLoops =
1390 countBeneficialLoops(&CurRegion, *SE, *LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001391 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001392
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001393 // Scops with at least two loops may allow either loop fusion or tiling and
1394 // are consequently interesting to look at.
1395 if (NumAffineLoops >= 2)
1396 return true;
1397
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001398 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1399 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1400 return true;
1401
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001402 // Scops that contain a loop with a non-trivial amount of computation per
1403 // loop-iteration are interesting as we may be able to parallelize such
1404 // loops. Individual loops that have only a small amount of computation
1405 // per-iteration are performance-wise very fragile as any change to the
1406 // loop induction variables may affect performance. To not cause spurious
1407 // performance regressions, we do not consider such loops.
1408 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1409 return true;
1410
1411 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001412}
1413
Tobias Grosser75805372011-04-29 06:27:02 +00001414bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001415 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001416
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001417 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001418
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001419 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001420 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001421 return false;
1422 }
1423
Tobias Grosser134a5722017-03-07 15:50:43 +00001424 DebugLoc DbgLoc;
1425 if (isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
1426 DEBUG(dbgs() << "Unreachable in exit\n");
1427 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1428 CurRegion.getExit(), DbgLoc);
1429 }
1430
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001431 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001432 DEBUG({
1433 dbgs() << "Region entry does not match -polly-region-only";
1434 dbgs() << "\n";
1435 });
1436 return false;
1437 }
1438
Tobias Grosserd654c252012-04-10 18:12:19 +00001439 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001440 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001441 if (CurRegion.getEntry() ==
1442 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1443 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001444
Hongbin Zheng94868e62012-04-07 12:29:17 +00001445 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001446 return false;
1447
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001448 if (!isReducibleRegion(CurRegion, DbgLoc))
1449 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1450 &CurRegion, DbgLoc);
1451
Tobias Grosser75805372011-04-29 06:27:02 +00001452 DEBUG(dbgs() << "OK\n");
1453 return true;
1454}
1455
Tobias Grosser629109b2016-08-03 12:00:07 +00001456void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001457 F->addFnAttr(PollySkipFnAttr);
1458}
1459
Tobias Grosser75805372011-04-29 06:27:02 +00001460bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001461 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001462}
1463
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001464void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001465 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001466 unsigned LineEntry, LineExit;
1467 std::string FileName;
1468
Tobias Grosser00dc3092014-03-02 12:02:46 +00001469 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001470 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1471 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001472 }
1473}
1474
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001475void ScopDetection::emitMissedRemarks(const Function &F) {
1476 for (auto &DIt : DetectionContextMap) {
1477 auto &DC = DIt.getSecond();
1478 if (DC.Log.hasErrors())
1479 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001480 }
1481}
1482
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001483bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001484 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001485 ///
1486 /// WHITE - Unvisited BB in DFS walk.
1487 /// GREY - BBs which are currently on the DFS stack for processing.
1488 /// BLACK - Visited and completely processed BB.
1489 enum Color { WHITE, GREY, BLACK };
1490
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001491 BasicBlock *REntry = R.getEntry();
1492 BasicBlock *RExit = R.getExit();
1493 // Map to match the color of a BasicBlock during the DFS walk.
1494 DenseMap<const BasicBlock *, Color> BBColorMap;
1495 // Stack keeping track of current BB and index of next child to be processed.
1496 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1497
1498 unsigned AdjacentBlockIndex = 0;
1499 BasicBlock *CurrBB, *SuccBB;
1500 CurrBB = REntry;
1501
1502 // Initialize the map for all BB with WHITE color.
1503 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001504 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001505
1506 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001507 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001508 DFSStack.push(std::make_pair(CurrBB, 0));
1509
1510 while (!DFSStack.empty()) {
1511 // Get next BB on stack to be processed.
1512 CurrBB = DFSStack.top().first;
1513 AdjacentBlockIndex = DFSStack.top().second;
1514 DFSStack.pop();
1515
1516 // Loop to iterate over the successors of current BB.
1517 const TerminatorInst *TInst = CurrBB->getTerminator();
1518 unsigned NSucc = TInst->getNumSuccessors();
1519 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1520 ++I, ++AdjacentBlockIndex) {
1521 SuccBB = TInst->getSuccessor(I);
1522
1523 // Checks for region exit block and self-loops in BB.
1524 if (SuccBB == RExit || SuccBB == CurrBB)
1525 continue;
1526
1527 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001528 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001529 // Push the current BB and the index of the next child to be visited.
1530 DFSStack.push(std::make_pair(CurrBB, I + 1));
1531 // Push the next BB to be processed.
1532 DFSStack.push(std::make_pair(SuccBB, 0));
1533 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001534 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001535 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001536 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001537 // GREY indicates a loop in the control flow.
1538 // If the destination dominates the source, it is a natural loop
1539 // else, an irreducible control flow in the region is detected.
1540 if (!DT->dominates(SuccBB, CurrBB)) {
1541 // Get debug info of instruction which causes irregular control flow.
1542 DbgLoc = TInst->getDebugLoc();
1543 return false;
1544 }
1545 }
1546 }
1547
1548 // If all children of current BB have been processed,
1549 // then mark that BB as fully processed.
1550 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001551 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001552 }
1553
1554 return true;
1555}
1556
Tobias Grosserb45ae562016-11-26 07:37:46 +00001557void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1558 bool OnlyProfitable) {
1559 if (!OnlyProfitable) {
1560 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001561 MaxNumLoopsInScop =
1562 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001563 if (Stats.MaxDepth == 1)
1564 NumScopsDepthOne++;
1565 else if (Stats.MaxDepth == 2)
1566 NumScopsDepthTwo++;
1567 else if (Stats.MaxDepth == 3)
1568 NumScopsDepthThree++;
1569 else if (Stats.MaxDepth == 4)
1570 NumScopsDepthFour++;
1571 else if (Stats.MaxDepth == 5)
1572 NumScopsDepthFive++;
1573 else
1574 NumScopsDepthLarger++;
1575 } else {
1576 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001577 MaxNumLoopsInProfScop =
1578 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001579 if (Stats.MaxDepth == 1)
1580 NumProfScopsDepthOne++;
1581 else if (Stats.MaxDepth == 2)
1582 NumProfScopsDepthTwo++;
1583 else if (Stats.MaxDepth == 3)
1584 NumProfScopsDepthThree++;
1585 else if (Stats.MaxDepth == 4)
1586 NumProfScopsDepthFour++;
1587 else if (Stats.MaxDepth == 5)
1588 NumProfScopsDepthFive++;
1589 else
1590 NumProfScopsDepthLarger++;
1591 }
1592}
1593
Tobias Grosser75805372011-04-29 06:27:02 +00001594bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001595 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001596 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001597 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001598 return false;
1599
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001600 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001601 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001602 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001603 Region *TopRegion = RI->getTopLevelRegion();
1604
Tobias Grosser2ff87232011-10-23 11:17:06 +00001605 releaseMemory();
1606
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001607 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001608 return false;
1609
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001610 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001611 return false;
1612
1613 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001614
Tobias Grosserb45ae562016-11-26 07:37:46 +00001615 NumScopRegions += ValidRegions.size();
1616
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001617 // Prune non-profitable regions.
1618 for (auto &DIt : DetectionContextMap) {
1619 auto &DC = DIt.getSecond();
1620 if (DC.Log.hasErrors())
1621 continue;
1622 if (!ValidRegions.count(&DC.CurRegion))
1623 continue;
Tobias Grossercd01a362017-02-17 08:12:36 +00001624 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, *SE, *LI, 0);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001625 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
1626 if (isProfitableRegion(DC)) {
1627 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001628 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001629 }
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001630
1631 ValidRegions.remove(&DC.CurRegion);
1632 }
1633
Tobias Grosserb45ae562016-11-26 07:37:46 +00001634 NumProfScopRegions += ValidRegions.size();
Tobias Grossercd01a362017-02-17 08:12:36 +00001635 NumLoopsOverall += countBeneficialLoops(TopRegion, *SE, *LI, 0).NumLoops;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001636
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001637 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001638 if (PollyTrackFailures)
1639 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001640
Johannes Doerferta05214f2014-10-15 23:24:28 +00001641 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001642 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001643
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001644 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001645 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001646 return false;
1647}
1648
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001649ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001650ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001651 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001652 if (DCMIt == DetectionContextMap.end())
1653 return nullptr;
1654 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001655}
1656
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001657const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1658 const DetectionContext *DC = getDetectionContext(R);
1659 return DC ? &DC->Log : nullptr;
1660}
1661
Tobias Grosser75805372011-04-29 06:27:02 +00001662void polly::ScopDetection::verifyRegion(const Region &R) const {
1663 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001664
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001665 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001666 isValidRegion(Context);
1667}
1668
1669void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001670 if (!VerifyScops)
1671 return;
1672
Tobias Grosser26108892014-04-02 20:18:19 +00001673 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001674 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001675}
1676
1677void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001678 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001679 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001680 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001681 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001682 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001683 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001684 AU.setPreservesAll();
1685}
1686
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001687void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001688 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001689 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001690
1691 OS << "\n";
1692}
1693
1694void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001695 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001696 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001697
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001698 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001699}
1700
1701char ScopDetection::ID = 0;
1702
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001703Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1704
Tobias Grosser73600b82011-10-08 00:30:40 +00001705INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1706 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001707 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001708INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001709INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001710INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001711INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001712INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001713INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1714 "Polly - Detect static control parts (SCoPs)", false, false)