blob: 5809b442a85ce5d3bda9967e16dd1ff6c269201c [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"
Matt Arsenault8ca36812014-07-19 18:40:17 +000057#include "llvm/Analysis/PostDominators.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 Grosser75805372011-04-29 06:27:02 +0000224
Tobias Grosser8519f892013-12-18 10:49:53 +0000225class DiagnosticScopFound : public DiagnosticInfo {
226private:
227 static int PluginDiagnosticKind;
228
229 Function &F;
230 std::string FileName;
231 unsigned EntryLine, ExitLine;
232
233public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000234 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
235 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000236 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000237 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000238
239 virtual void print(DiagnosticPrinter &DP) const;
240
241 static bool classof(const DiagnosticInfo *DI) {
242 return DI->getKind() == PluginDiagnosticKind;
243 }
244};
245
Tobias Grosserdb6db502016-04-01 07:15:19 +0000246int DiagnosticScopFound::PluginDiagnosticKind =
247 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000248
Tobias Grosser8519f892013-12-18 10:49:53 +0000249void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000250 DP << "Polly detected an optimizable loop region (scop) in function '" << F
251 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000252
253 if (FileName.empty()) {
254 DP << "Scop location is unknown. Compile with debug info "
255 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000256 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000257 }
258
259 DP << FileName << ":" << EntryLine << ": Start of scop\n";
260 DP << FileName << ":" << ExitLine << ": End of scop";
261}
262
Tobias Grosser75805372011-04-29 06:27:02 +0000263//===----------------------------------------------------------------------===//
264// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000265
Johannes Doerfertb164c792014-09-18 11:17:17 +0000266ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000267 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000268 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000269 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000270}
271
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000272template <class RR, typename... Args>
273inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
274 Args &&... Arguments) const {
275
276 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000277 RejectLog &Log = Context.Log;
278 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000279
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000280 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000281 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000282
283 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000284 DEBUG(dbgs() << "\n");
285 } else {
286 assert(!Assert && "Verification of detected scop failed");
287 }
288
289 return false;
290}
291
Tobias Grossera1689932014-02-18 18:49:49 +0000292bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
293 if (!ValidRegions.count(&R))
294 return false;
295
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000296 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000297 DetectionContextMap.erase(getBBPairForRegion(&R));
298 const auto &It = DetectionContextMap.insert(std::make_pair(
299 getBBPairForRegion(&R),
300 DetectionContext(const_cast<Region &>(R), *AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000301 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000302 return isValidRegion(Context);
303 }
Tobias Grossera1689932014-02-18 18:49:49 +0000304
305 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000306}
307
Tobias Grosser4f129a62011-10-08 00:30:55 +0000308std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000309 // Get the first error we found. Even in keep-going mode, this is the first
310 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000311 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000312
313 // This can happen when we marked a region invalid, but didn't track
314 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000315 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000316 return "";
317
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000318 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000319 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000320}
321
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000322bool ScopDetection::addOverApproximatedRegion(Region *AR,
323 DetectionContext &Context) const {
324
325 // If we already know about Ar we can exit.
326 if (!Context.NonAffineSubRegionSet.insert(AR))
327 return true;
328
329 // All loops in the region have to be overapproximated too if there
330 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000331
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000332 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000333 Loop *L = LI->getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000334 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000335 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000336 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000337
338 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000339}
340
Johannes Doerfert09e36972015-10-07 20:17:36 +0000341bool ScopDetection::onlyValidRequiredInvariantLoads(
342 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
343 Region &CurRegion = Context.CurRegion;
344
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000345 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
346 return false;
347
Johannes Doerfert09e36972015-10-07 20:17:36 +0000348 for (LoadInst *Load : RequiredILS)
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000349 if (!isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000350 return false;
351
352 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
353
354 return true;
355}
356
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000357bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
358 Loop *Scope) const {
359 SetVector<Value *> Values;
360 findValues(S0, *SE, Values);
361 if (S1)
362 findValues(S1, *SE, Values);
363
364 SmallPtrSet<Value *, 8> PtrVals;
365 for (auto *V : Values) {
366 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
367 V = P2I->getOperand(0);
368
369 if (!V->getType()->isPointerTy())
370 continue;
371
372 auto *PtrSCEV = SE->getSCEVAtScope(V, Scope);
373 if (isa<SCEVConstant>(PtrSCEV))
374 continue;
375
376 auto *BasePtr = dyn_cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
377 if (!BasePtr)
378 return true;
379
380 auto *BasePtrVal = BasePtr->getValue();
381 if (PtrVals.insert(BasePtrVal).second) {
382 for (auto *PtrVal : PtrVals)
383 if (PtrVal != BasePtrVal && !AA->isNoAlias(PtrVal, BasePtrVal))
384 return true;
385 }
386 }
387
388 return false;
389}
390
Michael Kruse09eb4452016-03-03 22:10:47 +0000391bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000392 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000393
394 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000395 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000396 return false;
397
398 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
399 return false;
400
401 return true;
402}
403
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000404bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000405 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000406 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000407 Loop *L = LI->getLoopFor(&BB);
408 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000409
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000410 if (IsLoopBranch && L->isLoopLatch(&BB))
411 return false;
412
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000413 // Check for invalid usage of different pointers in one expression.
414 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
415 return false;
416
Michael Kruse09eb4452016-03-03 22:10:47 +0000417 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000418 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000419
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000420 if (AllowNonAffineSubRegions &&
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000421 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
422 return true;
423
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000424 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
425 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000426}
427
428bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000429 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000430 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000431
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000432 // Constant integer conditions are always affine.
433 if (isa<ConstantInt>(Condition))
434 return true;
435
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000436 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
437 auto Opcode = BinOp->getOpcode();
438 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
439 Value *Op0 = BinOp->getOperand(0);
440 Value *Op1 = BinOp->getOperand(1);
441 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
442 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
443 }
444 }
445
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000446 // Non constant conditions of branches need to be ICmpInst.
447 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000448 if (!IsLoopBranch && AllowNonAffineSubRegions &&
449 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
450 return true;
451 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000452 }
Tobias Grosser75805372011-04-29 06:27:02 +0000453
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000454 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000455
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000456 // Are both operands of the ICmp affine?
457 if (isa<UndefValue>(ICmp->getOperand(0)) ||
458 isa<UndefValue>(ICmp->getOperand(1)))
459 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000460
Tobias Grossera2f8fa32016-11-13 19:27:04 +0000461 Loop *L = LI->getLoopFor(&BB);
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000462 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
463 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000464
Johannes Doerfertbda81432016-12-02 17:55:41 +0000465 // If unsigned operations are not allowed try to approximate the region.
466 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
467 return !IsLoopBranch && AllowNonAffineSubRegions &&
468 addOverApproximatedRegion(RI->getRegionFor(&BB), Context);
469
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000470 // Check for invalid usage of different pointers in one expression.
471 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
472 involvesMultiplePtrs(RHS, nullptr, L))
473 return false;
474
475 // Check for invalid usage of different pointers in a relational comparison.
476 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
477 return false;
478
Michael Kruse09eb4452016-03-03 22:10:47 +0000479 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000480 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000481
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000482 if (!IsLoopBranch && AllowNonAffineSubRegions &&
483 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
484 return true;
485
486 if (IsLoopBranch)
487 return false;
488
489 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
490 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000491}
492
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000493bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000494 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000495 DetectionContext &Context) const {
496 Region &CurRegion = Context.CurRegion;
497
498 TerminatorInst *TI = BB.getTerminator();
499
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000500 if (AllowUnreachable && isa<UnreachableInst>(TI))
501 return true;
502
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000503 // Return instructions are only valid if the region is the top level region.
504 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
505 return true;
506
507 Value *Condition = getConditionFromTerminator(TI);
508
509 if (!Condition)
510 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
511
512 // UndefValue is not allowed as condition.
513 if (isa<UndefValue>(Condition))
514 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
515
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000516 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000517 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000518
519 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
520 assert(SI && "Terminator was neither branch nor switch");
521
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000522 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000523}
524
Johannes Doerfertcea61932016-02-21 19:13:19 +0000525bool ScopDetection::isValidCallInst(CallInst &CI,
526 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000527 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000528 return false;
529
530 if (CI.doesNotAccessMemory())
531 return true;
532
Johannes Doerfertcea61932016-02-21 19:13:19 +0000533 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000534 if (isValidIntrinsicInst(*II, Context))
535 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000536
Tobias Grosser75805372011-04-29 06:27:02 +0000537 Function *CalledFunction = CI.getCalledFunction();
538
539 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000540 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000541 return false;
542
Tobias Grosser898a6362016-03-23 06:40:15 +0000543 if (AllowModrefCall) {
544 switch (AA->getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000545 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000546 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000547 case FMRB_DoesNotAccessMemory:
548 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000549 // Implicitly disable delinearization since we have an unknown
550 // accesses with an unknown access function.
551 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000552 Context.AST.add(&CI);
553 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000554 case FMRB_OnlyReadsArgumentPointees:
555 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000556 for (const auto &Arg : CI.arg_operands()) {
557 if (!Arg->getType()->isPointerTy())
558 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000559
Tobias Grosser898a6362016-03-23 06:40:15 +0000560 // Bail if a pointer argument has a base address not known to
561 // ScalarEvolution. Note that a zero pointer is acceptable.
562 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
563 if (ArgSCEV->isZero())
564 continue;
565
566 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
567 if (!BP)
568 return false;
569
570 // Implicitly disable delinearization since we have an unknown
571 // accesses with an unknown access function.
572 Context.HasUnknownAccess = true;
573 }
574
575 Context.AST.add(&CI);
576 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000577 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000578 case FMRB_OnlyAccessesInaccessibleMem:
579 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000580 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000581 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000582 }
583
Johannes Doerfertcea61932016-02-21 19:13:19 +0000584 return false;
585}
586
587bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
588 DetectionContext &Context) const {
589 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000590 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000591
Johannes Doerfertcea61932016-02-21 19:13:19 +0000592 // The closest loop surrounding the call instruction.
593 Loop *L = LI->getLoopFor(II.getParent());
594
595 // The access function and base pointer for memory intrinsics.
596 const SCEV *AF;
597 const SCEVUnknown *BP;
598
599 switch (II.getIntrinsicID()) {
600 // Memory intrinsics that can be represented are supported.
601 case llvm::Intrinsic::memmove:
602 case llvm::Intrinsic::memcpy:
603 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000604 if (!AF->isZero()) {
605 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
606 // Bail if the source pointer is not valid.
607 if (!isValidAccess(&II, AF, BP, Context))
608 return false;
609 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000610 // Fall through
611 case llvm::Intrinsic::memset:
612 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000613 if (!AF->isZero()) {
614 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
615 // Bail if the destination pointer is not valid.
616 if (!isValidAccess(&II, AF, BP, Context))
617 return false;
618 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000619
620 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000621 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000622 Context))
623 return false;
624
625 return true;
626 default:
627 break;
628 }
629
Tobias Grosser75805372011-04-29 06:27:02 +0000630 return false;
631}
632
Tobias Grosser458fb782014-01-28 12:58:58 +0000633bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
634 // A reference to function argument or constant value is invariant.
635 if (isa<Argument>(Val) || isa<Constant>(Val))
636 return true;
637
638 const Instruction *I = dyn_cast<Instruction>(&Val);
639 if (!I)
640 return false;
641
642 if (!Reg.contains(I))
643 return true;
644
645 if (I->mayHaveSideEffects())
646 return false;
647
Johannes Doerfertfbb63b82016-04-09 21:57:13 +0000648 if (isa<SelectInst>(I))
649 return false;
650
Tobias Grosser458fb782014-01-28 12:58:58 +0000651 // When Val is a Phi node, it is likely not invariant. We do not check whether
652 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000653 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000654 if (isa<PHINode>(*I))
655 return false;
656
Tobias Grosser26108892014-04-02 20:18:19 +0000657 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000658 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000659 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000660
Tobias Grosser458fb782014-01-28 12:58:58 +0000661 return true;
662}
663
Tobias Grosserc80d6972016-09-02 06:33:33 +0000664/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000665/// register the '...' components.
666///
667/// Array access expressions as they are generated by gfortran contain smax(0,
668/// size) expressions that confuse the 'normal' delinearization algorithm.
669/// However, if we extract such expressions before the normal delinearization
670/// takes place they can actually help to identify array size expressions in
671/// fortran accesses. For the subsequently following delinearization the smax(0,
672/// size) component can be replaced by just 'size'. This is correct as we will
673/// always add and verify the assumption that for all subscript expressions
674/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
675/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000676class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000677public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000678 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
679 std::vector<const SCEV *> *Terms = nullptr) {
680 SCEVRemoveMax Rewriter(SE, Terms);
681 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000682 }
683
684 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000685 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000686
687 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000688 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000689 auto Res = visit(Expr->getOperand(1));
690 if (Terms)
691 (*Terms).push_back(Res);
692 return Res;
693 }
694
695 return Expr;
696 }
697
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000698private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000699 std::vector<const SCEV *> *Terms;
700};
701
Tobias Grosserd68ba422015-11-24 05:00:36 +0000702SmallVector<const SCEV *, 4>
703ScopDetection::getDelinearizationTerms(DetectionContext &Context,
704 const SCEVUnknown *BasePointer) const {
705 SmallVector<const SCEV *, 4> Terms;
706 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000707 std::vector<const SCEV *> MaxTerms;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000708 SCEVRemoveMax::rewrite(Pair.second, *SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000709 if (MaxTerms.size() > 0) {
710 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
711 continue;
712 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000713 // In case the outermost expression is a plain add, we check if any of its
714 // terms has the form 4 * %inst * %param * %param ..., aka a term that
715 // contains a product between a parameter and an instruction that is
716 // inside the scop. Such instructions, if allowed at all, are instructions
717 // SCEV can not represent, but Polly is still looking through. As a
718 // result, these instructions can depend on induction variables and are
719 // most likely no array sizes. However, terms that are multiplied with
720 // them are likely candidates for array sizes.
721 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
722 for (auto Op : AF->operands()) {
723 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
724 SE->collectParametricTerms(AF2, Terms);
725 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
726 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000727
Tobias Grosserd68ba422015-11-24 05:00:36 +0000728 for (auto *MulOp : AF2->operands()) {
729 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
730 Operands.push_back(Const);
731 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
732 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
733 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000734 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000735
736 } else {
737 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000738 }
739 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000740 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000741 if (Operands.size())
742 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000743 }
744 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000745 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000746 if (Terms.empty())
747 SE->collectParametricTerms(Pair.second, Terms);
748 }
749 return Terms;
750}
Sebastian Pope8863b82014-05-12 19:02:02 +0000751
Tobias Grosserd68ba422015-11-24 05:00:36 +0000752bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
753 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000754 const SCEVUnknown *BasePointer,
755 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000756 Value *BaseValue = BasePointer->getValue();
757 Region &CurRegion = Context.CurRegion;
758 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000759 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000760 Sizes.clear();
761 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000762 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000763 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
764 auto *V = dyn_cast<Value>(Unknown->getValue());
765 if (auto *Load = dyn_cast<LoadInst>(V)) {
766 if (Context.CurRegion.contains(Load) &&
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000767 isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000768 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000769 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000770 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000771 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000772 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000773 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000774 Context, /*Assert=*/true, DelinearizedSize,
775 Context.Accesses[BasePointer].front().first, BaseValue);
776 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000777
Tobias Grosserd68ba422015-11-24 05:00:36 +0000778 // No array shape derived.
779 if (Sizes.empty()) {
780 if (AllowNonAffine)
781 return true;
782
Tobias Grosser230acc42014-09-13 14:47:55 +0000783 for (const auto &Pair : Context.Accesses[BasePointer]) {
784 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000785 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000786
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000787 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000788 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
789 BaseValue);
790 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000791 return false;
792 }
793 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000794 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000795 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000796 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000797}
798
Tobias Grosserd68ba422015-11-24 05:00:36 +0000799// We first store the resulting memory accesses in TempMemoryAccesses. Only
800// if the access functions for all memory accesses have been successfully
801// delinearized we continue. Otherwise, we either report a failure or, if
802// non-affine accesses are allowed, we drop the information. In case the
803// information is dropped the memory accesses need to be overapproximated
804// when translated to a polyhedral representation.
805bool ScopDetection::computeAccessFunctions(
806 DetectionContext &Context, const SCEVUnknown *BasePointer,
807 std::shared_ptr<ArrayShape> Shape) const {
808 Value *BaseValue = BasePointer->getValue();
809 bool BasePtrHasNonAffine = false;
810 MapInsnToMemAcc TempMemoryAccesses;
811 for (const auto &Pair : Context.Accesses[BasePointer]) {
812 const Instruction *Insn = Pair.first;
813 auto *AF = Pair.second;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000814 AF = SCEVRemoveMax::rewrite(AF, *SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000815 bool IsNonAffine = false;
816 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
817 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000818 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000819
820 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000821 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000822 Acc->DelinearizedSubscripts.push_back(Pair.second);
823 else
824 IsNonAffine = true;
825 } else {
826 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
827 Shape->DelinearizedSizes);
828 if (Acc->DelinearizedSubscripts.size() == 0)
829 IsNonAffine = true;
830 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000831 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000832 IsNonAffine = true;
833 }
834
835 // (Possibly) report non affine access
836 if (IsNonAffine) {
837 BasePtrHasNonAffine = true;
838 if (!AllowNonAffine)
839 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
840 Insn, BaseValue);
841 if (!KeepGoing && !AllowNonAffine)
842 return false;
843 }
844 }
845
846 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000847 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
848 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000849
850 return true;
851}
852
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000853bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
854 const SCEVUnknown *BasePointer,
855 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000856 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
857
858 auto Terms = getDelinearizationTerms(Context, BasePointer);
859
860 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
861 Context.ElementSize[BasePointer]);
862
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000863 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
864 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000865 return false;
866
867 return computeAccessFunctions(Context, BasePointer, Shape);
868}
869
870bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000871 // TODO: If we have an unknown access and other non-affine accesses we do
872 // not try to delinearize them for now.
873 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
874 return AllowNonAffine;
875
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000876 for (auto &Pair : Context.NonAffineAccesses) {
877 auto *BasePointer = Pair.first;
878 auto *Scope = Pair.second;
879 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000880 if (KeepGoing)
881 continue;
882 else
883 return false;
884 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000885 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000886 return true;
887}
888
Johannes Doerfertcea61932016-02-21 19:13:19 +0000889bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
890 const SCEVUnknown *BP,
891 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000892
Johannes Doerfertcea61932016-02-21 19:13:19 +0000893 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000894 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000895
Johannes Doerfertcea61932016-02-21 19:13:19 +0000896 auto *BV = BP->getValue();
897 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000898 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000899
Johannes Doerfertcea61932016-02-21 19:13:19 +0000900 // FIXME: Think about allowing IntToPtrInst
901 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
902 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
903
Tobias Grosser458fb782014-01-28 12:58:58 +0000904 // Check that the base address of the access is invariant in the current
905 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000906 if (!isInvariant(*BV, Context.CurRegion))
907 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000908
Johannes Doerfertcea61932016-02-21 19:13:19 +0000909 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000910
Johannes Doerfertcea61932016-02-21 19:13:19 +0000911 const SCEV *Size;
912 if (!isa<MemIntrinsic>(Inst)) {
913 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000914 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000915 auto *SizeTy =
916 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
917 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000918 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000919
Johannes Doerfertcea61932016-02-21 19:13:19 +0000920 if (Context.ElementSize[BP]) {
921 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
922 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
923 Inst, BV);
924
925 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
926 } else {
927 Context.ElementSize[BP] = Size;
928 }
929
930 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000931 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000932 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000933 for (const Loop *L : Loops)
934 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000935 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000936
Michael Kruse09eb4452016-03-03 22:10:47 +0000937 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000938 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000939 // Do not try to delinearize memory intrinsics and force them to be affine.
940 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
941 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
942 BV);
943 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
944 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000945
Johannes Doerfertcea61932016-02-21 19:13:19 +0000946 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000947 Context.NonAffineAccesses.insert(
948 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000949 } else if (!AllowNonAffine && !IsAffine) {
950 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
951 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000952 }
Tobias Grosser75805372011-04-29 06:27:02 +0000953
Tobias Grosser1eedb672014-09-24 21:04:29 +0000954 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000955 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000956
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000957 // Check if the base pointer of the memory access does alias with
958 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000959 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000960 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000961 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000962 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000963
Tobias Grosser1eedb672014-09-24 21:04:29 +0000964 if (!AS.isMustAlias()) {
965 if (PollyUseRuntimeAliasChecks) {
966 bool CanBuildRunTimeCheck = true;
967 // The run-time alias check places code that involves the base pointer at
968 // the beginning of the SCoP. This breaks if the base pointer is defined
969 // inside the scop. Hence, we can only create a run-time check if we are
970 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000971 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000972 for (const auto &Ptr : AS) {
973 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000974 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000975 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000976 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE, *DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000977 Context.RequiredILS.insert(Load);
978 continue;
979 }
980
Tobias Grosser1eedb672014-09-24 21:04:29 +0000981 CanBuildRunTimeCheck = false;
982 break;
983 }
984 }
985
986 if (CanBuildRunTimeCheck)
987 return true;
988 }
Michael Kruse70131d32016-01-27 17:09:17 +0000989 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000990 }
Tobias Grosser75805372011-04-29 06:27:02 +0000991
992 return true;
993}
994
Johannes Doerfertcea61932016-02-21 19:13:19 +0000995bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
996 DetectionContext &Context) const {
997 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000998 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000999 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
1000 const SCEVUnknown *BasePointer;
1001
1002 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
1003
1004 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1005}
1006
Tobias Grosser75805372011-04-29 06:27:02 +00001007bool ScopDetection::isValidInstruction(Instruction &Inst,
1008 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001009 for (auto &Op : Inst.operands()) {
1010 auto *OpInst = dyn_cast<Instruction>(&Op);
1011
1012 if (!OpInst)
1013 continue;
1014
1015 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
1016 return false;
1017 }
1018
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001019 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1020 return false;
1021
Tobias Grosser75805372011-04-29 06:27:02 +00001022 // We only check the call instruction but not invoke instruction.
1023 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001024 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001025 return true;
1026
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001027 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001028 }
1029
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001030 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001031 if (!isa<AllocaInst>(Inst))
1032 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001033
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001034 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001035 }
1036
1037 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001038 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001039 Context.hasStores |= isa<StoreInst>(MemInst);
1040 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001041 if (!MemInst.isSimple())
1042 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1043 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001044
Michael Kruse70131d32016-01-27 17:09:17 +00001045 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001046 }
Tobias Grosser75805372011-04-29 06:27:02 +00001047
1048 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001049 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001050}
1051
Tobias Grosser349d1c32016-09-20 17:05:22 +00001052/// Check whether @p L has exiting blocks.
1053///
1054/// @param L The loop of interest
1055///
1056/// @return True if the loop has exiting blocks, false otherwise.
1057static bool hasExitingBlocks(Loop *L) {
1058 SmallVector<BasicBlock *, 4> ExitingBlocks;
1059 L->getExitingBlocks(ExitingBlocks);
1060 return !ExitingBlocks.empty();
1061}
1062
Johannes Doerfertd020b772015-08-27 06:53:52 +00001063bool ScopDetection::canUseISLTripCount(Loop *L,
1064 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001065 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1066 // need to overapproximate it as a boxed loop.
1067 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001068 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001069 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001070 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001071 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001072 return false;
1073 }
1074
Johannes Doerfertd020b772015-08-27 06:53:52 +00001075 // We can use ISL to compute the trip count of L.
1076 return true;
1077}
1078
Tobias Grosser75805372011-04-29 06:27:02 +00001079bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001080 // Loops that contain part but not all of the blocks of a region cannot be
1081 // handled by the schedule generation. Such loop constructs can happen
1082 // because a region can contain BBs that have no path to the exit block
1083 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1084 // loop.
1085 //
1086 // _______________
1087 // | Loop Header | <-----------.
1088 // --------------- |
1089 // | |
1090 // _______________ ______________
1091 // | RegionEntry |-----> | RegionExit |----->
1092 // --------------- --------------
1093 // |
1094 // _______________
1095 // | EndlessLoop | <--.
1096 // --------------- |
1097 // | |
1098 // \------------/
1099 //
1100 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1101 // neither entirely contained in the region RegionEntry->RegionExit
1102 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1103 // in the loop.
1104 // The block EndlessLoop is contained in the region because Region::contains
1105 // tests whether it is not dominated by RegionExit. This is probably to not
1106 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1107 // end can also be formed by an UnreachableInst. This case is already caught
1108 // by isErrorBlock(). We hence only have to reject endless loops here.
1109 if (!hasExitingBlocks(L))
1110 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1111
Johannes Doerfertf61df692015-10-04 14:56:08 +00001112 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001113 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001114
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001115 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001116 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001117 while (R != &Context.CurRegion && !R->contains(L))
1118 R = R->getParent();
1119
1120 if (addOverApproximatedRegion(R, Context))
1121 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001122 }
Tobias Grosser75805372011-04-29 06:27:02 +00001123
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001124 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001125 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001126}
1127
Tobias Grosserc80d6972016-09-02 06:33:33 +00001128/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001129/// count that is not known to be less than @MinProfitableTrips.
1130ScopDetection::LoopStats
1131ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
1132 unsigned MinProfitableTrips) const {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001133 auto *TripCount = SE.getBackedgeTakenCount(L);
1134
Tobias Grosserb45ae562016-11-26 07:37:46 +00001135 int NumLoops = 1;
1136 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001137 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001138 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001139 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1140 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001141
Tobias Grosserb45ae562016-11-26 07:37:46 +00001142 for (auto &SubLoop : *L) {
1143 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1144 NumLoops += Stats.NumLoops;
1145 MaxLoopDepth += std::max(MaxLoopDepth, Stats.MaxDepth + 1);
1146 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001147
Tobias Grosserb45ae562016-11-26 07:37:46 +00001148 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001149}
1150
Tobias Grosserb45ae562016-11-26 07:37:46 +00001151ScopDetection::LoopStats
1152ScopDetection::countBeneficialLoops(Region *R,
1153 unsigned MinProfitableTrips) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001154 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001155 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001156
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001157 auto L = LI->getLoopFor(R->getEntry());
1158 L = L ? R->outermostLoopInRegion(L) : nullptr;
1159 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001160
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001161 auto SubLoops =
1162 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1163
1164 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001165 if (R->contains(SubLoop)) {
1166 LoopStats Stats =
1167 countBeneficialSubLoops(SubLoop, *SE, MinProfitableTrips);
1168 LoopNum += Stats.NumLoops;
1169 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1170 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001171
Tobias Grosserb45ae562016-11-26 07:37:46 +00001172 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001173}
1174
Tobias Grosser75805372011-04-29 06:27:02 +00001175Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001176 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001177 std::unique_ptr<Region> LastValidRegion;
1178 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001179
1180 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1181
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001182 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001183 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001184 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001185 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1186 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001187 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001188 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001189
Johannes Doerfert717b8662015-09-08 21:44:27 +00001190 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001191 // If the exit is valid check all blocks
1192 // - if true, a valid region was found => store it + keep expanding
1193 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001194 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1195 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001196 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001197 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001198 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001199
Tobias Grosserd7e58642013-04-10 06:55:45 +00001200 // Store this region, because it is the greatest valid (encountered so
1201 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001202 if (LastValidRegion) {
1203 removeCachedResults(*LastValidRegion);
1204 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1205 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001206 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001207
1208 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001209 ExpandedRegion =
1210 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001211
1212 } else {
1213 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001214 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001215 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001216 ExpandedRegion =
1217 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001218 }
Tobias Grosser75805372011-04-29 06:27:02 +00001219 }
1220
Tobias Grosser378a9f22013-11-16 19:34:11 +00001221 DEBUG({
1222 if (LastValidRegion)
1223 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1224 else
1225 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1226 });
Tobias Grosser75805372011-04-29 06:27:02 +00001227
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001228 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001229}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001230static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001231 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001232 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001233 return false;
1234
1235 return true;
1236}
Tobias Grosser75805372011-04-29 06:27:02 +00001237
Tobias Grosserb45ae562016-11-26 07:37:46 +00001238void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001239 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001240 if (ValidRegions.count(SubRegion.get())) {
1241 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001242 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001243 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001244 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001245}
1246
Johannes Doerferte46925f2015-10-01 10:59:14 +00001247void ScopDetection::removeCachedResults(const Region &R) {
1248 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001249}
1250
Tobias Grosser75805372011-04-29 06:27:02 +00001251void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001252 const auto &It = DetectionContextMap.insert(std::make_pair(
1253 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001254 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001255
1256 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001257 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001258 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001259 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001260 RegionIsValid = isValidRegion(Context);
1261
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001262 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001263
Johannes Doerferte46925f2015-10-01 10:59:14 +00001264 if (HasErrors) {
1265 removeCachedResults(R);
1266 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001267 ValidRegions.insert(&R);
1268 return;
1269 }
1270
David Blaikieb035f6d2014-04-15 18:45:27 +00001271 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001272 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001273
1274 // Try to expand regions.
1275 //
1276 // As the region tree normally only contains canonical regions, non canonical
1277 // regions that form a Scop are not found. Therefore, those non canonical
1278 // regions are checked by expanding the canonical ones.
1279
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001280 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001281
David Blaikieb035f6d2014-04-15 18:45:27 +00001282 for (auto &SubRegion : R)
1283 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001284
Tobias Grosser26108892014-04-02 20:18:19 +00001285 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001286 // Skip invalid regions. Regions may become invalid, if they are element of
1287 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001288 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001289 continue;
1290
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001291 // Skip regions that had errors.
1292 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1293 if (HadErrors)
1294 continue;
1295
Tobias Grosser75805372011-04-29 06:27:02 +00001296 Region *ExpandedR = expandRegion(*CurrentRegion);
1297
1298 if (!ExpandedR)
1299 continue;
1300
1301 R.addSubRegion(ExpandedR, true);
1302 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001303 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001304 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001305 }
1306}
1307
1308bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001309 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001310
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001311 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001312 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001313 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1314 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001315 return false;
1316 }
1317
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001318 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001319 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1320
1321 // Also check exception blocks (and possibly register them as non-affine
1322 // regions). Even though exception blocks are not modeled, we use them
1323 // to forward-propagate domain constraints during ScopInfo construction.
1324 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1325 return false;
1326
1327 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001328 continue;
1329
Tobias Grosser1d191902014-03-03 13:13:55 +00001330 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001331 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001332 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001333 }
Tobias Grosser75805372011-04-29 06:27:02 +00001334
Sebastian Pope8863b82014-05-12 19:02:02 +00001335 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001336 return false;
1337
Tobias Grosser75805372011-04-29 06:27:02 +00001338 return true;
1339}
1340
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001341bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1342 int NumLoops) const {
1343 int InstCount = 0;
1344
Tobias Grosserb316dc12016-09-08 14:08:05 +00001345 if (NumLoops == 0)
1346 return false;
1347
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001348 for (auto *BB : Context.CurRegion.blocks())
1349 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001350 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001351
1352 InstCount = InstCount / NumLoops;
1353
1354 return InstCount >= ProfitabilityMinPerLoopInstructions;
1355}
1356
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001357bool ScopDetection::hasPossiblyDistributableLoop(
1358 DetectionContext &Context) const {
1359 for (auto *BB : Context.CurRegion.blocks()) {
1360 auto *L = LI->getLoopFor(BB);
1361 if (!Context.CurRegion.contains(L))
1362 continue;
1363 if (Context.BoxedLoopsSet.count(L))
1364 continue;
1365 unsigned StmtsWithStoresInLoops = 0;
1366 for (auto *LBB : L->blocks()) {
1367 bool MemStore = false;
1368 for (auto &I : *LBB)
1369 MemStore |= isa<StoreInst>(&I);
1370 StmtsWithStoresInLoops += MemStore;
1371 }
1372 return (StmtsWithStoresInLoops > 1);
1373 }
1374 return false;
1375}
1376
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001377bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1378 Region &CurRegion = Context.CurRegion;
1379
1380 if (PollyProcessUnprofitable)
1381 return true;
1382
1383 // We can probably not do a lot on scops that only write or only read
1384 // data.
1385 if (!Context.hasStores || !Context.hasLoads)
1386 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1387
Tobias Grosserb45ae562016-11-26 07:37:46 +00001388 int NumLoops = countBeneficialLoops(&CurRegion, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001389 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001390
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001391 // Scops with at least two loops may allow either loop fusion or tiling and
1392 // are consequently interesting to look at.
1393 if (NumAffineLoops >= 2)
1394 return true;
1395
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001396 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1397 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1398 return true;
1399
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001400 // Scops that contain a loop with a non-trivial amount of computation per
1401 // loop-iteration are interesting as we may be able to parallelize such
1402 // loops. Individual loops that have only a small amount of computation
1403 // per-iteration are performance-wise very fragile as any change to the
1404 // loop induction variables may affect performance. To not cause spurious
1405 // performance regressions, we do not consider such loops.
1406 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1407 return true;
1408
1409 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001410}
1411
Tobias Grosser75805372011-04-29 06:27:02 +00001412bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001413 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001414
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001415 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001416
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001417 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001418 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001419 return false;
1420 }
1421
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001422 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001423 DEBUG({
1424 dbgs() << "Region entry does not match -polly-region-only";
1425 dbgs() << "\n";
1426 });
1427 return false;
1428 }
1429
Tobias Grosserd654c252012-04-10 18:12:19 +00001430 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001431 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001432 if (CurRegion.getEntry() ==
1433 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1434 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001435
Hongbin Zheng94868e62012-04-07 12:29:17 +00001436 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001437 return false;
1438
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001439 DebugLoc DbgLoc;
1440 if (!isReducibleRegion(CurRegion, DbgLoc))
1441 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1442 &CurRegion, DbgLoc);
1443
Tobias Grosser75805372011-04-29 06:27:02 +00001444 DEBUG(dbgs() << "OK\n");
1445 return true;
1446}
1447
Tobias Grosser629109b2016-08-03 12:00:07 +00001448void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001449 F->addFnAttr(PollySkipFnAttr);
1450}
1451
Tobias Grosser75805372011-04-29 06:27:02 +00001452bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001453 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001454}
1455
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001456void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001457 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001458 unsigned LineEntry, LineExit;
1459 std::string FileName;
1460
Tobias Grosser00dc3092014-03-02 12:02:46 +00001461 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001462 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1463 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001464 }
1465}
1466
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001467void ScopDetection::emitMissedRemarks(const Function &F) {
1468 for (auto &DIt : DetectionContextMap) {
1469 auto &DC = DIt.getSecond();
1470 if (DC.Log.hasErrors())
1471 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001472 }
1473}
1474
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001475bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001476 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001477 ///
1478 /// WHITE - Unvisited BB in DFS walk.
1479 /// GREY - BBs which are currently on the DFS stack for processing.
1480 /// BLACK - Visited and completely processed BB.
1481 enum Color { WHITE, GREY, BLACK };
1482
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001483 BasicBlock *REntry = R.getEntry();
1484 BasicBlock *RExit = R.getExit();
1485 // Map to match the color of a BasicBlock during the DFS walk.
1486 DenseMap<const BasicBlock *, Color> BBColorMap;
1487 // Stack keeping track of current BB and index of next child to be processed.
1488 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1489
1490 unsigned AdjacentBlockIndex = 0;
1491 BasicBlock *CurrBB, *SuccBB;
1492 CurrBB = REntry;
1493
1494 // Initialize the map for all BB with WHITE color.
1495 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001496 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001497
1498 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001499 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001500 DFSStack.push(std::make_pair(CurrBB, 0));
1501
1502 while (!DFSStack.empty()) {
1503 // Get next BB on stack to be processed.
1504 CurrBB = DFSStack.top().first;
1505 AdjacentBlockIndex = DFSStack.top().second;
1506 DFSStack.pop();
1507
1508 // Loop to iterate over the successors of current BB.
1509 const TerminatorInst *TInst = CurrBB->getTerminator();
1510 unsigned NSucc = TInst->getNumSuccessors();
1511 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1512 ++I, ++AdjacentBlockIndex) {
1513 SuccBB = TInst->getSuccessor(I);
1514
1515 // Checks for region exit block and self-loops in BB.
1516 if (SuccBB == RExit || SuccBB == CurrBB)
1517 continue;
1518
1519 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001520 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001521 // Push the current BB and the index of the next child to be visited.
1522 DFSStack.push(std::make_pair(CurrBB, I + 1));
1523 // Push the next BB to be processed.
1524 DFSStack.push(std::make_pair(SuccBB, 0));
1525 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001526 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001527 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001528 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001529 // GREY indicates a loop in the control flow.
1530 // If the destination dominates the source, it is a natural loop
1531 // else, an irreducible control flow in the region is detected.
1532 if (!DT->dominates(SuccBB, CurrBB)) {
1533 // Get debug info of instruction which causes irregular control flow.
1534 DbgLoc = TInst->getDebugLoc();
1535 return false;
1536 }
1537 }
1538 }
1539
1540 // If all children of current BB have been processed,
1541 // then mark that BB as fully processed.
1542 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001543 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001544 }
1545
1546 return true;
1547}
1548
Tobias Grosserb45ae562016-11-26 07:37:46 +00001549void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1550 bool OnlyProfitable) {
1551 if (!OnlyProfitable) {
1552 NumLoopsInScop += Stats.NumLoops;
1553 if (Stats.MaxDepth == 1)
1554 NumScopsDepthOne++;
1555 else if (Stats.MaxDepth == 2)
1556 NumScopsDepthTwo++;
1557 else if (Stats.MaxDepth == 3)
1558 NumScopsDepthThree++;
1559 else if (Stats.MaxDepth == 4)
1560 NumScopsDepthFour++;
1561 else if (Stats.MaxDepth == 5)
1562 NumScopsDepthFive++;
1563 else
1564 NumScopsDepthLarger++;
1565 } else {
1566 NumLoopsInProfScop += Stats.NumLoops;
1567 if (Stats.MaxDepth == 1)
1568 NumProfScopsDepthOne++;
1569 else if (Stats.MaxDepth == 2)
1570 NumProfScopsDepthTwo++;
1571 else if (Stats.MaxDepth == 3)
1572 NumProfScopsDepthThree++;
1573 else if (Stats.MaxDepth == 4)
1574 NumProfScopsDepthFour++;
1575 else if (Stats.MaxDepth == 5)
1576 NumProfScopsDepthFive++;
1577 else
1578 NumProfScopsDepthLarger++;
1579 }
1580}
1581
Tobias Grosser75805372011-04-29 06:27:02 +00001582bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001583 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001584 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001585 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001586 return false;
1587
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001588 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001589 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001590 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001591 Region *TopRegion = RI->getTopLevelRegion();
1592
Tobias Grosser2ff87232011-10-23 11:17:06 +00001593 releaseMemory();
1594
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001595 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001596 return false;
1597
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001598 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001599 return false;
1600
1601 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001602
Tobias Grosserb45ae562016-11-26 07:37:46 +00001603 NumScopRegions += ValidRegions.size();
1604
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001605 // Prune non-profitable regions.
1606 for (auto &DIt : DetectionContextMap) {
1607 auto &DC = DIt.getSecond();
1608 if (DC.Log.hasErrors())
1609 continue;
1610 if (!ValidRegions.count(&DC.CurRegion))
1611 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001612 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, 0);
1613 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
1614 if (isProfitableRegion(DC)) {
1615 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001616 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001617 }
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001618
1619 ValidRegions.remove(&DC.CurRegion);
1620 }
1621
Tobias Grosserb45ae562016-11-26 07:37:46 +00001622 NumProfScopRegions += ValidRegions.size();
1623 NumLoopsOverall += countBeneficialLoops(TopRegion, 0).NumLoops;
1624
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001625 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001626 if (PollyTrackFailures)
1627 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001628
Johannes Doerferta05214f2014-10-15 23:24:28 +00001629 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001630 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001631
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001632 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001633 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001634 return false;
1635}
1636
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001637ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001638ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001639 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001640 if (DCMIt == DetectionContextMap.end())
1641 return nullptr;
1642 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001643}
1644
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001645const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1646 const DetectionContext *DC = getDetectionContext(R);
1647 return DC ? &DC->Log : nullptr;
1648}
1649
Tobias Grosser75805372011-04-29 06:27:02 +00001650void polly::ScopDetection::verifyRegion(const Region &R) const {
1651 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001652
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001653 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001654 isValidRegion(Context);
1655}
1656
1657void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001658 if (!VerifyScops)
1659 return;
1660
Tobias Grosser26108892014-04-02 20:18:19 +00001661 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001662 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001663}
1664
1665void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001666 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001667 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001668 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001669 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001670 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001671 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001672 AU.setPreservesAll();
1673}
1674
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001675void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001676 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001677 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001678
1679 OS << "\n";
1680}
1681
1682void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001683 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001684 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001685
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001686 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001687}
1688
1689char ScopDetection::ID = 0;
1690
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001691Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1692
Tobias Grosser73600b82011-10-08 00:30:40 +00001693INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1694 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001695 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001696INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001697INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001698INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001699INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001700INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001701INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1702 "Polly - Detect static control parts (SCoPs)", false, false)