blob: d63ab3207b17097b9a2c7872db6c083159559051 [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,
Tobias Grosser74814e12016-08-15 16:43:36 +0000179 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000180
Tobias Grosserc80d6972016-09-02 06:33:33 +0000181/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000182static 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
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000300 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000301 Loop *L = LI->getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000302 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000303 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000304 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000305
306 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000307}
308
Johannes Doerfert09e36972015-10-07 20:17:36 +0000309bool ScopDetection::onlyValidRequiredInvariantLoads(
310 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
311 Region &CurRegion = Context.CurRegion;
312
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000313 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
314 return false;
315
Johannes Doerfert09e36972015-10-07 20:17:36 +0000316 for (LoadInst *Load : RequiredILS)
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000317 if (!isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000318 return false;
319
320 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
321
322 return true;
323}
324
Michael Kruse09eb4452016-03-03 22:10:47 +0000325bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000326 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000327
328 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000329 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000330 return false;
331
332 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
333 return false;
334
335 return true;
336}
337
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000338bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000339 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000340 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000341 Loop *L = LI->getLoopFor(&BB);
342 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000343
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000344 if (IsLoopBranch && L->isLoopLatch(&BB))
345 return false;
346
Michael Kruse09eb4452016-03-03 22:10:47 +0000347 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000348 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000349
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000350 if (AllowNonAffineSubRegions &&
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000351 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
352 return true;
353
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000354 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
355 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000356}
357
358bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000359 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000360 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000361
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000362 // Constant integer conditions are always affine.
363 if (isa<ConstantInt>(Condition))
364 return true;
365
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000366 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
367 auto Opcode = BinOp->getOpcode();
368 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
369 Value *Op0 = BinOp->getOperand(0);
370 Value *Op1 = BinOp->getOperand(1);
371 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
372 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
373 }
374 }
375
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000376 // Non constant conditions of branches need to be ICmpInst.
377 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000378 if (!IsLoopBranch && AllowNonAffineSubRegions &&
379 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
380 return true;
381 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000382 }
Tobias Grosser75805372011-04-29 06:27:02 +0000383
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000384 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000385
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000386 // Are both operands of the ICmp affine?
387 if (isa<UndefValue>(ICmp->getOperand(0)) ||
388 isa<UndefValue>(ICmp->getOperand(1)))
389 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000390
Tobias Grossera2f8fa32016-11-13 19:27:04 +0000391 Loop *L = LI->getLoopFor(&BB);
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000392 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
393 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000394
Michael Kruse09eb4452016-03-03 22:10:47 +0000395 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000396 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000397
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000398 if (!IsLoopBranch && AllowNonAffineSubRegions &&
399 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
400 return true;
401
402 if (IsLoopBranch)
403 return false;
404
405 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
406 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000407}
408
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000409bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000410 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000411 DetectionContext &Context) const {
412 Region &CurRegion = Context.CurRegion;
413
414 TerminatorInst *TI = BB.getTerminator();
415
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000416 if (AllowUnreachable && isa<UnreachableInst>(TI))
417 return true;
418
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000419 // Return instructions are only valid if the region is the top level region.
420 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
421 return true;
422
423 Value *Condition = getConditionFromTerminator(TI);
424
425 if (!Condition)
426 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
427
428 // UndefValue is not allowed as condition.
429 if (isa<UndefValue>(Condition))
430 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
431
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000432 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000433 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000434
435 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
436 assert(SI && "Terminator was neither branch nor switch");
437
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000438 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000439}
440
Johannes Doerfertcea61932016-02-21 19:13:19 +0000441bool ScopDetection::isValidCallInst(CallInst &CI,
442 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000443 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000444 return false;
445
446 if (CI.doesNotAccessMemory())
447 return true;
448
Johannes Doerfertcea61932016-02-21 19:13:19 +0000449 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000450 if (isValidIntrinsicInst(*II, Context))
451 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000452
Tobias Grosser75805372011-04-29 06:27:02 +0000453 Function *CalledFunction = CI.getCalledFunction();
454
455 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000456 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000457 return false;
458
Tobias Grosser898a6362016-03-23 06:40:15 +0000459 if (AllowModrefCall) {
460 switch (AA->getModRefBehavior(CalledFunction)) {
461 case llvm::FMRB_UnknownModRefBehavior:
462 return false;
463 case llvm::FMRB_DoesNotAccessMemory:
464 case llvm::FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000465 // Implicitly disable delinearization since we have an unknown
466 // accesses with an unknown access function.
467 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000468 Context.AST.add(&CI);
469 return true;
470 case llvm::FMRB_OnlyReadsArgumentPointees:
471 case llvm::FMRB_OnlyAccessesArgumentPointees:
472 for (const auto &Arg : CI.arg_operands()) {
473 if (!Arg->getType()->isPointerTy())
474 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000475
Tobias Grosser898a6362016-03-23 06:40:15 +0000476 // Bail if a pointer argument has a base address not known to
477 // ScalarEvolution. Note that a zero pointer is acceptable.
478 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
479 if (ArgSCEV->isZero())
480 continue;
481
482 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
483 if (!BP)
484 return false;
485
486 // Implicitly disable delinearization since we have an unknown
487 // accesses with an unknown access function.
488 Context.HasUnknownAccess = true;
489 }
490
491 Context.AST.add(&CI);
492 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000493 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000494 case FMRB_OnlyAccessesInaccessibleMem:
495 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000496 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000497 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000498 }
499
Johannes Doerfertcea61932016-02-21 19:13:19 +0000500 return false;
501}
502
503bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
504 DetectionContext &Context) const {
505 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000506 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000507
Johannes Doerfertcea61932016-02-21 19:13:19 +0000508 // The closest loop surrounding the call instruction.
509 Loop *L = LI->getLoopFor(II.getParent());
510
511 // The access function and base pointer for memory intrinsics.
512 const SCEV *AF;
513 const SCEVUnknown *BP;
514
515 switch (II.getIntrinsicID()) {
516 // Memory intrinsics that can be represented are supported.
517 case llvm::Intrinsic::memmove:
518 case llvm::Intrinsic::memcpy:
519 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000520 if (!AF->isZero()) {
521 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
522 // Bail if the source pointer is not valid.
523 if (!isValidAccess(&II, AF, BP, Context))
524 return false;
525 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000526 // Fall through
527 case llvm::Intrinsic::memset:
528 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000529 if (!AF->isZero()) {
530 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
531 // Bail if the destination pointer is not valid.
532 if (!isValidAccess(&II, AF, BP, Context))
533 return false;
534 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000535
536 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000537 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000538 Context))
539 return false;
540
541 return true;
542 default:
543 break;
544 }
545
Tobias Grosser75805372011-04-29 06:27:02 +0000546 return false;
547}
548
Tobias Grosser458fb782014-01-28 12:58:58 +0000549bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
550 // A reference to function argument or constant value is invariant.
551 if (isa<Argument>(Val) || isa<Constant>(Val))
552 return true;
553
554 const Instruction *I = dyn_cast<Instruction>(&Val);
555 if (!I)
556 return false;
557
558 if (!Reg.contains(I))
559 return true;
560
561 if (I->mayHaveSideEffects())
562 return false;
563
Johannes Doerfertfbb63b82016-04-09 21:57:13 +0000564 if (isa<SelectInst>(I))
565 return false;
566
Tobias Grosser458fb782014-01-28 12:58:58 +0000567 // When Val is a Phi node, it is likely not invariant. We do not check whether
568 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000569 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000570 if (isa<PHINode>(*I))
571 return false;
572
Tobias Grosser26108892014-04-02 20:18:19 +0000573 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000574 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000575 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000576
Tobias Grosser458fb782014-01-28 12:58:58 +0000577 return true;
578}
579
Tobias Grosserc80d6972016-09-02 06:33:33 +0000580/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000581/// register the '...' components.
582///
583/// Array access expressions as they are generated by gfortran contain smax(0,
584/// size) expressions that confuse the 'normal' delinearization algorithm.
585/// However, if we extract such expressions before the normal delinearization
586/// takes place they can actually help to identify array size expressions in
587/// fortran accesses. For the subsequently following delinearization the smax(0,
588/// size) component can be replaced by just 'size'. This is correct as we will
589/// always add and verify the assumption that for all subscript expressions
590/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
591/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000592class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000593public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000594 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
595 std::vector<const SCEV *> *Terms = nullptr) {
596 SCEVRemoveMax Rewriter(SE, Terms);
597 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000598 }
599
600 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000601 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000602
603 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000604 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000605 auto Res = visit(Expr->getOperand(1));
606 if (Terms)
607 (*Terms).push_back(Res);
608 return Res;
609 }
610
611 return Expr;
612 }
613
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000614private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000615 std::vector<const SCEV *> *Terms;
616};
617
Tobias Grosserd68ba422015-11-24 05:00:36 +0000618SmallVector<const SCEV *, 4>
619ScopDetection::getDelinearizationTerms(DetectionContext &Context,
620 const SCEVUnknown *BasePointer) const {
621 SmallVector<const SCEV *, 4> Terms;
622 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000623 std::vector<const SCEV *> MaxTerms;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000624 SCEVRemoveMax::rewrite(Pair.second, *SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000625 if (MaxTerms.size() > 0) {
626 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
627 continue;
628 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000629 // In case the outermost expression is a plain add, we check if any of its
630 // terms has the form 4 * %inst * %param * %param ..., aka a term that
631 // contains a product between a parameter and an instruction that is
632 // inside the scop. Such instructions, if allowed at all, are instructions
633 // SCEV can not represent, but Polly is still looking through. As a
634 // result, these instructions can depend on induction variables and are
635 // most likely no array sizes. However, terms that are multiplied with
636 // them are likely candidates for array sizes.
637 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
638 for (auto Op : AF->operands()) {
639 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
640 SE->collectParametricTerms(AF2, Terms);
641 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
642 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000643
Tobias Grosserd68ba422015-11-24 05:00:36 +0000644 for (auto *MulOp : AF2->operands()) {
645 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
646 Operands.push_back(Const);
647 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
648 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
649 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000650 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000651
652 } else {
653 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000654 }
655 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000656 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000657 if (Operands.size())
658 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000659 }
660 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000661 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000662 if (Terms.empty())
663 SE->collectParametricTerms(Pair.second, Terms);
664 }
665 return Terms;
666}
Sebastian Pope8863b82014-05-12 19:02:02 +0000667
Tobias Grosserd68ba422015-11-24 05:00:36 +0000668bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
669 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000670 const SCEVUnknown *BasePointer,
671 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000672 Value *BaseValue = BasePointer->getValue();
673 Region &CurRegion = Context.CurRegion;
674 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000675 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000676 Sizes.clear();
677 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000678 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000679 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
680 auto *V = dyn_cast<Value>(Unknown->getValue());
681 if (auto *Load = dyn_cast<LoadInst>(V)) {
682 if (Context.CurRegion.contains(Load) &&
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000683 isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000684 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000685 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000686 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000687 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000688 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000689 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000690 Context, /*Assert=*/true, DelinearizedSize,
691 Context.Accesses[BasePointer].front().first, BaseValue);
692 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000693
Tobias Grosserd68ba422015-11-24 05:00:36 +0000694 // No array shape derived.
695 if (Sizes.empty()) {
696 if (AllowNonAffine)
697 return true;
698
Tobias Grosser230acc42014-09-13 14:47:55 +0000699 for (const auto &Pair : Context.Accesses[BasePointer]) {
700 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000701 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000702
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000703 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000704 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
705 BaseValue);
706 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000707 return false;
708 }
709 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000710 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000711 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000712 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000713}
714
Tobias Grosserd68ba422015-11-24 05:00:36 +0000715// We first store the resulting memory accesses in TempMemoryAccesses. Only
716// if the access functions for all memory accesses have been successfully
717// delinearized we continue. Otherwise, we either report a failure or, if
718// non-affine accesses are allowed, we drop the information. In case the
719// information is dropped the memory accesses need to be overapproximated
720// when translated to a polyhedral representation.
721bool ScopDetection::computeAccessFunctions(
722 DetectionContext &Context, const SCEVUnknown *BasePointer,
723 std::shared_ptr<ArrayShape> Shape) const {
724 Value *BaseValue = BasePointer->getValue();
725 bool BasePtrHasNonAffine = false;
726 MapInsnToMemAcc TempMemoryAccesses;
727 for (const auto &Pair : Context.Accesses[BasePointer]) {
728 const Instruction *Insn = Pair.first;
729 auto *AF = Pair.second;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000730 AF = SCEVRemoveMax::rewrite(AF, *SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000731 bool IsNonAffine = false;
732 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
733 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000734 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000735
736 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000737 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000738 Acc->DelinearizedSubscripts.push_back(Pair.second);
739 else
740 IsNonAffine = true;
741 } else {
742 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
743 Shape->DelinearizedSizes);
744 if (Acc->DelinearizedSubscripts.size() == 0)
745 IsNonAffine = true;
746 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000747 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000748 IsNonAffine = true;
749 }
750
751 // (Possibly) report non affine access
752 if (IsNonAffine) {
753 BasePtrHasNonAffine = true;
754 if (!AllowNonAffine)
755 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
756 Insn, BaseValue);
757 if (!KeepGoing && !AllowNonAffine)
758 return false;
759 }
760 }
761
762 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000763 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
764 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000765
766 return true;
767}
768
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000769bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
770 const SCEVUnknown *BasePointer,
771 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000772 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
773
774 auto Terms = getDelinearizationTerms(Context, BasePointer);
775
776 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
777 Context.ElementSize[BasePointer]);
778
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000779 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
780 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000781 return false;
782
783 return computeAccessFunctions(Context, BasePointer, Shape);
784}
785
786bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000787 // TODO: If we have an unknown access and other non-affine accesses we do
788 // not try to delinearize them for now.
789 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
790 return AllowNonAffine;
791
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000792 for (auto &Pair : Context.NonAffineAccesses) {
793 auto *BasePointer = Pair.first;
794 auto *Scope = Pair.second;
795 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000796 if (KeepGoing)
797 continue;
798 else
799 return false;
800 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000801 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000802 return true;
803}
804
Johannes Doerfertcea61932016-02-21 19:13:19 +0000805bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
806 const SCEVUnknown *BP,
807 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000808
Johannes Doerfertcea61932016-02-21 19:13:19 +0000809 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000810 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000811
Johannes Doerfertcea61932016-02-21 19:13:19 +0000812 auto *BV = BP->getValue();
813 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000814 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000815
Johannes Doerfertcea61932016-02-21 19:13:19 +0000816 // FIXME: Think about allowing IntToPtrInst
817 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
818 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
819
Tobias Grosser458fb782014-01-28 12:58:58 +0000820 // Check that the base address of the access is invariant in the current
821 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000822 if (!isInvariant(*BV, Context.CurRegion))
823 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000824
Johannes Doerfertcea61932016-02-21 19:13:19 +0000825 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000826
Johannes Doerfertcea61932016-02-21 19:13:19 +0000827 const SCEV *Size;
828 if (!isa<MemIntrinsic>(Inst)) {
829 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000830 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000831 auto *SizeTy =
832 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
833 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000834 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000835
Johannes Doerfertcea61932016-02-21 19:13:19 +0000836 if (Context.ElementSize[BP]) {
837 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
838 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
839 Inst, BV);
840
841 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
842 } else {
843 Context.ElementSize[BP] = Size;
844 }
845
846 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000847 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000848 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000849 for (const Loop *L : Loops)
850 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000851 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000852
Michael Kruse09eb4452016-03-03 22:10:47 +0000853 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000854 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000855 // Do not try to delinearize memory intrinsics and force them to be affine.
856 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
857 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
858 BV);
859 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
860 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000861
Johannes Doerfertcea61932016-02-21 19:13:19 +0000862 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000863 Context.NonAffineAccesses.insert(
864 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000865 } else if (!AllowNonAffine && !IsAffine) {
866 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
867 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000868 }
Tobias Grosser75805372011-04-29 06:27:02 +0000869
Tobias Grosser1eedb672014-09-24 21:04:29 +0000870 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000871 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000872
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000873 // Check if the base pointer of the memory access does alias with
874 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000875 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000876 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000877 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000878 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000879
Tobias Grosser1eedb672014-09-24 21:04:29 +0000880 if (!AS.isMustAlias()) {
881 if (PollyUseRuntimeAliasChecks) {
882 bool CanBuildRunTimeCheck = true;
883 // The run-time alias check places code that involves the base pointer at
884 // the beginning of the SCoP. This breaks if the base pointer is defined
885 // inside the scop. Hence, we can only create a run-time check if we are
886 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000887 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000888 for (const auto &Ptr : AS) {
889 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000890 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000891 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000892 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE, *DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000893 Context.RequiredILS.insert(Load);
894 continue;
895 }
896
Tobias Grosser1eedb672014-09-24 21:04:29 +0000897 CanBuildRunTimeCheck = false;
898 break;
899 }
900 }
901
902 if (CanBuildRunTimeCheck)
903 return true;
904 }
Michael Kruse70131d32016-01-27 17:09:17 +0000905 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000906 }
Tobias Grosser75805372011-04-29 06:27:02 +0000907
908 return true;
909}
910
Johannes Doerfertcea61932016-02-21 19:13:19 +0000911bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
912 DetectionContext &Context) const {
913 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000914 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000915 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
916 const SCEVUnknown *BasePointer;
917
918 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
919
920 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
921}
922
Tobias Grosser75805372011-04-29 06:27:02 +0000923bool ScopDetection::isValidInstruction(Instruction &Inst,
924 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000925 for (auto &Op : Inst.operands()) {
926 auto *OpInst = dyn_cast<Instruction>(&Op);
927
928 if (!OpInst)
929 continue;
930
931 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
932 return false;
933 }
934
Johannes Doerfert81c41b92016-04-09 21:55:58 +0000935 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
936 return false;
937
Tobias Grosser75805372011-04-29 06:27:02 +0000938 // We only check the call instruction but not invoke instruction.
939 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000940 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000941 return true;
942
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000943 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000944 }
945
946 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000947 if (!isa<AllocaInst>(Inst))
948 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000949
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000950 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000951 }
952
953 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +0000954 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000955 Context.hasStores |= isa<StoreInst>(MemInst);
956 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +0000957 if (!MemInst.isSimple())
958 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
959 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +0000960
Michael Kruse70131d32016-01-27 17:09:17 +0000961 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000962 }
Tobias Grosser75805372011-04-29 06:27:02 +0000963
964 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000965 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000966}
967
Tobias Grosser349d1c32016-09-20 17:05:22 +0000968/// Check whether @p L has exiting blocks.
969///
970/// @param L The loop of interest
971///
972/// @return True if the loop has exiting blocks, false otherwise.
973static bool hasExitingBlocks(Loop *L) {
974 SmallVector<BasicBlock *, 4> ExitingBlocks;
975 L->getExitingBlocks(ExitingBlocks);
976 return !ExitingBlocks.empty();
977}
978
Johannes Doerfertd020b772015-08-27 06:53:52 +0000979bool ScopDetection::canUseISLTripCount(Loop *L,
980 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000981 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
982 // need to overapproximate it as a boxed loop.
983 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +0000984 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +0000985 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000986 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000987 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000988 return false;
989 }
990
Johannes Doerfertd020b772015-08-27 06:53:52 +0000991 // We can use ISL to compute the trip count of L.
992 return true;
993}
994
Tobias Grosser75805372011-04-29 06:27:02 +0000995bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +0000996 // Loops that contain part but not all of the blocks of a region cannot be
997 // handled by the schedule generation. Such loop constructs can happen
998 // because a region can contain BBs that have no path to the exit block
999 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1000 // loop.
1001 //
1002 // _______________
1003 // | Loop Header | <-----------.
1004 // --------------- |
1005 // | |
1006 // _______________ ______________
1007 // | RegionEntry |-----> | RegionExit |----->
1008 // --------------- --------------
1009 // |
1010 // _______________
1011 // | EndlessLoop | <--.
1012 // --------------- |
1013 // | |
1014 // \------------/
1015 //
1016 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1017 // neither entirely contained in the region RegionEntry->RegionExit
1018 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1019 // in the loop.
1020 // The block EndlessLoop is contained in the region because Region::contains
1021 // tests whether it is not dominated by RegionExit. This is probably to not
1022 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1023 // end can also be formed by an UnreachableInst. This case is already caught
1024 // by isErrorBlock(). We hence only have to reject endless loops here.
1025 if (!hasExitingBlocks(L))
1026 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1027
Johannes Doerfertf61df692015-10-04 14:56:08 +00001028 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001029 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001030
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001031 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001032 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001033 while (R != &Context.CurRegion && !R->contains(L))
1034 R = R->getParent();
1035
1036 if (addOverApproximatedRegion(R, Context))
1037 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001038 }
Tobias Grosser75805372011-04-29 06:27:02 +00001039
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001040 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001041 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001042}
1043
Tobias Grosserc80d6972016-09-02 06:33:33 +00001044/// Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +00001045/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +00001046static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001047 auto *TripCount = SE.getBackedgeTakenCount(L);
1048
Johannes Doerfertf61df692015-10-04 14:56:08 +00001049 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001050 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001051 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1052 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1053 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001054
1055 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001056 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001057
1058 return count;
1059}
1060
Johannes Doerfertf61df692015-10-04 14:56:08 +00001061int ScopDetection::countBeneficialLoops(Region *R) const {
1062 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001063
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001064 auto L = LI->getLoopFor(R->getEntry());
1065 L = L ? R->outermostLoopInRegion(L) : nullptr;
1066 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001067
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001068 auto SubLoops =
1069 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1070
1071 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001072 if (R->contains(SubLoop))
1073 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001074
Johannes Doerfertf61df692015-10-04 14:56:08 +00001075 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001076}
1077
Tobias Grosser75805372011-04-29 06:27:02 +00001078Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001079 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001080 std::unique_ptr<Region> LastValidRegion;
1081 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001082
1083 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1084
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001085 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001086 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001087 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001088 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1089 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001090 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001091 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001092
Johannes Doerfert717b8662015-09-08 21:44:27 +00001093 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001094 // If the exit is valid check all blocks
1095 // - if true, a valid region was found => store it + keep expanding
1096 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001097 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1098 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001099 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001100 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001101 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001102
Tobias Grosserd7e58642013-04-10 06:55:45 +00001103 // Store this region, because it is the greatest valid (encountered so
1104 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001105 if (LastValidRegion) {
1106 removeCachedResults(*LastValidRegion);
1107 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1108 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001109 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001110
1111 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001112 ExpandedRegion =
1113 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001114
1115 } else {
1116 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001117 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001118 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001119 ExpandedRegion =
1120 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001121 }
Tobias Grosser75805372011-04-29 06:27:02 +00001122 }
1123
Tobias Grosser378a9f22013-11-16 19:34:11 +00001124 DEBUG({
1125 if (LastValidRegion)
1126 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1127 else
1128 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1129 });
Tobias Grosser75805372011-04-29 06:27:02 +00001130
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001131 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001132}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001133static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001134 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001135 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001136 return false;
1137
1138 return true;
1139}
Tobias Grosser75805372011-04-29 06:27:02 +00001140
Johannes Doerferte46925f2015-10-01 10:59:14 +00001141unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001142 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001143 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001144 if (ValidRegions.count(SubRegion.get())) {
1145 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001146 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001147 } else
1148 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001149 }
1150 return Count;
1151}
1152
Johannes Doerferte46925f2015-10-01 10:59:14 +00001153void ScopDetection::removeCachedResults(const Region &R) {
1154 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001155}
1156
Tobias Grosser75805372011-04-29 06:27:02 +00001157void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001158 const auto &It = DetectionContextMap.insert(std::make_pair(
1159 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001160 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001161
1162 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001163 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001164 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001165 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001166 RegionIsValid = isValidRegion(Context);
1167
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001168 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001169
Johannes Doerferte46925f2015-10-01 10:59:14 +00001170 if (HasErrors) {
1171 removeCachedResults(R);
1172 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001173 ++ValidRegion;
1174 ValidRegions.insert(&R);
1175 return;
1176 }
1177
David Blaikieb035f6d2014-04-15 18:45:27 +00001178 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001179 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001180
1181 // Try to expand regions.
1182 //
1183 // As the region tree normally only contains canonical regions, non canonical
1184 // regions that form a Scop are not found. Therefore, those non canonical
1185 // regions are checked by expanding the canonical ones.
1186
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001187 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001188
David Blaikieb035f6d2014-04-15 18:45:27 +00001189 for (auto &SubRegion : R)
1190 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001191
Tobias Grosser26108892014-04-02 20:18:19 +00001192 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001193 // Skip invalid regions. Regions may become invalid, if they are element of
1194 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001195 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001196 continue;
1197
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001198 // Skip regions that had errors.
1199 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1200 if (HadErrors)
1201 continue;
1202
Tobias Grosser75805372011-04-29 06:27:02 +00001203 Region *ExpandedR = expandRegion(*CurrentRegion);
1204
1205 if (!ExpandedR)
1206 continue;
1207
1208 R.addSubRegion(ExpandedR, true);
1209 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001210 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001211
Tobias Grosser28a70c52014-01-29 19:05:30 +00001212 // Erase all (direct and indirect) children of ExpandedR from the valid
1213 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001214 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001215 }
1216}
1217
1218bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001219 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001220
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001221 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001222 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001223 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1224 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001225 return false;
1226 }
1227
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001228 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001229 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1230
1231 // Also check exception blocks (and possibly register them as non-affine
1232 // regions). Even though exception blocks are not modeled, we use them
1233 // to forward-propagate domain constraints during ScopInfo construction.
1234 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1235 return false;
1236
1237 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001238 continue;
1239
Tobias Grosser1d191902014-03-03 13:13:55 +00001240 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001241 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001242 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001243 }
Tobias Grosser75805372011-04-29 06:27:02 +00001244
Sebastian Pope8863b82014-05-12 19:02:02 +00001245 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001246 return false;
1247
Tobias Grosser75805372011-04-29 06:27:02 +00001248 return true;
1249}
1250
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001251bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1252 int NumLoops) const {
1253 int InstCount = 0;
1254
Tobias Grosserb316dc12016-09-08 14:08:05 +00001255 if (NumLoops == 0)
1256 return false;
1257
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001258 for (auto *BB : Context.CurRegion.blocks())
1259 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001260 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001261
1262 InstCount = InstCount / NumLoops;
1263
1264 return InstCount >= ProfitabilityMinPerLoopInstructions;
1265}
1266
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001267bool ScopDetection::hasPossiblyDistributableLoop(
1268 DetectionContext &Context) const {
1269 for (auto *BB : Context.CurRegion.blocks()) {
1270 auto *L = LI->getLoopFor(BB);
1271 if (!Context.CurRegion.contains(L))
1272 continue;
1273 if (Context.BoxedLoopsSet.count(L))
1274 continue;
1275 unsigned StmtsWithStoresInLoops = 0;
1276 for (auto *LBB : L->blocks()) {
1277 bool MemStore = false;
1278 for (auto &I : *LBB)
1279 MemStore |= isa<StoreInst>(&I);
1280 StmtsWithStoresInLoops += MemStore;
1281 }
1282 return (StmtsWithStoresInLoops > 1);
1283 }
1284 return false;
1285}
1286
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001287bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1288 Region &CurRegion = Context.CurRegion;
1289
1290 if (PollyProcessUnprofitable)
1291 return true;
1292
1293 // We can probably not do a lot on scops that only write or only read
1294 // data.
1295 if (!Context.hasStores || !Context.hasLoads)
1296 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1297
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001298 int NumLoops = countBeneficialLoops(&CurRegion);
1299 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001300
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001301 // Scops with at least two loops may allow either loop fusion or tiling and
1302 // are consequently interesting to look at.
1303 if (NumAffineLoops >= 2)
1304 return true;
1305
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001306 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1307 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1308 return true;
1309
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001310 // Scops that contain a loop with a non-trivial amount of computation per
1311 // loop-iteration are interesting as we may be able to parallelize such
1312 // loops. Individual loops that have only a small amount of computation
1313 // per-iteration are performance-wise very fragile as any change to the
1314 // loop induction variables may affect performance. To not cause spurious
1315 // performance regressions, we do not consider such loops.
1316 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1317 return true;
1318
1319 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001320}
1321
Tobias Grosser75805372011-04-29 06:27:02 +00001322bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001323 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001324
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001325 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001326
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001327 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001328 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001329 return false;
1330 }
1331
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001332 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001333 DEBUG({
1334 dbgs() << "Region entry does not match -polly-region-only";
1335 dbgs() << "\n";
1336 });
1337 return false;
1338 }
1339
Tobias Grosserd654c252012-04-10 18:12:19 +00001340 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001341 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001342 if (CurRegion.getEntry() ==
1343 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1344 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001345
Hongbin Zheng94868e62012-04-07 12:29:17 +00001346 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001347 return false;
1348
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001349 DebugLoc DbgLoc;
1350 if (!isReducibleRegion(CurRegion, DbgLoc))
1351 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1352 &CurRegion, DbgLoc);
1353
Tobias Grosser75805372011-04-29 06:27:02 +00001354 DEBUG(dbgs() << "OK\n");
1355 return true;
1356}
1357
Tobias Grosser629109b2016-08-03 12:00:07 +00001358void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001359 F->addFnAttr(PollySkipFnAttr);
1360}
1361
Tobias Grosser75805372011-04-29 06:27:02 +00001362bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001363 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001364}
1365
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001366void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001367 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001368 unsigned LineEntry, LineExit;
1369 std::string FileName;
1370
Tobias Grosser00dc3092014-03-02 12:02:46 +00001371 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001372 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1373 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001374 }
1375}
1376
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001377void ScopDetection::emitMissedRemarks(const Function &F) {
1378 for (auto &DIt : DetectionContextMap) {
1379 auto &DC = DIt.getSecond();
1380 if (DC.Log.hasErrors())
1381 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001382 }
1383}
1384
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001385bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001386 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001387 ///
1388 /// WHITE - Unvisited BB in DFS walk.
1389 /// GREY - BBs which are currently on the DFS stack for processing.
1390 /// BLACK - Visited and completely processed BB.
1391 enum Color { WHITE, GREY, BLACK };
1392
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001393 BasicBlock *REntry = R.getEntry();
1394 BasicBlock *RExit = R.getExit();
1395 // Map to match the color of a BasicBlock during the DFS walk.
1396 DenseMap<const BasicBlock *, Color> BBColorMap;
1397 // Stack keeping track of current BB and index of next child to be processed.
1398 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1399
1400 unsigned AdjacentBlockIndex = 0;
1401 BasicBlock *CurrBB, *SuccBB;
1402 CurrBB = REntry;
1403
1404 // Initialize the map for all BB with WHITE color.
1405 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001406 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001407
1408 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001409 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001410 DFSStack.push(std::make_pair(CurrBB, 0));
1411
1412 while (!DFSStack.empty()) {
1413 // Get next BB on stack to be processed.
1414 CurrBB = DFSStack.top().first;
1415 AdjacentBlockIndex = DFSStack.top().second;
1416 DFSStack.pop();
1417
1418 // Loop to iterate over the successors of current BB.
1419 const TerminatorInst *TInst = CurrBB->getTerminator();
1420 unsigned NSucc = TInst->getNumSuccessors();
1421 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1422 ++I, ++AdjacentBlockIndex) {
1423 SuccBB = TInst->getSuccessor(I);
1424
1425 // Checks for region exit block and self-loops in BB.
1426 if (SuccBB == RExit || SuccBB == CurrBB)
1427 continue;
1428
1429 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001430 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001431 // Push the current BB and the index of the next child to be visited.
1432 DFSStack.push(std::make_pair(CurrBB, I + 1));
1433 // Push the next BB to be processed.
1434 DFSStack.push(std::make_pair(SuccBB, 0));
1435 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001436 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001437 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001438 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001439 // GREY indicates a loop in the control flow.
1440 // If the destination dominates the source, it is a natural loop
1441 // else, an irreducible control flow in the region is detected.
1442 if (!DT->dominates(SuccBB, CurrBB)) {
1443 // Get debug info of instruction which causes irregular control flow.
1444 DbgLoc = TInst->getDebugLoc();
1445 return false;
1446 }
1447 }
1448 }
1449
1450 // If all children of current BB have been processed,
1451 // then mark that BB as fully processed.
1452 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001453 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001454 }
1455
1456 return true;
1457}
1458
Tobias Grosser75805372011-04-29 06:27:02 +00001459bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001460 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001461 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001462 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001463 return false;
1464
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001465 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001466 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001467 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001468 Region *TopRegion = RI->getTopLevelRegion();
1469
Tobias Grosser2ff87232011-10-23 11:17:06 +00001470 releaseMemory();
1471
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001472 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001473 return false;
1474
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001475 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001476 return false;
1477
1478 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001479
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001480 // Prune non-profitable regions.
1481 for (auto &DIt : DetectionContextMap) {
1482 auto &DC = DIt.getSecond();
1483 if (DC.Log.hasErrors())
1484 continue;
1485 if (!ValidRegions.count(&DC.CurRegion))
1486 continue;
1487 if (isProfitableRegion(DC))
1488 continue;
1489
1490 ValidRegions.remove(&DC.CurRegion);
1491 }
1492
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001493 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001494 if (PollyTrackFailures)
1495 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001496
Johannes Doerferta05214f2014-10-15 23:24:28 +00001497 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001498 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001499
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001500 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001501 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001502 return false;
1503}
1504
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001505ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001506ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001507 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001508 if (DCMIt == DetectionContextMap.end())
1509 return nullptr;
1510 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001511}
1512
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001513const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1514 const DetectionContext *DC = getDetectionContext(R);
1515 return DC ? &DC->Log : nullptr;
1516}
1517
Tobias Grosser75805372011-04-29 06:27:02 +00001518void polly::ScopDetection::verifyRegion(const Region &R) const {
1519 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001520
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001521 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001522 isValidRegion(Context);
1523}
1524
1525void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001526 if (!VerifyScops)
1527 return;
1528
Tobias Grosser26108892014-04-02 20:18:19 +00001529 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001530 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001531}
1532
1533void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001534 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001535 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001536 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001537 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001538 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001539 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001540 AU.setPreservesAll();
1541}
1542
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001543void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001544 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001545 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001546
1547 OS << "\n";
1548}
1549
1550void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001551 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001552 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001553
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001554 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001555}
1556
1557char ScopDetection::ID = 0;
1558
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001559Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1560
Tobias Grosser73600b82011-10-08 00:30:40 +00001561INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1562 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001563 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001564INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001565INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001566INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001567INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001568INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001569INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1570 "Polly - Detect static control parts (SCoPs)", false, false)