blob: d6721302b34ea8c378b7bd6f424559abb4623562 [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 Doerfertb164c792014-09-18 11:17:17 +0000112bool polly::PollyUseRuntimeAliasChecks;
113static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
114 "polly-use-runtime-alias-checks",
115 cl::desc("Use runtime alias checks to resolve possible aliasing."),
116 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Tobias Grosser637bd632013-05-07 07:31:10 +0000119static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000120 ReportLevel("polly-report",
121 cl::desc("Print information about the activities of Polly"),
122 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000123
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000124static cl::opt<bool> AllowDifferentTypes(
125 "polly-allow-differing-element-types",
126 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000127 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000128
Tobias Grosser531891e2012-11-01 16:45:20 +0000129static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000130 AllowNonAffine("polly-allow-nonaffine",
131 cl::desc("Allow non affine access functions in arrays"),
132 cl::Hidden, cl::init(false), cl::ZeroOrMore,
133 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000134
Tobias Grosser898a6362016-03-23 06:40:15 +0000135static cl::opt<bool>
136 AllowModrefCall("polly-allow-modref-calls",
137 cl::desc("Allow functions with known modref behavior"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
140
Johannes Doerfertba65c162015-02-24 11:45:21 +0000141static cl::opt<bool> AllowNonAffineSubRegions(
142 "polly-allow-nonaffine-branches",
143 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000144 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000145
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000146static cl::opt<bool>
147 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
148 cl::desc("Allow non affine conditions for loops"),
149 cl::Hidden, cl::init(false), cl::ZeroOrMore,
150 cl::cat(PollyCategory));
151
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000152static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000153 TrackFailures("polly-detect-track-failures",
154 cl::desc("Track failure strings in detecting scop regions"),
155 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000156 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000157
Andreas Simbuerger04472402014-05-24 09:25:10 +0000158static cl::opt<bool> KeepGoing("polly-detect-keep-going",
159 cl::desc("Do not fail on the first error."),
160 cl::Hidden, cl::ZeroOrMore, cl::init(false),
161 cl::cat(PollyCategory));
162
Sebastian Pop18016682014-04-08 21:20:44 +0000163static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000164 PollyDelinearizeX("polly-delinearize",
165 cl::desc("Delinearize array access functions"),
166 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000167 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000168
Tobias Grossera1689932014-02-18 18:49:49 +0000169static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000170 VerifyScops("polly-detect-verify",
171 cl::desc("Verify the detected SCoPs after each transformation"),
172 cl::Hidden, cl::init(false), cl::ZeroOrMore,
173 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000174
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000175bool polly::PollyInvariantLoadHoisting;
176static cl::opt<bool, true> XPollyInvariantLoadHoisting(
177 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
178 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
179 cl::init(true), cl::cat(PollyCategory));
180
Johannes Doerferte526de52015-09-21 19:10:11 +0000181/// @brief The minimal trip count under which loops are considered unprofitable.
182static const unsigned MIN_LOOP_TRIP_COUNT = 8;
183
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000184bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000185bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000186StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000187
Tobias Grosser75805372011-04-29 06:27:02 +0000188//===----------------------------------------------------------------------===//
189// Statistics.
190
191STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
192
Tobias Grosser8519f892013-12-18 10:49:53 +0000193class DiagnosticScopFound : public DiagnosticInfo {
194private:
195 static int PluginDiagnosticKind;
196
197 Function &F;
198 std::string FileName;
199 unsigned EntryLine, ExitLine;
200
201public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000202 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
203 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000204 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000205 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000206
207 virtual void print(DiagnosticPrinter &DP) const;
208
209 static bool classof(const DiagnosticInfo *DI) {
210 return DI->getKind() == PluginDiagnosticKind;
211 }
212};
213
Tobias Grosserdb6db502016-04-01 07:15:19 +0000214int DiagnosticScopFound::PluginDiagnosticKind =
215 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000216
Tobias Grosser8519f892013-12-18 10:49:53 +0000217void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000218 DP << "Polly detected an optimizable loop region (scop) in function '" << F
219 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000220
221 if (FileName.empty()) {
222 DP << "Scop location is unknown. Compile with debug info "
223 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000224 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000225 }
226
227 DP << FileName << ":" << EntryLine << ": Start of scop\n";
228 DP << FileName << ":" << ExitLine << ": End of scop";
229}
230
Tobias Grosser75805372011-04-29 06:27:02 +0000231//===----------------------------------------------------------------------===//
232// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000233
Johannes Doerfertb164c792014-09-18 11:17:17 +0000234ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000235 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000236 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000237 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000238}
239
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000240template <class RR, typename... Args>
241inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
242 Args &&... Arguments) const {
243
244 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000245 RejectLog &Log = Context.Log;
246 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000247
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000248 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000249 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000250
251 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000252 DEBUG(dbgs() << "\n");
253 } else {
254 assert(!Assert && "Verification of detected scop failed");
255 }
256
257 return false;
258}
259
Tobias Grossera1689932014-02-18 18:49:49 +0000260bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
261 if (!ValidRegions.count(&R))
262 return false;
263
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000264 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000265 DetectionContextMap.erase(getBBPairForRegion(&R));
266 const auto &It = DetectionContextMap.insert(std::make_pair(
267 getBBPairForRegion(&R),
268 DetectionContext(const_cast<Region &>(R), *AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000269 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000270 return isValidRegion(Context);
271 }
Tobias Grossera1689932014-02-18 18:49:49 +0000272
273 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000274}
275
Tobias Grosser4f129a62011-10-08 00:30:55 +0000276std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000277 // Get the first error we found. Even in keep-going mode, this is the first
278 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000279 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000280
281 // This can happen when we marked a region invalid, but didn't track
282 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000283 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000284 return "";
285
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000286 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000287 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000288}
289
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000290bool ScopDetection::addOverApproximatedRegion(Region *AR,
291 DetectionContext &Context) const {
292
293 // If we already know about Ar we can exit.
294 if (!Context.NonAffineSubRegionSet.insert(AR))
295 return true;
296
297 // All loops in the region have to be overapproximated too if there
298 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000299
300 BoxedLoopsSetTy ARBoxedLoopsSet;
301
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000302 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000303 Loop *L = LI->getLoopFor(BB);
Michael Kruse41f046a2016-06-27 19:00:49 +0000304 if (AR->contains(L)) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000305 Context.BoxedLoopsSet.insert(L);
Michael Kruse41f046a2016-06-27 19:00:49 +0000306 ARBoxedLoopsSet.insert(L);
307 }
308 }
309
310 // Reject if the surrounding loop does not entirely contain the nonaffine
311 // subregion.
312 BasicBlock *BBEntry = AR->getEntry();
313 Loop *L = LI->getLoopFor(BBEntry);
314 while (L && AR->contains(L))
315 L = L->getParentLoop();
316 if (L) {
317 for (const auto *ARBoxedLoop : ARBoxedLoopsSet)
318 if (!L->contains(ARBoxedLoop))
319 return invalid<ReportLoopOverlapWithNonAffineSubRegion>(
320 Context, /*Assert=*/true, L, AR);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000321 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000322
323 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000324}
325
Johannes Doerfert09e36972015-10-07 20:17:36 +0000326bool ScopDetection::onlyValidRequiredInvariantLoads(
327 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
328 Region &CurRegion = Context.CurRegion;
329
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000330 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
331 return false;
332
Johannes Doerfert09e36972015-10-07 20:17:36 +0000333 for (LoadInst *Load : RequiredILS)
334 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
335 return false;
336
337 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
338
339 return true;
340}
341
Michael Kruse09eb4452016-03-03 22:10:47 +0000342bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000343 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000344
345 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000346 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000347 return false;
348
349 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
350 return false;
351
352 return true;
353}
354
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000355bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000356 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000357 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000358 Loop *L = LI->getLoopFor(&BB);
359 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000360
Michael Kruse09eb4452016-03-03 22:10:47 +0000361 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000362 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000363
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000364 if (!IsLoopBranch && AllowNonAffineSubRegions &&
365 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
366 return true;
367
368 if (IsLoopBranch)
369 return false;
370
371 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
372 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000373}
374
375bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000376 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000377 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000378
379 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
380 auto Opcode = BinOp->getOpcode();
381 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
382 Value *Op0 = BinOp->getOperand(0);
383 Value *Op1 = BinOp->getOperand(1);
384 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
385 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
386 }
387 }
388
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000389 // Non constant conditions of branches need to be ICmpInst.
390 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000391 if (!IsLoopBranch && AllowNonAffineSubRegions &&
392 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
393 return true;
394 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000395 }
Tobias Grosser75805372011-04-29 06:27:02 +0000396
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000397 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000398
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000399 // Are both operands of the ICmp affine?
400 if (isa<UndefValue>(ICmp->getOperand(0)) ||
401 isa<UndefValue>(ICmp->getOperand(1)))
402 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000403
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000404 Loop *L = LI->getLoopFor(ICmp->getParent());
405 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
406 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000407
Michael Kruse09eb4452016-03-03 22:10:47 +0000408 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000409 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000410
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000411 if (!IsLoopBranch && AllowNonAffineSubRegions &&
412 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
413 return true;
414
415 if (IsLoopBranch)
416 return false;
417
418 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
419 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000420}
421
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000422bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000423 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000424 DetectionContext &Context) const {
425 Region &CurRegion = Context.CurRegion;
426
427 TerminatorInst *TI = BB.getTerminator();
428
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000429 if (AllowUnreachable && isa<UnreachableInst>(TI))
430 return true;
431
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000432 // Return instructions are only valid if the region is the top level region.
433 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
434 return true;
435
436 Value *Condition = getConditionFromTerminator(TI);
437
438 if (!Condition)
439 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
440
441 // UndefValue is not allowed as condition.
442 if (isa<UndefValue>(Condition))
443 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
444
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000445 // Constant integer conditions are always affine.
446 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000447 return true;
448
449 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000450 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000451
452 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
453 assert(SI && "Terminator was neither branch nor switch");
454
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000455 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000456}
457
Johannes Doerfertcea61932016-02-21 19:13:19 +0000458bool ScopDetection::isValidCallInst(CallInst &CI,
459 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000460 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000461 return false;
462
463 if (CI.doesNotAccessMemory())
464 return true;
465
Johannes Doerfertcea61932016-02-21 19:13:19 +0000466 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000467 if (isValidIntrinsicInst(*II, Context))
468 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000469
Tobias Grosser75805372011-04-29 06:27:02 +0000470 Function *CalledFunction = CI.getCalledFunction();
471
472 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000473 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000474 return false;
475
Tobias Grosser898a6362016-03-23 06:40:15 +0000476 if (AllowModrefCall) {
477 switch (AA->getModRefBehavior(CalledFunction)) {
478 case llvm::FMRB_UnknownModRefBehavior:
479 return false;
480 case llvm::FMRB_DoesNotAccessMemory:
481 case llvm::FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000482 // Implicitly disable delinearization since we have an unknown
483 // accesses with an unknown access function.
484 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000485 Context.AST.add(&CI);
486 return true;
487 case llvm::FMRB_OnlyReadsArgumentPointees:
488 case llvm::FMRB_OnlyAccessesArgumentPointees:
489 for (const auto &Arg : CI.arg_operands()) {
490 if (!Arg->getType()->isPointerTy())
491 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000492
Tobias Grosser898a6362016-03-23 06:40:15 +0000493 // Bail if a pointer argument has a base address not known to
494 // ScalarEvolution. Note that a zero pointer is acceptable.
495 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
496 if (ArgSCEV->isZero())
497 continue;
498
499 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
500 if (!BP)
501 return false;
502
503 // Implicitly disable delinearization since we have an unknown
504 // accesses with an unknown access function.
505 Context.HasUnknownAccess = true;
506 }
507
508 Context.AST.add(&CI);
509 return true;
510 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000511 }
512
Johannes Doerfertcea61932016-02-21 19:13:19 +0000513 return false;
514}
515
516bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
517 DetectionContext &Context) const {
518 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000519 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000520
Johannes Doerfertcea61932016-02-21 19:13:19 +0000521 // The closest loop surrounding the call instruction.
522 Loop *L = LI->getLoopFor(II.getParent());
523
524 // The access function and base pointer for memory intrinsics.
525 const SCEV *AF;
526 const SCEVUnknown *BP;
527
528 switch (II.getIntrinsicID()) {
529 // Memory intrinsics that can be represented are supported.
530 case llvm::Intrinsic::memmove:
531 case llvm::Intrinsic::memcpy:
532 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000533 if (!AF->isZero()) {
534 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
535 // Bail if the source pointer is not valid.
536 if (!isValidAccess(&II, AF, BP, Context))
537 return false;
538 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000539 // Fall through
540 case llvm::Intrinsic::memset:
541 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000542 if (!AF->isZero()) {
543 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
544 // Bail if the destination pointer is not valid.
545 if (!isValidAccess(&II, AF, BP, Context))
546 return false;
547 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000548
549 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000550 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000551 Context))
552 return false;
553
554 return true;
555 default:
556 break;
557 }
558
Tobias Grosser75805372011-04-29 06:27:02 +0000559 return false;
560}
561
Tobias Grosser458fb782014-01-28 12:58:58 +0000562bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
563 // A reference to function argument or constant value is invariant.
564 if (isa<Argument>(Val) || isa<Constant>(Val))
565 return true;
566
567 const Instruction *I = dyn_cast<Instruction>(&Val);
568 if (!I)
569 return false;
570
571 if (!Reg.contains(I))
572 return true;
573
574 if (I->mayHaveSideEffects())
575 return false;
576
Johannes Doerfertfbb63b82016-04-09 21:57:13 +0000577 if (isa<SelectInst>(I))
578 return false;
579
Tobias Grosser458fb782014-01-28 12:58:58 +0000580 // When Val is a Phi node, it is likely not invariant. We do not check whether
581 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000582 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000583 if (isa<PHINode>(*I))
584 return false;
585
Tobias Grosser26108892014-04-02 20:18:19 +0000586 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000587 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000588 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000589
Tobias Grosser458fb782014-01-28 12:58:58 +0000590 return true;
591}
592
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000593/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
594/// register the '...' components.
595///
596/// Array access expressions as they are generated by gfortran contain smax(0,
597/// size) expressions that confuse the 'normal' delinearization algorithm.
598/// However, if we extract such expressions before the normal delinearization
599/// takes place they can actually help to identify array size expressions in
600/// fortran accesses. For the subsequently following delinearization the smax(0,
601/// size) component can be replaced by just 'size'. This is correct as we will
602/// always add and verify the assumption that for all subscript expressions
603/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
604/// that 0 <= size, which means smax(0, size) == size.
605struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
606public:
607 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
608 std::vector<const SCEV *> *Terms = nullptr) {
609
610 SCEVRemoveMax D(SE, Terms);
611 return D.visit(Expr);
612 }
613
614 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
615 : SE(SE), Terms(Terms) {}
616
617 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
618
619 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
620 return Expr;
621 }
622
623 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
624 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
625 }
626
627 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
628
629 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000630 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000631 auto Res = visit(Expr->getOperand(1));
632 if (Terms)
633 (*Terms).push_back(Res);
634 return Res;
635 }
636
637 return Expr;
638 }
639
Roman Gareev8aa43752015-12-17 20:37:17 +0000640 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000641
642 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
643
644 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
645 return Expr;
646 }
647
648 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
649
650 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
651 SmallVector<const SCEV *, 5> NewOps;
652 for (const SCEV *Op : Expr->operands())
653 NewOps.push_back(visit(Op));
654
655 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
656 }
657
658 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
659 SmallVector<const SCEV *, 5> NewOps;
660 for (const SCEV *Op : Expr->operands())
661 NewOps.push_back(visit(Op));
662
663 return SE.getAddExpr(NewOps);
664 }
665
666 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
667 SmallVector<const SCEV *, 5> NewOps;
668 for (const SCEV *Op : Expr->operands())
669 NewOps.push_back(visit(Op));
670
671 return SE.getMulExpr(NewOps);
672 }
673
674private:
675 ScalarEvolution &SE;
676 std::vector<const SCEV *> *Terms;
677};
678
Tobias Grosserd68ba422015-11-24 05:00:36 +0000679SmallVector<const SCEV *, 4>
680ScopDetection::getDelinearizationTerms(DetectionContext &Context,
681 const SCEVUnknown *BasePointer) const {
682 SmallVector<const SCEV *, 4> Terms;
683 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000684 std::vector<const SCEV *> MaxTerms;
685 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
686 if (MaxTerms.size() > 0) {
687 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
688 continue;
689 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000690 // In case the outermost expression is a plain add, we check if any of its
691 // terms has the form 4 * %inst * %param * %param ..., aka a term that
692 // contains a product between a parameter and an instruction that is
693 // inside the scop. Such instructions, if allowed at all, are instructions
694 // SCEV can not represent, but Polly is still looking through. As a
695 // result, these instructions can depend on induction variables and are
696 // most likely no array sizes. However, terms that are multiplied with
697 // them are likely candidates for array sizes.
698 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
699 for (auto Op : AF->operands()) {
700 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
701 SE->collectParametricTerms(AF2, Terms);
702 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
703 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000704
Tobias Grosserd68ba422015-11-24 05:00:36 +0000705 for (auto *MulOp : AF2->operands()) {
706 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
707 Operands.push_back(Const);
708 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
709 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
710 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000711 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000712
713 } else {
714 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000715 }
716 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000717 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000718 if (Operands.size())
719 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000720 }
721 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000722 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000723 if (Terms.empty())
724 SE->collectParametricTerms(Pair.second, Terms);
725 }
726 return Terms;
727}
Sebastian Pope8863b82014-05-12 19:02:02 +0000728
Tobias Grosserd68ba422015-11-24 05:00:36 +0000729bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
730 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000731 const SCEVUnknown *BasePointer,
732 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000733 Value *BaseValue = BasePointer->getValue();
734 Region &CurRegion = Context.CurRegion;
735 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000736 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000737 Sizes.clear();
738 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000739 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000740 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
741 auto *V = dyn_cast<Value>(Unknown->getValue());
742 if (auto *Load = dyn_cast<LoadInst>(V)) {
743 if (Context.CurRegion.contains(Load) &&
744 isHoistableLoad(Load, CurRegion, *LI, *SE))
745 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000746 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000747 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000748 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000749 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000750 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000751 Context, /*Assert=*/true, DelinearizedSize,
752 Context.Accesses[BasePointer].front().first, BaseValue);
753 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000754
Tobias Grosserd68ba422015-11-24 05:00:36 +0000755 // No array shape derived.
756 if (Sizes.empty()) {
757 if (AllowNonAffine)
758 return true;
759
Tobias Grosser230acc42014-09-13 14:47:55 +0000760 for (const auto &Pair : Context.Accesses[BasePointer]) {
761 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000762 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000763
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000764 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000765 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
766 BaseValue);
767 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000768 return false;
769 }
770 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000771 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000772 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000773 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000774}
775
Tobias Grosserd68ba422015-11-24 05:00:36 +0000776// We first store the resulting memory accesses in TempMemoryAccesses. Only
777// if the access functions for all memory accesses have been successfully
778// delinearized we continue. Otherwise, we either report a failure or, if
779// non-affine accesses are allowed, we drop the information. In case the
780// information is dropped the memory accesses need to be overapproximated
781// when translated to a polyhedral representation.
782bool ScopDetection::computeAccessFunctions(
783 DetectionContext &Context, const SCEVUnknown *BasePointer,
784 std::shared_ptr<ArrayShape> Shape) const {
785 Value *BaseValue = BasePointer->getValue();
786 bool BasePtrHasNonAffine = false;
787 MapInsnToMemAcc TempMemoryAccesses;
788 for (const auto &Pair : Context.Accesses[BasePointer]) {
789 const Instruction *Insn = Pair.first;
790 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000791 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000792 bool IsNonAffine = false;
793 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
794 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000795 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000796
797 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000798 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000799 Acc->DelinearizedSubscripts.push_back(Pair.second);
800 else
801 IsNonAffine = true;
802 } else {
803 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
804 Shape->DelinearizedSizes);
805 if (Acc->DelinearizedSubscripts.size() == 0)
806 IsNonAffine = true;
807 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000808 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000809 IsNonAffine = true;
810 }
811
812 // (Possibly) report non affine access
813 if (IsNonAffine) {
814 BasePtrHasNonAffine = true;
815 if (!AllowNonAffine)
816 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
817 Insn, BaseValue);
818 if (!KeepGoing && !AllowNonAffine)
819 return false;
820 }
821 }
822
823 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000824 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
825 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000826
827 return true;
828}
829
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000830bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
831 const SCEVUnknown *BasePointer,
832 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000833 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
834
835 auto Terms = getDelinearizationTerms(Context, BasePointer);
836
837 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
838 Context.ElementSize[BasePointer]);
839
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000840 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
841 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000842 return false;
843
844 return computeAccessFunctions(Context, BasePointer, Shape);
845}
846
847bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000848 // TODO: If we have an unknown access and other non-affine accesses we do
849 // not try to delinearize them for now.
850 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
851 return AllowNonAffine;
852
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000853 for (auto &Pair : Context.NonAffineAccesses) {
854 auto *BasePointer = Pair.first;
855 auto *Scope = Pair.second;
856 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000857 if (KeepGoing)
858 continue;
859 else
860 return false;
861 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000862 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000863 return true;
864}
865
Johannes Doerfertcea61932016-02-21 19:13:19 +0000866bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
867 const SCEVUnknown *BP,
868 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000869
Johannes Doerfertcea61932016-02-21 19:13:19 +0000870 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000871 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000872
Johannes Doerfertcea61932016-02-21 19:13:19 +0000873 auto *BV = BP->getValue();
874 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000875 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000876
Johannes Doerfertcea61932016-02-21 19:13:19 +0000877 // FIXME: Think about allowing IntToPtrInst
878 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
879 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
880
Tobias Grosser458fb782014-01-28 12:58:58 +0000881 // Check that the base address of the access is invariant in the current
882 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000883 if (!isInvariant(*BV, Context.CurRegion))
884 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000885
Johannes Doerfertcea61932016-02-21 19:13:19 +0000886 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000887
Johannes Doerfertcea61932016-02-21 19:13:19 +0000888 const SCEV *Size;
889 if (!isa<MemIntrinsic>(Inst)) {
890 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000891 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000892 auto *SizeTy =
893 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
894 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000895 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000896
Johannes Doerfertcea61932016-02-21 19:13:19 +0000897 if (Context.ElementSize[BP]) {
898 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
899 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
900 Inst, BV);
901
902 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
903 } else {
904 Context.ElementSize[BP] = Size;
905 }
906
907 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000908 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000909 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000910 for (const Loop *L : Loops)
911 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000912 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000913
Michael Kruse09eb4452016-03-03 22:10:47 +0000914 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000915 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000916 // Do not try to delinearize memory intrinsics and force them to be affine.
917 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
918 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
919 BV);
920 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
921 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000922
Johannes Doerfertcea61932016-02-21 19:13:19 +0000923 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000924 Context.NonAffineAccesses.insert(
925 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000926 } else if (!AllowNonAffine && !IsAffine) {
927 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
928 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000929 }
Tobias Grosser75805372011-04-29 06:27:02 +0000930
Tobias Grosser1eedb672014-09-24 21:04:29 +0000931 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000932 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000933
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000934 // Check if the base pointer of the memory access does alias with
935 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000936 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000937 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000938 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000939 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000940
Tobias Grosser1eedb672014-09-24 21:04:29 +0000941 if (!AS.isMustAlias()) {
942 if (PollyUseRuntimeAliasChecks) {
943 bool CanBuildRunTimeCheck = true;
944 // The run-time alias check places code that involves the base pointer at
945 // the beginning of the SCoP. This breaks if the base pointer is defined
946 // inside the scop. Hence, we can only create a run-time check if we are
947 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000948 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000949 for (const auto &Ptr : AS) {
950 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000951 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000952 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000953 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000954 Context.RequiredILS.insert(Load);
955 continue;
956 }
957
Tobias Grosser1eedb672014-09-24 21:04:29 +0000958 CanBuildRunTimeCheck = false;
959 break;
960 }
961 }
962
963 if (CanBuildRunTimeCheck)
964 return true;
965 }
Michael Kruse70131d32016-01-27 17:09:17 +0000966 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000967 }
Tobias Grosser75805372011-04-29 06:27:02 +0000968
969 return true;
970}
971
Johannes Doerfertcea61932016-02-21 19:13:19 +0000972bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
973 DetectionContext &Context) const {
974 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000975 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000976 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
977 const SCEVUnknown *BasePointer;
978
979 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
980
981 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
982}
983
Tobias Grosser75805372011-04-29 06:27:02 +0000984bool ScopDetection::isValidInstruction(Instruction &Inst,
985 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000986 for (auto &Op : Inst.operands()) {
987 auto *OpInst = dyn_cast<Instruction>(&Op);
988
989 if (!OpInst)
990 continue;
991
992 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
993 return false;
994 }
995
Johannes Doerfert81c41b92016-04-09 21:55:58 +0000996 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
997 return false;
998
Tobias Grosser75805372011-04-29 06:27:02 +0000999 // We only check the call instruction but not invoke instruction.
1000 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001001 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001002 return true;
1003
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001004 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001005 }
1006
1007 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001008 if (!isa<AllocaInst>(Inst))
1009 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001010
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001011 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001012 }
1013
1014 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001015 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001016 Context.hasStores |= isa<StoreInst>(MemInst);
1017 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001018 if (!MemInst.isSimple())
1019 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1020 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001021
Michael Kruse70131d32016-01-27 17:09:17 +00001022 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001023 }
Tobias Grosser75805372011-04-29 06:27:02 +00001024
1025 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001026 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001027}
1028
Johannes Doerfertd020b772015-08-27 06:53:52 +00001029bool ScopDetection::canUseISLTripCount(Loop *L,
1030 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001031 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1032 // need to overapproximate it as a boxed loop.
1033 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001034 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001035
1036 // Loops without exiting blocks cannot be handled by the schedule generation
1037 // as it depends on a region covering that is not given.
1038 if (LoopControlBlocks.empty())
1039 return false;
1040
1041 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001042 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001043 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001044 return false;
1045 }
1046
Johannes Doerfertd020b772015-08-27 06:53:52 +00001047 // We can use ISL to compute the trip count of L.
1048 return true;
1049}
1050
Tobias Grosser75805372011-04-29 06:27:02 +00001051bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001052 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001053 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001054
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001055 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001056 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001057 while (R != &Context.CurRegion && !R->contains(L))
1058 R = R->getParent();
1059
1060 if (addOverApproximatedRegion(R, Context))
1061 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001062 }
Tobias Grosser75805372011-04-29 06:27:02 +00001063
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001064 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001065 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001066}
1067
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001068/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +00001069/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +00001070static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001071 auto *TripCount = SE.getBackedgeTakenCount(L);
1072
Johannes Doerfertf61df692015-10-04 14:56:08 +00001073 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001074 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001075 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1076 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1077 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001078
1079 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001080 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001081
1082 return count;
1083}
1084
Johannes Doerfertf61df692015-10-04 14:56:08 +00001085int ScopDetection::countBeneficialLoops(Region *R) const {
1086 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001087
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001088 auto L = LI->getLoopFor(R->getEntry());
1089 L = L ? R->outermostLoopInRegion(L) : nullptr;
1090 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001091
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001092 auto SubLoops =
1093 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1094
1095 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001096 if (R->contains(SubLoop))
1097 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001098
Johannes Doerfertf61df692015-10-04 14:56:08 +00001099 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001100}
1101
Tobias Grosser75805372011-04-29 06:27:02 +00001102Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001103 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001104 std::unique_ptr<Region> LastValidRegion;
1105 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001106
1107 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1108
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001109 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001110 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001111 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001112 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1113 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001114 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001115 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001116
Johannes Doerfert717b8662015-09-08 21:44:27 +00001117 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001118 // If the exit is valid check all blocks
1119 // - if true, a valid region was found => store it + keep expanding
1120 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001121 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1122 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001123 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001124 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001125
Tobias Grosserd7e58642013-04-10 06:55:45 +00001126 // Store this region, because it is the greatest valid (encountered so
1127 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001128 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001129 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001130
1131 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001132 ExpandedRegion =
1133 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001134
1135 } else {
1136 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001137 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001138 ExpandedRegion =
1139 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001140 }
Tobias Grosser75805372011-04-29 06:27:02 +00001141 }
1142
Tobias Grosser378a9f22013-11-16 19:34:11 +00001143 DEBUG({
1144 if (LastValidRegion)
1145 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1146 else
1147 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1148 });
Tobias Grosser75805372011-04-29 06:27:02 +00001149
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001150 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001151}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001152static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001153 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001154 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001155 return false;
1156
1157 return true;
1158}
Tobias Grosser75805372011-04-29 06:27:02 +00001159
Johannes Doerferte46925f2015-10-01 10:59:14 +00001160unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001161 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001162 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001163 if (ValidRegions.count(SubRegion.get())) {
1164 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001165 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001166 } else
1167 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001168 }
1169 return Count;
1170}
1171
Johannes Doerferte46925f2015-10-01 10:59:14 +00001172void ScopDetection::removeCachedResults(const Region &R) {
1173 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001174}
1175
Tobias Grosser75805372011-04-29 06:27:02 +00001176void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001177 const auto &It = DetectionContextMap.insert(std::make_pair(
1178 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001179 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001180
1181 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001182 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001183 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001184 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001185 RegionIsValid = isValidRegion(Context);
1186
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001187 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001188
Johannes Doerferte46925f2015-10-01 10:59:14 +00001189 if (HasErrors) {
1190 removeCachedResults(R);
1191 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001192 ++ValidRegion;
1193 ValidRegions.insert(&R);
1194 return;
1195 }
1196
David Blaikieb035f6d2014-04-15 18:45:27 +00001197 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001198 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001199
1200 // Try to expand regions.
1201 //
1202 // As the region tree normally only contains canonical regions, non canonical
1203 // regions that form a Scop are not found. Therefore, those non canonical
1204 // regions are checked by expanding the canonical ones.
1205
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001206 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001207
David Blaikieb035f6d2014-04-15 18:45:27 +00001208 for (auto &SubRegion : R)
1209 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001210
Tobias Grosser26108892014-04-02 20:18:19 +00001211 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001212 // Skip invalid regions. Regions may become invalid, if they are element of
1213 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001214 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001215 continue;
1216
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001217 // Skip regions that had errors.
1218 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1219 if (HadErrors)
1220 continue;
1221
Tobias Grosser75805372011-04-29 06:27:02 +00001222 Region *ExpandedR = expandRegion(*CurrentRegion);
1223
1224 if (!ExpandedR)
1225 continue;
1226
1227 R.addSubRegion(ExpandedR, true);
1228 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001229 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001230
Tobias Grosser28a70c52014-01-29 19:05:30 +00001231 // Erase all (direct and indirect) children of ExpandedR from the valid
1232 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001233 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001234 }
1235}
1236
1237bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001238 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001239
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001240 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001241 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001242 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1243 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001244 return false;
1245 }
1246
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001247 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001248 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1249
1250 // Also check exception blocks (and possibly register them as non-affine
1251 // regions). Even though exception blocks are not modeled, we use them
1252 // to forward-propagate domain constraints during ScopInfo construction.
1253 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1254 return false;
1255
1256 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001257 continue;
1258
Tobias Grosser1d191902014-03-03 13:13:55 +00001259 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001260 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001261 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001262 }
Tobias Grosser75805372011-04-29 06:27:02 +00001263
Sebastian Pope8863b82014-05-12 19:02:02 +00001264 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001265 return false;
1266
Tobias Grosser75805372011-04-29 06:27:02 +00001267 return true;
1268}
1269
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001270bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1271 int NumLoops) const {
1272 int InstCount = 0;
1273
1274 for (auto *BB : Context.CurRegion.blocks())
1275 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001276 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001277
1278 InstCount = InstCount / NumLoops;
1279
1280 return InstCount >= ProfitabilityMinPerLoopInstructions;
1281}
1282
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001283bool ScopDetection::hasPossiblyDistributableLoop(
1284 DetectionContext &Context) const {
1285 for (auto *BB : Context.CurRegion.blocks()) {
1286 auto *L = LI->getLoopFor(BB);
1287 if (!Context.CurRegion.contains(L))
1288 continue;
1289 if (Context.BoxedLoopsSet.count(L))
1290 continue;
1291 unsigned StmtsWithStoresInLoops = 0;
1292 for (auto *LBB : L->blocks()) {
1293 bool MemStore = false;
1294 for (auto &I : *LBB)
1295 MemStore |= isa<StoreInst>(&I);
1296 StmtsWithStoresInLoops += MemStore;
1297 }
1298 return (StmtsWithStoresInLoops > 1);
1299 }
1300 return false;
1301}
1302
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001303bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1304 Region &CurRegion = Context.CurRegion;
1305
1306 if (PollyProcessUnprofitable)
1307 return true;
1308
1309 // We can probably not do a lot on scops that only write or only read
1310 // data.
1311 if (!Context.hasStores || !Context.hasLoads)
1312 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1313
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001314 int NumLoops = countBeneficialLoops(&CurRegion);
1315 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001316
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001317 // Scops with at least two loops may allow either loop fusion or tiling and
1318 // are consequently interesting to look at.
1319 if (NumAffineLoops >= 2)
1320 return true;
1321
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001322 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1323 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1324 return true;
1325
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001326 // Scops that contain a loop with a non-trivial amount of computation per
1327 // loop-iteration are interesting as we may be able to parallelize such
1328 // loops. Individual loops that have only a small amount of computation
1329 // per-iteration are performance-wise very fragile as any change to the
1330 // loop induction variables may affect performance. To not cause spurious
1331 // performance regressions, we do not consider such loops.
1332 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1333 return true;
1334
1335 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001336}
1337
Tobias Grosser75805372011-04-29 06:27:02 +00001338bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001339 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001340
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001341 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001342
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001343 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001344 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001345 return false;
1346 }
1347
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001348 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001349 DEBUG({
1350 dbgs() << "Region entry does not match -polly-region-only";
1351 dbgs() << "\n";
1352 });
1353 return false;
1354 }
1355
Tobias Grosserd654c252012-04-10 18:12:19 +00001356 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001357 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001358 if (CurRegion.getEntry() ==
1359 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1360 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001361
Hongbin Zheng94868e62012-04-07 12:29:17 +00001362 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001363 return false;
1364
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001365 DebugLoc DbgLoc;
1366 if (!isReducibleRegion(CurRegion, DbgLoc))
1367 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1368 &CurRegion, DbgLoc);
1369
Tobias Grosser75805372011-04-29 06:27:02 +00001370 DEBUG(dbgs() << "OK\n");
1371 return true;
1372}
1373
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001374void ScopDetection::markFunctionAsInvalid(Function *F) const {
1375 F->addFnAttr(PollySkipFnAttr);
1376}
1377
Tobias Grosser75805372011-04-29 06:27:02 +00001378bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001379 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001380}
1381
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001382void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001383 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001384 unsigned LineEntry, LineExit;
1385 std::string FileName;
1386
Tobias Grosser00dc3092014-03-02 12:02:46 +00001387 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001388 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1389 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001390 }
1391}
1392
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001393void ScopDetection::emitMissedRemarks(const Function &F) {
1394 for (auto &DIt : DetectionContextMap) {
1395 auto &DC = DIt.getSecond();
1396 if (DC.Log.hasErrors())
1397 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001398 }
1399}
1400
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001401bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosseref6ae702016-06-11 09:00:37 +00001402 /// @brief Enum for coloring BBs in Region.
1403 ///
1404 /// WHITE - Unvisited BB in DFS walk.
1405 /// GREY - BBs which are currently on the DFS stack for processing.
1406 /// BLACK - Visited and completely processed BB.
1407 enum Color { WHITE, GREY, BLACK };
1408
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001409 BasicBlock *REntry = R.getEntry();
1410 BasicBlock *RExit = R.getExit();
1411 // Map to match the color of a BasicBlock during the DFS walk.
1412 DenseMap<const BasicBlock *, Color> BBColorMap;
1413 // Stack keeping track of current BB and index of next child to be processed.
1414 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1415
1416 unsigned AdjacentBlockIndex = 0;
1417 BasicBlock *CurrBB, *SuccBB;
1418 CurrBB = REntry;
1419
1420 // Initialize the map for all BB with WHITE color.
1421 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001422 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001423
1424 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001425 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001426 DFSStack.push(std::make_pair(CurrBB, 0));
1427
1428 while (!DFSStack.empty()) {
1429 // Get next BB on stack to be processed.
1430 CurrBB = DFSStack.top().first;
1431 AdjacentBlockIndex = DFSStack.top().second;
1432 DFSStack.pop();
1433
1434 // Loop to iterate over the successors of current BB.
1435 const TerminatorInst *TInst = CurrBB->getTerminator();
1436 unsigned NSucc = TInst->getNumSuccessors();
1437 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1438 ++I, ++AdjacentBlockIndex) {
1439 SuccBB = TInst->getSuccessor(I);
1440
1441 // Checks for region exit block and self-loops in BB.
1442 if (SuccBB == RExit || SuccBB == CurrBB)
1443 continue;
1444
1445 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001446 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001447 // Push the current BB and the index of the next child to be visited.
1448 DFSStack.push(std::make_pair(CurrBB, I + 1));
1449 // Push the next BB to be processed.
1450 DFSStack.push(std::make_pair(SuccBB, 0));
1451 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001452 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001453 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001454 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001455 // GREY indicates a loop in the control flow.
1456 // If the destination dominates the source, it is a natural loop
1457 // else, an irreducible control flow in the region is detected.
1458 if (!DT->dominates(SuccBB, CurrBB)) {
1459 // Get debug info of instruction which causes irregular control flow.
1460 DbgLoc = TInst->getDebugLoc();
1461 return false;
1462 }
1463 }
1464 }
1465
1466 // If all children of current BB have been processed,
1467 // then mark that BB as fully processed.
1468 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001469 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001470 }
1471
1472 return true;
1473}
1474
Tobias Grosser75805372011-04-29 06:27:02 +00001475bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001476 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001477 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001478 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001479 return false;
1480
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001481 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001482 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001483 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001484 Region *TopRegion = RI->getTopLevelRegion();
1485
Tobias Grosser2ff87232011-10-23 11:17:06 +00001486 releaseMemory();
1487
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001488 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001489 return false;
1490
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001491 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001492 return false;
1493
1494 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001495
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001496 // Prune non-profitable regions.
1497 for (auto &DIt : DetectionContextMap) {
1498 auto &DC = DIt.getSecond();
1499 if (DC.Log.hasErrors())
1500 continue;
1501 if (!ValidRegions.count(&DC.CurRegion))
1502 continue;
1503 if (isProfitableRegion(DC))
1504 continue;
1505
1506 ValidRegions.remove(&DC.CurRegion);
1507 }
1508
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001509 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001510 if (PollyTrackFailures)
1511 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001512
Johannes Doerferta05214f2014-10-15 23:24:28 +00001513 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001514 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001515
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001516 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001517 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001518 return false;
1519}
1520
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001521ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001522ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001523 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001524 if (DCMIt == DetectionContextMap.end())
1525 return nullptr;
1526 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001527}
1528
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001529const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1530 const DetectionContext *DC = getDetectionContext(R);
1531 return DC ? &DC->Log : nullptr;
1532}
1533
Tobias Grosser75805372011-04-29 06:27:02 +00001534void polly::ScopDetection::verifyRegion(const Region &R) const {
1535 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001536
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001537 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001538 isValidRegion(Context);
1539}
1540
1541void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001542 if (!VerifyScops)
1543 return;
1544
Tobias Grosser26108892014-04-02 20:18:19 +00001545 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001546 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001547}
1548
1549void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001550 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001551 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001552 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001553 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001554 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001555 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001556 AU.setPreservesAll();
1557}
1558
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001559void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001560 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001561 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001562
1563 OS << "\n";
1564}
1565
1566void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001567 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001568 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001569
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001570 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001571}
1572
1573char ScopDetection::ID = 0;
1574
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001575Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1576
Tobias Grosser73600b82011-10-08 00:30:40 +00001577INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1578 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001579 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001580INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001581INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001582INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001583INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001584INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001585INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1586 "Polly - Detect static control parts (SCoPs)", false, false)