blob: 60911a7e5b93b22f38a23831322221029a8d1b69 [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)");
221STATISTIC(NumProfScopsDepthLarger, "Number of scops with maximal loop depth 6 "
222 "and larger (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000223
Tobias Grosser8519f892013-12-18 10:49:53 +0000224class DiagnosticScopFound : public DiagnosticInfo {
225private:
226 static int PluginDiagnosticKind;
227
228 Function &F;
229 std::string FileName;
230 unsigned EntryLine, ExitLine;
231
232public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000233 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
234 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000235 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000236 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000237
238 virtual void print(DiagnosticPrinter &DP) const;
239
240 static bool classof(const DiagnosticInfo *DI) {
241 return DI->getKind() == PluginDiagnosticKind;
242 }
243};
244
Tobias Grosserdb6db502016-04-01 07:15:19 +0000245int DiagnosticScopFound::PluginDiagnosticKind =
246 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000247
Tobias Grosser8519f892013-12-18 10:49:53 +0000248void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000249 DP << "Polly detected an optimizable loop region (scop) in function '" << F
250 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000251
252 if (FileName.empty()) {
253 DP << "Scop location is unknown. Compile with debug info "
254 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000255 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000256 }
257
258 DP << FileName << ":" << EntryLine << ": Start of scop\n";
259 DP << FileName << ":" << ExitLine << ": End of scop";
260}
261
Tobias Grosser75805372011-04-29 06:27:02 +0000262//===----------------------------------------------------------------------===//
263// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000264
Johannes Doerfertb164c792014-09-18 11:17:17 +0000265ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000266 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000267 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000268 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000269}
270
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000271template <class RR, typename... Args>
272inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
273 Args &&... Arguments) const {
274
275 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000276 RejectLog &Log = Context.Log;
277 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000278
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000279 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000280 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000281
282 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000283 DEBUG(dbgs() << "\n");
284 } else {
285 assert(!Assert && "Verification of detected scop failed");
286 }
287
288 return false;
289}
290
Tobias Grossera1689932014-02-18 18:49:49 +0000291bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
292 if (!ValidRegions.count(&R))
293 return false;
294
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000295 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000296 DetectionContextMap.erase(getBBPairForRegion(&R));
297 const auto &It = DetectionContextMap.insert(std::make_pair(
298 getBBPairForRegion(&R),
299 DetectionContext(const_cast<Region &>(R), *AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000300 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000301 return isValidRegion(Context);
302 }
Tobias Grossera1689932014-02-18 18:49:49 +0000303
304 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000305}
306
Tobias Grosser4f129a62011-10-08 00:30:55 +0000307std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000308 // Get the first error we found. Even in keep-going mode, this is the first
309 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000310 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000311
312 // This can happen when we marked a region invalid, but didn't track
313 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000314 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000315 return "";
316
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000317 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000318 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000319}
320
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000321bool ScopDetection::addOverApproximatedRegion(Region *AR,
322 DetectionContext &Context) const {
323
324 // If we already know about Ar we can exit.
325 if (!Context.NonAffineSubRegionSet.insert(AR))
326 return true;
327
328 // All loops in the region have to be overapproximated too if there
329 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000330
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000331 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000332 Loop *L = LI->getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000333 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000334 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000335 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000336
337 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000338}
339
Johannes Doerfert09e36972015-10-07 20:17:36 +0000340bool ScopDetection::onlyValidRequiredInvariantLoads(
341 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
342 Region &CurRegion = Context.CurRegion;
343
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000344 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
345 return false;
346
Johannes Doerfert09e36972015-10-07 20:17:36 +0000347 for (LoadInst *Load : RequiredILS)
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000348 if (!isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000349 return false;
350
351 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
352
353 return true;
354}
355
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000356bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
357 Loop *Scope) const {
358 SetVector<Value *> Values;
359 findValues(S0, *SE, Values);
360 if (S1)
361 findValues(S1, *SE, Values);
362
363 SmallPtrSet<Value *, 8> PtrVals;
364 for (auto *V : Values) {
365 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
366 V = P2I->getOperand(0);
367
368 if (!V->getType()->isPointerTy())
369 continue;
370
371 auto *PtrSCEV = SE->getSCEVAtScope(V, Scope);
372 if (isa<SCEVConstant>(PtrSCEV))
373 continue;
374
375 auto *BasePtr = dyn_cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
376 if (!BasePtr)
377 return true;
378
379 auto *BasePtrVal = BasePtr->getValue();
380 if (PtrVals.insert(BasePtrVal).second) {
381 for (auto *PtrVal : PtrVals)
382 if (PtrVal != BasePtrVal && !AA->isNoAlias(PtrVal, BasePtrVal))
383 return true;
384 }
385 }
386
387 return false;
388}
389
Michael Kruse09eb4452016-03-03 22:10:47 +0000390bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000391 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000392
393 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000394 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000395 return false;
396
397 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
398 return false;
399
400 return true;
401}
402
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000403bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000404 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000405 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000406 Loop *L = LI->getLoopFor(&BB);
407 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000408
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000409 if (IsLoopBranch && L->isLoopLatch(&BB))
410 return false;
411
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000412 // Check for invalid usage of different pointers in one expression.
413 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
414 return false;
415
Michael Kruse09eb4452016-03-03 22:10:47 +0000416 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000417 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000418
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000419 if (AllowNonAffineSubRegions &&
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000420 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
421 return true;
422
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000423 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
424 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000425}
426
427bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000428 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000429 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000430
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000431 // Constant integer conditions are always affine.
432 if (isa<ConstantInt>(Condition))
433 return true;
434
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000435 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
436 auto Opcode = BinOp->getOpcode();
437 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
438 Value *Op0 = BinOp->getOperand(0);
439 Value *Op1 = BinOp->getOperand(1);
440 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
441 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
442 }
443 }
444
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000445 // Non constant conditions of branches need to be ICmpInst.
446 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000447 if (!IsLoopBranch && AllowNonAffineSubRegions &&
448 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
449 return true;
450 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000451 }
Tobias Grosser75805372011-04-29 06:27:02 +0000452
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000453 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000454
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000455 // Are both operands of the ICmp affine?
456 if (isa<UndefValue>(ICmp->getOperand(0)) ||
457 isa<UndefValue>(ICmp->getOperand(1)))
458 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000459
Tobias Grossera2f8fa32016-11-13 19:27:04 +0000460 Loop *L = LI->getLoopFor(&BB);
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000461 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
462 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000463
Johannes Doerfertbda81432016-12-02 17:55:41 +0000464 // If unsigned operations are not allowed try to approximate the region.
465 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
466 return !IsLoopBranch && AllowNonAffineSubRegions &&
467 addOverApproximatedRegion(RI->getRegionFor(&BB), Context);
468
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000469 // Check for invalid usage of different pointers in one expression.
470 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
471 involvesMultiplePtrs(RHS, nullptr, L))
472 return false;
473
474 // Check for invalid usage of different pointers in a relational comparison.
475 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
476 return false;
477
Michael Kruse09eb4452016-03-03 22:10:47 +0000478 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000479 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000480
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000481 if (!IsLoopBranch && AllowNonAffineSubRegions &&
482 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
483 return true;
484
485 if (IsLoopBranch)
486 return false;
487
488 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
489 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000490}
491
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000492bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000493 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000494 DetectionContext &Context) const {
495 Region &CurRegion = Context.CurRegion;
496
497 TerminatorInst *TI = BB.getTerminator();
498
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000499 if (AllowUnreachable && isa<UnreachableInst>(TI))
500 return true;
501
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000502 // Return instructions are only valid if the region is the top level region.
503 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
504 return true;
505
506 Value *Condition = getConditionFromTerminator(TI);
507
508 if (!Condition)
509 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
510
511 // UndefValue is not allowed as condition.
512 if (isa<UndefValue>(Condition))
513 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
514
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000515 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000516 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000517
518 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
519 assert(SI && "Terminator was neither branch nor switch");
520
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000521 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000522}
523
Johannes Doerfertcea61932016-02-21 19:13:19 +0000524bool ScopDetection::isValidCallInst(CallInst &CI,
525 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000526 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000527 return false;
528
529 if (CI.doesNotAccessMemory())
530 return true;
531
Johannes Doerfertcea61932016-02-21 19:13:19 +0000532 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000533 if (isValidIntrinsicInst(*II, Context))
534 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000535
Tobias Grosser75805372011-04-29 06:27:02 +0000536 Function *CalledFunction = CI.getCalledFunction();
537
538 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000539 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000540 return false;
541
Tobias Grosser898a6362016-03-23 06:40:15 +0000542 if (AllowModrefCall) {
543 switch (AA->getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000544 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000545 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000546 case FMRB_DoesNotAccessMemory:
547 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000548 // Implicitly disable delinearization since we have an unknown
549 // accesses with an unknown access function.
550 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000551 Context.AST.add(&CI);
552 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000553 case FMRB_OnlyReadsArgumentPointees:
554 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000555 for (const auto &Arg : CI.arg_operands()) {
556 if (!Arg->getType()->isPointerTy())
557 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000558
Tobias Grosser898a6362016-03-23 06:40:15 +0000559 // Bail if a pointer argument has a base address not known to
560 // ScalarEvolution. Note that a zero pointer is acceptable.
561 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
562 if (ArgSCEV->isZero())
563 continue;
564
565 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
566 if (!BP)
567 return false;
568
569 // Implicitly disable delinearization since we have an unknown
570 // accesses with an unknown access function.
571 Context.HasUnknownAccess = true;
572 }
573
574 Context.AST.add(&CI);
575 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000576 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000577 case FMRB_OnlyAccessesInaccessibleMem:
578 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000579 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000580 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000581 }
582
Johannes Doerfertcea61932016-02-21 19:13:19 +0000583 return false;
584}
585
586bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
587 DetectionContext &Context) const {
588 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000589 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000590
Johannes Doerfertcea61932016-02-21 19:13:19 +0000591 // The closest loop surrounding the call instruction.
592 Loop *L = LI->getLoopFor(II.getParent());
593
594 // The access function and base pointer for memory intrinsics.
595 const SCEV *AF;
596 const SCEVUnknown *BP;
597
598 switch (II.getIntrinsicID()) {
599 // Memory intrinsics that can be represented are supported.
600 case llvm::Intrinsic::memmove:
601 case llvm::Intrinsic::memcpy:
602 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000603 if (!AF->isZero()) {
604 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
605 // Bail if the source pointer is not valid.
606 if (!isValidAccess(&II, AF, BP, Context))
607 return false;
608 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000609 // Fall through
610 case llvm::Intrinsic::memset:
611 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000612 if (!AF->isZero()) {
613 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
614 // Bail if the destination pointer is not valid.
615 if (!isValidAccess(&II, AF, BP, Context))
616 return false;
617 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000618
619 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000620 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000621 Context))
622 return false;
623
624 return true;
625 default:
626 break;
627 }
628
Tobias Grosser75805372011-04-29 06:27:02 +0000629 return false;
630}
631
Tobias Grosser458fb782014-01-28 12:58:58 +0000632bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
633 // A reference to function argument or constant value is invariant.
634 if (isa<Argument>(Val) || isa<Constant>(Val))
635 return true;
636
637 const Instruction *I = dyn_cast<Instruction>(&Val);
638 if (!I)
639 return false;
640
641 if (!Reg.contains(I))
642 return true;
643
644 if (I->mayHaveSideEffects())
645 return false;
646
Johannes Doerfertfbb63b82016-04-09 21:57:13 +0000647 if (isa<SelectInst>(I))
648 return false;
649
Tobias Grosser458fb782014-01-28 12:58:58 +0000650 // When Val is a Phi node, it is likely not invariant. We do not check whether
651 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000652 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000653 if (isa<PHINode>(*I))
654 return false;
655
Tobias Grosser26108892014-04-02 20:18:19 +0000656 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000657 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000658 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000659
Tobias Grosser458fb782014-01-28 12:58:58 +0000660 return true;
661}
662
Tobias Grosserc80d6972016-09-02 06:33:33 +0000663/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000664/// register the '...' components.
665///
666/// Array access expressions as they are generated by gfortran contain smax(0,
667/// size) expressions that confuse the 'normal' delinearization algorithm.
668/// However, if we extract such expressions before the normal delinearization
669/// takes place they can actually help to identify array size expressions in
670/// fortran accesses. For the subsequently following delinearization the smax(0,
671/// size) component can be replaced by just 'size'. This is correct as we will
672/// always add and verify the assumption that for all subscript expressions
673/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
674/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000675class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000676public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000677 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
678 std::vector<const SCEV *> *Terms = nullptr) {
679 SCEVRemoveMax Rewriter(SE, Terms);
680 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000681 }
682
683 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000684 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000685
686 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000687 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000688 auto Res = visit(Expr->getOperand(1));
689 if (Terms)
690 (*Terms).push_back(Res);
691 return Res;
692 }
693
694 return Expr;
695 }
696
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000697private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000698 std::vector<const SCEV *> *Terms;
699};
700
Tobias Grosserd68ba422015-11-24 05:00:36 +0000701SmallVector<const SCEV *, 4>
702ScopDetection::getDelinearizationTerms(DetectionContext &Context,
703 const SCEVUnknown *BasePointer) const {
704 SmallVector<const SCEV *, 4> Terms;
705 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000706 std::vector<const SCEV *> MaxTerms;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000707 SCEVRemoveMax::rewrite(Pair.second, *SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000708 if (MaxTerms.size() > 0) {
709 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
710 continue;
711 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000712 // In case the outermost expression is a plain add, we check if any of its
713 // terms has the form 4 * %inst * %param * %param ..., aka a term that
714 // contains a product between a parameter and an instruction that is
715 // inside the scop. Such instructions, if allowed at all, are instructions
716 // SCEV can not represent, but Polly is still looking through. As a
717 // result, these instructions can depend on induction variables and are
718 // most likely no array sizes. However, terms that are multiplied with
719 // them are likely candidates for array sizes.
720 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
721 for (auto Op : AF->operands()) {
722 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
723 SE->collectParametricTerms(AF2, Terms);
724 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
725 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000726
Tobias Grosserd68ba422015-11-24 05:00:36 +0000727 for (auto *MulOp : AF2->operands()) {
728 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
729 Operands.push_back(Const);
730 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
731 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
732 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000733 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000734
735 } else {
736 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000737 }
738 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000739 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000740 if (Operands.size())
741 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000742 }
743 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000744 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000745 if (Terms.empty())
746 SE->collectParametricTerms(Pair.second, Terms);
747 }
748 return Terms;
749}
Sebastian Pope8863b82014-05-12 19:02:02 +0000750
Tobias Grosserd68ba422015-11-24 05:00:36 +0000751bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
752 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000753 const SCEVUnknown *BasePointer,
754 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000755 Value *BaseValue = BasePointer->getValue();
756 Region &CurRegion = Context.CurRegion;
757 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000758 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000759 Sizes.clear();
760 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000761 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000762 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
763 auto *V = dyn_cast<Value>(Unknown->getValue());
764 if (auto *Load = dyn_cast<LoadInst>(V)) {
765 if (Context.CurRegion.contains(Load) &&
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000766 isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000767 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000768 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000769 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000770 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000771 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000772 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000773 Context, /*Assert=*/true, DelinearizedSize,
774 Context.Accesses[BasePointer].front().first, BaseValue);
775 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000776
Tobias Grosserd68ba422015-11-24 05:00:36 +0000777 // No array shape derived.
778 if (Sizes.empty()) {
779 if (AllowNonAffine)
780 return true;
781
Tobias Grosser230acc42014-09-13 14:47:55 +0000782 for (const auto &Pair : Context.Accesses[BasePointer]) {
783 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000784 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000785
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000786 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000787 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
788 BaseValue);
789 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000790 return false;
791 }
792 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000793 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000794 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000795 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000796}
797
Tobias Grosserd68ba422015-11-24 05:00:36 +0000798// We first store the resulting memory accesses in TempMemoryAccesses. Only
799// if the access functions for all memory accesses have been successfully
800// delinearized we continue. Otherwise, we either report a failure or, if
801// non-affine accesses are allowed, we drop the information. In case the
802// information is dropped the memory accesses need to be overapproximated
803// when translated to a polyhedral representation.
804bool ScopDetection::computeAccessFunctions(
805 DetectionContext &Context, const SCEVUnknown *BasePointer,
806 std::shared_ptr<ArrayShape> Shape) const {
807 Value *BaseValue = BasePointer->getValue();
808 bool BasePtrHasNonAffine = false;
809 MapInsnToMemAcc TempMemoryAccesses;
810 for (const auto &Pair : Context.Accesses[BasePointer]) {
811 const Instruction *Insn = Pair.first;
812 auto *AF = Pair.second;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000813 AF = SCEVRemoveMax::rewrite(AF, *SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000814 bool IsNonAffine = false;
815 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
816 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000817 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000818
819 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000820 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000821 Acc->DelinearizedSubscripts.push_back(Pair.second);
822 else
823 IsNonAffine = true;
824 } else {
825 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
826 Shape->DelinearizedSizes);
827 if (Acc->DelinearizedSubscripts.size() == 0)
828 IsNonAffine = true;
829 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000830 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000831 IsNonAffine = true;
832 }
833
834 // (Possibly) report non affine access
835 if (IsNonAffine) {
836 BasePtrHasNonAffine = true;
837 if (!AllowNonAffine)
838 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
839 Insn, BaseValue);
840 if (!KeepGoing && !AllowNonAffine)
841 return false;
842 }
843 }
844
845 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000846 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
847 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000848
849 return true;
850}
851
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000852bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
853 const SCEVUnknown *BasePointer,
854 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000855 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
856
857 auto Terms = getDelinearizationTerms(Context, BasePointer);
858
859 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
860 Context.ElementSize[BasePointer]);
861
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000862 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
863 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000864 return false;
865
866 return computeAccessFunctions(Context, BasePointer, Shape);
867}
868
869bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000870 // TODO: If we have an unknown access and other non-affine accesses we do
871 // not try to delinearize them for now.
872 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
873 return AllowNonAffine;
874
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000875 for (auto &Pair : Context.NonAffineAccesses) {
876 auto *BasePointer = Pair.first;
877 auto *Scope = Pair.second;
878 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000879 if (KeepGoing)
880 continue;
881 else
882 return false;
883 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000884 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000885 return true;
886}
887
Johannes Doerfertcea61932016-02-21 19:13:19 +0000888bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
889 const SCEVUnknown *BP,
890 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000891
Johannes Doerfertcea61932016-02-21 19:13:19 +0000892 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000893 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000894
Johannes Doerfertcea61932016-02-21 19:13:19 +0000895 auto *BV = BP->getValue();
896 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000897 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000898
Johannes Doerfertcea61932016-02-21 19:13:19 +0000899 // FIXME: Think about allowing IntToPtrInst
900 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
901 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
902
Tobias Grosser458fb782014-01-28 12:58:58 +0000903 // Check that the base address of the access is invariant in the current
904 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000905 if (!isInvariant(*BV, Context.CurRegion))
906 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000907
Johannes Doerfertcea61932016-02-21 19:13:19 +0000908 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000909
Johannes Doerfertcea61932016-02-21 19:13:19 +0000910 const SCEV *Size;
911 if (!isa<MemIntrinsic>(Inst)) {
912 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000913 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000914 auto *SizeTy =
915 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
916 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000917 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000918
Johannes Doerfertcea61932016-02-21 19:13:19 +0000919 if (Context.ElementSize[BP]) {
920 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
921 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
922 Inst, BV);
923
924 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
925 } else {
926 Context.ElementSize[BP] = Size;
927 }
928
929 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000930 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000931 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000932 for (const Loop *L : Loops)
933 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000934 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000935
Michael Kruse09eb4452016-03-03 22:10:47 +0000936 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000937 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000938 // Do not try to delinearize memory intrinsics and force them to be affine.
939 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
940 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
941 BV);
942 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
943 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000944
Johannes Doerfertcea61932016-02-21 19:13:19 +0000945 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000946 Context.NonAffineAccesses.insert(
947 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000948 } else if (!AllowNonAffine && !IsAffine) {
949 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
950 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000951 }
Tobias Grosser75805372011-04-29 06:27:02 +0000952
Tobias Grosser1eedb672014-09-24 21:04:29 +0000953 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000954 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000955
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000956 // Check if the base pointer of the memory access does alias with
957 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000958 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000959 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000960 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000961 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000962
Tobias Grosser1eedb672014-09-24 21:04:29 +0000963 if (!AS.isMustAlias()) {
964 if (PollyUseRuntimeAliasChecks) {
965 bool CanBuildRunTimeCheck = true;
966 // The run-time alias check places code that involves the base pointer at
967 // the beginning of the SCoP. This breaks if the base pointer is defined
968 // inside the scop. Hence, we can only create a run-time check if we are
969 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000970 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000971 for (const auto &Ptr : AS) {
972 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000973 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000974 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000975 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE, *DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000976 Context.RequiredILS.insert(Load);
977 continue;
978 }
979
Tobias Grosser1eedb672014-09-24 21:04:29 +0000980 CanBuildRunTimeCheck = false;
981 break;
982 }
983 }
984
985 if (CanBuildRunTimeCheck)
986 return true;
987 }
Michael Kruse70131d32016-01-27 17:09:17 +0000988 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000989 }
Tobias Grosser75805372011-04-29 06:27:02 +0000990
991 return true;
992}
993
Johannes Doerfertcea61932016-02-21 19:13:19 +0000994bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
995 DetectionContext &Context) const {
996 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000997 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000998 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
999 const SCEVUnknown *BasePointer;
1000
1001 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
1002
1003 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1004}
1005
Tobias Grosser75805372011-04-29 06:27:02 +00001006bool ScopDetection::isValidInstruction(Instruction &Inst,
1007 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001008 for (auto &Op : Inst.operands()) {
1009 auto *OpInst = dyn_cast<Instruction>(&Op);
1010
1011 if (!OpInst)
1012 continue;
1013
1014 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
1015 return false;
1016 }
1017
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001018 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1019 return false;
1020
Tobias Grosser75805372011-04-29 06:27:02 +00001021 // We only check the call instruction but not invoke instruction.
1022 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001023 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001024 return true;
1025
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001026 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001027 }
1028
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001029 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001030 if (!isa<AllocaInst>(Inst))
1031 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001032
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001033 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001034 }
1035
1036 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001037 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001038 Context.hasStores |= isa<StoreInst>(MemInst);
1039 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001040 if (!MemInst.isSimple())
1041 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1042 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001043
Michael Kruse70131d32016-01-27 17:09:17 +00001044 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001045 }
Tobias Grosser75805372011-04-29 06:27:02 +00001046
1047 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001048 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001049}
1050
Tobias Grosser349d1c32016-09-20 17:05:22 +00001051/// Check whether @p L has exiting blocks.
1052///
1053/// @param L The loop of interest
1054///
1055/// @return True if the loop has exiting blocks, false otherwise.
1056static bool hasExitingBlocks(Loop *L) {
1057 SmallVector<BasicBlock *, 4> ExitingBlocks;
1058 L->getExitingBlocks(ExitingBlocks);
1059 return !ExitingBlocks.empty();
1060}
1061
Johannes Doerfertd020b772015-08-27 06:53:52 +00001062bool ScopDetection::canUseISLTripCount(Loop *L,
1063 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001064 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1065 // need to overapproximate it as a boxed loop.
1066 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001067 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001068 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001069 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001070 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001071 return false;
1072 }
1073
Johannes Doerfertd020b772015-08-27 06:53:52 +00001074 // We can use ISL to compute the trip count of L.
1075 return true;
1076}
1077
Tobias Grosser75805372011-04-29 06:27:02 +00001078bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001079 // Loops that contain part but not all of the blocks of a region cannot be
1080 // handled by the schedule generation. Such loop constructs can happen
1081 // because a region can contain BBs that have no path to the exit block
1082 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1083 // loop.
1084 //
1085 // _______________
1086 // | Loop Header | <-----------.
1087 // --------------- |
1088 // | |
1089 // _______________ ______________
1090 // | RegionEntry |-----> | RegionExit |----->
1091 // --------------- --------------
1092 // |
1093 // _______________
1094 // | EndlessLoop | <--.
1095 // --------------- |
1096 // | |
1097 // \------------/
1098 //
1099 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1100 // neither entirely contained in the region RegionEntry->RegionExit
1101 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1102 // in the loop.
1103 // The block EndlessLoop is contained in the region because Region::contains
1104 // tests whether it is not dominated by RegionExit. This is probably to not
1105 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1106 // end can also be formed by an UnreachableInst. This case is already caught
1107 // by isErrorBlock(). We hence only have to reject endless loops here.
1108 if (!hasExitingBlocks(L))
1109 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1110
Johannes Doerfertf61df692015-10-04 14:56:08 +00001111 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001112 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001113
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001114 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001115 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001116 while (R != &Context.CurRegion && !R->contains(L))
1117 R = R->getParent();
1118
1119 if (addOverApproximatedRegion(R, Context))
1120 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001121 }
Tobias Grosser75805372011-04-29 06:27:02 +00001122
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001123 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001124 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001125}
1126
Tobias Grosserc80d6972016-09-02 06:33:33 +00001127/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001128/// count that is not known to be less than @MinProfitableTrips.
1129ScopDetection::LoopStats
1130ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
1131 unsigned MinProfitableTrips) const {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001132 auto *TripCount = SE.getBackedgeTakenCount(L);
1133
Tobias Grosserb45ae562016-11-26 07:37:46 +00001134 int NumLoops = 1;
1135 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001136 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001137 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001138 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1139 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001140
Tobias Grosserb45ae562016-11-26 07:37:46 +00001141 for (auto &SubLoop : *L) {
1142 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1143 NumLoops += Stats.NumLoops;
1144 MaxLoopDepth += std::max(MaxLoopDepth, Stats.MaxDepth + 1);
1145 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001146
Tobias Grosserb45ae562016-11-26 07:37:46 +00001147 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001148}
1149
Tobias Grosserb45ae562016-11-26 07:37:46 +00001150ScopDetection::LoopStats
1151ScopDetection::countBeneficialLoops(Region *R,
1152 unsigned MinProfitableTrips) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001153 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001154 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001155
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001156 auto L = LI->getLoopFor(R->getEntry());
1157 L = L ? R->outermostLoopInRegion(L) : nullptr;
1158 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001159
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001160 auto SubLoops =
1161 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1162
1163 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001164 if (R->contains(SubLoop)) {
1165 LoopStats Stats =
1166 countBeneficialSubLoops(SubLoop, *SE, MinProfitableTrips);
1167 LoopNum += Stats.NumLoops;
1168 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1169 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001170
Tobias Grosserb45ae562016-11-26 07:37:46 +00001171 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001172}
1173
Tobias Grosser75805372011-04-29 06:27:02 +00001174Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001175 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001176 std::unique_ptr<Region> LastValidRegion;
1177 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001178
1179 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1180
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001181 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001182 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001183 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001184 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1185 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001186 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001187 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001188
Johannes Doerfert717b8662015-09-08 21:44:27 +00001189 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001190 // If the exit is valid check all blocks
1191 // - if true, a valid region was found => store it + keep expanding
1192 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001193 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1194 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001195 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001196 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001197 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001198
Tobias Grosserd7e58642013-04-10 06:55:45 +00001199 // Store this region, because it is the greatest valid (encountered so
1200 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001201 if (LastValidRegion) {
1202 removeCachedResults(*LastValidRegion);
1203 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1204 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001205 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001206
1207 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001208 ExpandedRegion =
1209 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001210
1211 } else {
1212 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001213 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001214 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001215 ExpandedRegion =
1216 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001217 }
Tobias Grosser75805372011-04-29 06:27:02 +00001218 }
1219
Tobias Grosser378a9f22013-11-16 19:34:11 +00001220 DEBUG({
1221 if (LastValidRegion)
1222 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1223 else
1224 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1225 });
Tobias Grosser75805372011-04-29 06:27:02 +00001226
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001227 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001228}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001229static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001230 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001231 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001232 return false;
1233
1234 return true;
1235}
Tobias Grosser75805372011-04-29 06:27:02 +00001236
Tobias Grosserb45ae562016-11-26 07:37:46 +00001237void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001238 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001239 if (ValidRegions.count(SubRegion.get())) {
1240 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001241 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001242 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001243 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001244}
1245
Johannes Doerferte46925f2015-10-01 10:59:14 +00001246void ScopDetection::removeCachedResults(const Region &R) {
1247 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001248}
1249
Tobias Grosser75805372011-04-29 06:27:02 +00001250void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001251 const auto &It = DetectionContextMap.insert(std::make_pair(
1252 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001253 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001254
1255 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001256 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001257 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001258 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001259 RegionIsValid = isValidRegion(Context);
1260
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001261 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001262
Johannes Doerferte46925f2015-10-01 10:59:14 +00001263 if (HasErrors) {
1264 removeCachedResults(R);
1265 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001266 ValidRegions.insert(&R);
1267 return;
1268 }
1269
David Blaikieb035f6d2014-04-15 18:45:27 +00001270 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001271 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001272
1273 // Try to expand regions.
1274 //
1275 // As the region tree normally only contains canonical regions, non canonical
1276 // regions that form a Scop are not found. Therefore, those non canonical
1277 // regions are checked by expanding the canonical ones.
1278
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001279 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001280
David Blaikieb035f6d2014-04-15 18:45:27 +00001281 for (auto &SubRegion : R)
1282 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001283
Tobias Grosser26108892014-04-02 20:18:19 +00001284 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001285 // Skip invalid regions. Regions may become invalid, if they are element of
1286 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001287 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001288 continue;
1289
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001290 // Skip regions that had errors.
1291 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1292 if (HadErrors)
1293 continue;
1294
Tobias Grosser75805372011-04-29 06:27:02 +00001295 Region *ExpandedR = expandRegion(*CurrentRegion);
1296
1297 if (!ExpandedR)
1298 continue;
1299
1300 R.addSubRegion(ExpandedR, true);
1301 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001302 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001303 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001304 }
1305}
1306
1307bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001308 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001309
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001310 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001311 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001312 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1313 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001314 return false;
1315 }
1316
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001317 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001318 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1319
1320 // Also check exception blocks (and possibly register them as non-affine
1321 // regions). Even though exception blocks are not modeled, we use them
1322 // to forward-propagate domain constraints during ScopInfo construction.
1323 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1324 return false;
1325
1326 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001327 continue;
1328
Tobias Grosser1d191902014-03-03 13:13:55 +00001329 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001330 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001331 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001332 }
Tobias Grosser75805372011-04-29 06:27:02 +00001333
Sebastian Pope8863b82014-05-12 19:02:02 +00001334 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001335 return false;
1336
Tobias Grosser75805372011-04-29 06:27:02 +00001337 return true;
1338}
1339
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001340bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1341 int NumLoops) const {
1342 int InstCount = 0;
1343
Tobias Grosserb316dc12016-09-08 14:08:05 +00001344 if (NumLoops == 0)
1345 return false;
1346
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001347 for (auto *BB : Context.CurRegion.blocks())
1348 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001349 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001350
1351 InstCount = InstCount / NumLoops;
1352
1353 return InstCount >= ProfitabilityMinPerLoopInstructions;
1354}
1355
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001356bool ScopDetection::hasPossiblyDistributableLoop(
1357 DetectionContext &Context) const {
1358 for (auto *BB : Context.CurRegion.blocks()) {
1359 auto *L = LI->getLoopFor(BB);
1360 if (!Context.CurRegion.contains(L))
1361 continue;
1362 if (Context.BoxedLoopsSet.count(L))
1363 continue;
1364 unsigned StmtsWithStoresInLoops = 0;
1365 for (auto *LBB : L->blocks()) {
1366 bool MemStore = false;
1367 for (auto &I : *LBB)
1368 MemStore |= isa<StoreInst>(&I);
1369 StmtsWithStoresInLoops += MemStore;
1370 }
1371 return (StmtsWithStoresInLoops > 1);
1372 }
1373 return false;
1374}
1375
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001376bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1377 Region &CurRegion = Context.CurRegion;
1378
1379 if (PollyProcessUnprofitable)
1380 return true;
1381
1382 // We can probably not do a lot on scops that only write or only read
1383 // data.
1384 if (!Context.hasStores || !Context.hasLoads)
1385 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1386
Tobias Grosserb45ae562016-11-26 07:37:46 +00001387 int NumLoops = countBeneficialLoops(&CurRegion, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001388 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001389
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001390 // Scops with at least two loops may allow either loop fusion or tiling and
1391 // are consequently interesting to look at.
1392 if (NumAffineLoops >= 2)
1393 return true;
1394
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001395 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1396 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1397 return true;
1398
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001399 // Scops that contain a loop with a non-trivial amount of computation per
1400 // loop-iteration are interesting as we may be able to parallelize such
1401 // loops. Individual loops that have only a small amount of computation
1402 // per-iteration are performance-wise very fragile as any change to the
1403 // loop induction variables may affect performance. To not cause spurious
1404 // performance regressions, we do not consider such loops.
1405 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1406 return true;
1407
1408 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001409}
1410
Tobias Grosser75805372011-04-29 06:27:02 +00001411bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001412 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001413
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001414 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001415
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001416 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001417 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001418 return false;
1419 }
1420
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001421 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001422 DEBUG({
1423 dbgs() << "Region entry does not match -polly-region-only";
1424 dbgs() << "\n";
1425 });
1426 return false;
1427 }
1428
Tobias Grosserd654c252012-04-10 18:12:19 +00001429 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001430 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001431 if (CurRegion.getEntry() ==
1432 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1433 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001434
Hongbin Zheng94868e62012-04-07 12:29:17 +00001435 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001436 return false;
1437
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001438 DebugLoc DbgLoc;
1439 if (!isReducibleRegion(CurRegion, DbgLoc))
1440 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1441 &CurRegion, DbgLoc);
1442
Tobias Grosser75805372011-04-29 06:27:02 +00001443 DEBUG(dbgs() << "OK\n");
1444 return true;
1445}
1446
Tobias Grosser629109b2016-08-03 12:00:07 +00001447void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001448 F->addFnAttr(PollySkipFnAttr);
1449}
1450
Tobias Grosser75805372011-04-29 06:27:02 +00001451bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001452 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001453}
1454
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001455void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001456 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001457 unsigned LineEntry, LineExit;
1458 std::string FileName;
1459
Tobias Grosser00dc3092014-03-02 12:02:46 +00001460 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001461 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1462 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001463 }
1464}
1465
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001466void ScopDetection::emitMissedRemarks(const Function &F) {
1467 for (auto &DIt : DetectionContextMap) {
1468 auto &DC = DIt.getSecond();
1469 if (DC.Log.hasErrors())
1470 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001471 }
1472}
1473
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001474bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001475 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001476 ///
1477 /// WHITE - Unvisited BB in DFS walk.
1478 /// GREY - BBs which are currently on the DFS stack for processing.
1479 /// BLACK - Visited and completely processed BB.
1480 enum Color { WHITE, GREY, BLACK };
1481
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001482 BasicBlock *REntry = R.getEntry();
1483 BasicBlock *RExit = R.getExit();
1484 // Map to match the color of a BasicBlock during the DFS walk.
1485 DenseMap<const BasicBlock *, Color> BBColorMap;
1486 // Stack keeping track of current BB and index of next child to be processed.
1487 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1488
1489 unsigned AdjacentBlockIndex = 0;
1490 BasicBlock *CurrBB, *SuccBB;
1491 CurrBB = REntry;
1492
1493 // Initialize the map for all BB with WHITE color.
1494 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001495 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001496
1497 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001498 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001499 DFSStack.push(std::make_pair(CurrBB, 0));
1500
1501 while (!DFSStack.empty()) {
1502 // Get next BB on stack to be processed.
1503 CurrBB = DFSStack.top().first;
1504 AdjacentBlockIndex = DFSStack.top().second;
1505 DFSStack.pop();
1506
1507 // Loop to iterate over the successors of current BB.
1508 const TerminatorInst *TInst = CurrBB->getTerminator();
1509 unsigned NSucc = TInst->getNumSuccessors();
1510 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1511 ++I, ++AdjacentBlockIndex) {
1512 SuccBB = TInst->getSuccessor(I);
1513
1514 // Checks for region exit block and self-loops in BB.
1515 if (SuccBB == RExit || SuccBB == CurrBB)
1516 continue;
1517
1518 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001519 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001520 // Push the current BB and the index of the next child to be visited.
1521 DFSStack.push(std::make_pair(CurrBB, I + 1));
1522 // Push the next BB to be processed.
1523 DFSStack.push(std::make_pair(SuccBB, 0));
1524 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001525 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001526 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001527 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001528 // GREY indicates a loop in the control flow.
1529 // If the destination dominates the source, it is a natural loop
1530 // else, an irreducible control flow in the region is detected.
1531 if (!DT->dominates(SuccBB, CurrBB)) {
1532 // Get debug info of instruction which causes irregular control flow.
1533 DbgLoc = TInst->getDebugLoc();
1534 return false;
1535 }
1536 }
1537 }
1538
1539 // If all children of current BB have been processed,
1540 // then mark that BB as fully processed.
1541 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001542 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001543 }
1544
1545 return true;
1546}
1547
Tobias Grosserb45ae562016-11-26 07:37:46 +00001548void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1549 bool OnlyProfitable) {
1550 if (!OnlyProfitable) {
1551 NumLoopsInScop += Stats.NumLoops;
1552 if (Stats.MaxDepth == 1)
1553 NumScopsDepthOne++;
1554 else if (Stats.MaxDepth == 2)
1555 NumScopsDepthTwo++;
1556 else if (Stats.MaxDepth == 3)
1557 NumScopsDepthThree++;
1558 else if (Stats.MaxDepth == 4)
1559 NumScopsDepthFour++;
1560 else if (Stats.MaxDepth == 5)
1561 NumScopsDepthFive++;
1562 else
1563 NumScopsDepthLarger++;
1564 } else {
1565 NumLoopsInProfScop += Stats.NumLoops;
1566 if (Stats.MaxDepth == 1)
1567 NumProfScopsDepthOne++;
1568 else if (Stats.MaxDepth == 2)
1569 NumProfScopsDepthTwo++;
1570 else if (Stats.MaxDepth == 3)
1571 NumProfScopsDepthThree++;
1572 else if (Stats.MaxDepth == 4)
1573 NumProfScopsDepthFour++;
1574 else if (Stats.MaxDepth == 5)
1575 NumProfScopsDepthFive++;
1576 else
1577 NumProfScopsDepthLarger++;
1578 }
1579}
1580
Tobias Grosser75805372011-04-29 06:27:02 +00001581bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001582 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001583 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001584 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001585 return false;
1586
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001587 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001588 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001589 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001590 Region *TopRegion = RI->getTopLevelRegion();
1591
Tobias Grosser2ff87232011-10-23 11:17:06 +00001592 releaseMemory();
1593
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001594 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001595 return false;
1596
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001597 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001598 return false;
1599
1600 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001601
Tobias Grosserb45ae562016-11-26 07:37:46 +00001602 NumScopRegions += ValidRegions.size();
1603
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001604 // Prune non-profitable regions.
1605 for (auto &DIt : DetectionContextMap) {
1606 auto &DC = DIt.getSecond();
1607 if (DC.Log.hasErrors())
1608 continue;
1609 if (!ValidRegions.count(&DC.CurRegion))
1610 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001611 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, 0);
1612 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
1613 if (isProfitableRegion(DC)) {
1614 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001615 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001616 }
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001617
1618 ValidRegions.remove(&DC.CurRegion);
1619 }
1620
Tobias Grosserb45ae562016-11-26 07:37:46 +00001621 NumProfScopRegions += ValidRegions.size();
1622 NumLoopsOverall += countBeneficialLoops(TopRegion, 0).NumLoops;
1623
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001624 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001625 if (PollyTrackFailures)
1626 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001627
Johannes Doerferta05214f2014-10-15 23:24:28 +00001628 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001629 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001630
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001631 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001632 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001633 return false;
1634}
1635
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001636ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001637ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001638 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001639 if (DCMIt == DetectionContextMap.end())
1640 return nullptr;
1641 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001642}
1643
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001644const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1645 const DetectionContext *DC = getDetectionContext(R);
1646 return DC ? &DC->Log : nullptr;
1647}
1648
Tobias Grosser75805372011-04-29 06:27:02 +00001649void polly::ScopDetection::verifyRegion(const Region &R) const {
1650 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001651
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001652 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001653 isValidRegion(Context);
1654}
1655
1656void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001657 if (!VerifyScops)
1658 return;
1659
Tobias Grosser26108892014-04-02 20:18:19 +00001660 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001661 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001662}
1663
1664void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001665 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001666 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001667 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001668 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001669 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001670 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001671 AU.setPreservesAll();
1672}
1673
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001674void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001675 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001676 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001677
1678 OS << "\n";
1679}
1680
1681void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001682 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001683 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001684
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001685 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001686}
1687
1688char ScopDetection::ID = 0;
1689
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001690Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1691
Tobias Grosser73600b82011-10-08 00:30:40 +00001692INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1693 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001694 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001695INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001696INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001697INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001698INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001699INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001700INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1701 "Polly - Detect static control parts (SCoPs)", false, false)