blob: 18461d0829329f6a59fda896881a1349f3937d86 [file] [log] [blame]
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001//===- ScopInfo.cpp -------------------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
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// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000023#include "polly/ScopBuilder.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000024#include "polly/ScopDetection.h"
Tobias Grosser75805372011-04-29 06:27:02 +000025#include "polly/Support/GICHelper.h"
Tobias Grosser77eef902017-07-21 23:07:56 +000026#include "polly/Support/ISLOStream.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000027#include "polly/Support/SCEVAffinator.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000028#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "polly/Support/ScopHelper.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000030#include "llvm/ADT/APInt.h"
31#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/DenseSet.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000034#include "llvm/ADT/PostOrderIterator.h"
35#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000036#include "llvm/ADT/SetVector.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000037#include "llvm/ADT/SmallPtrSet.h"
38#include "llvm/ADT/SmallSet.h"
39#include "llvm/ADT/SmallVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000040#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000041#include "llvm/ADT/StringExtras.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000042#include "llvm/ADT/StringMap.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000043#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000044#include "llvm/Analysis/AliasSetTracker.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000045#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000046#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000048#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
49#include "llvm/Analysis/RegionInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000050#include "llvm/Analysis/RegionIterator.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000051#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosser83628182013-05-07 08:11:54 +000052#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000053#include "llvm/IR/Argument.h"
54#include "llvm/IR/BasicBlock.h"
55#include "llvm/IR/CFG.h"
56#include "llvm/IR/ConstantRange.h"
57#include "llvm/IR/Constants.h"
58#include "llvm/IR/DataLayout.h"
59#include "llvm/IR/DebugLoc.h"
60#include "llvm/IR/DerivedTypes.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000061#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000062#include "llvm/IR/Dominators.h"
63#include "llvm/IR/Function.h"
64#include "llvm/IR/InstrTypes.h"
65#include "llvm/IR/Instruction.h"
66#include "llvm/IR/Instructions.h"
67#include "llvm/IR/IntrinsicInst.h"
68#include "llvm/IR/Module.h"
69#include "llvm/IR/PassManager.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
74#include "llvm/Pass.h"
75#include "llvm/Support/Casting.h"
76#include "llvm/Support/CommandLine.h"
77#include "llvm/Support/Compiler.h"
Tobias Grosser75805372011-04-29 06:27:02 +000078#include "llvm/Support/Debug.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000079#include "llvm/Support/ErrorHandling.h"
80#include "llvm/Support/MathExtras.h"
81#include "llvm/Support/raw_ostream.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000082#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000083#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000084#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000085#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000086#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000087#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000088#include "isl/schedule.h"
89#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000090#include "isl/set.h"
91#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000092#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000093#include "isl/val.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000094#include <algorithm>
95#include <cassert>
96#include <cstdlib>
97#include <cstring>
98#include <deque>
99#include <iterator>
100#include <memory>
Tobias Grosser75805372011-04-29 06:27:02 +0000101#include <string>
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000102#include <tuple>
103#include <utility>
Tobias Grosser75805372011-04-29 06:27:02 +0000104#include <vector>
105
106using namespace llvm;
107using namespace polly;
108
Chandler Carruth95fef942014-04-22 03:30:19 +0000109#define DEBUG_TYPE "polly-scops"
110
Johannes Doerfert81aa6e82016-11-18 14:37:08 +0000111STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
112STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
113STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
114STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
115STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
116STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
117STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
118STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
119STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +0000120 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +0000121STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +0000122 "Number of delinearization assumptions taken.");
123
Michael Kruse06ed5292017-08-23 13:50:30 +0000124STATISTIC(NumScops, "Number of feasible SCoPs after ScopInfo");
Tobias Grossercd01a362017-02-17 08:12:36 +0000125STATISTIC(NumLoopsInScop, "Number of loops in scops");
Michael Kruse06ed5292017-08-23 13:50:30 +0000126STATISTIC(NumBoxedLoops, "Number of boxed loops in SCoPs after ScopInfo");
127STATISTIC(NumAffineLoops, "Number of affine loops in SCoPs after ScopInfo");
128
Tobias Grossercd01a362017-02-17 08:12:36 +0000129STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
130STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
131STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
132STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
133STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
134STATISTIC(NumScopsDepthLarger,
135 "Number of scops with maximal loop depth 6 and larger");
136STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
137
Michael Kruse06ed5292017-08-23 13:50:30 +0000138STATISTIC(NumValueWrites, "Number of scalar value writes after ScopInfo");
139STATISTIC(
140 NumValueWritesInLoops,
141 "Number of scalar value writes nested in affine loops after ScopInfo");
142STATISTIC(NumPHIWrites, "Number of scalar phi writes after ScopInfo");
143STATISTIC(NumPHIWritesInLoops,
144 "Number of scalar phi writes nested in affine loops after ScopInfo");
145STATISTIC(NumSingletonWrites, "Number of singleton writes after ScopInfo");
146STATISTIC(NumSingletonWritesInLoops,
147 "Number of singleton writes nested in affine loops after ScopInfo");
148
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000149// The maximal number of basic sets we allow during domain construction to
150// be created. More complex scops will result in very high compile time and
151// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +0000152static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000153
Tobias Grosserc8a82762017-02-16 19:11:25 +0000154// The number of disjunct in the context after which we stop to add more
155// disjuncts. This parameter is there to avoid exponential growth in the
156// number of disjunct when adding non-convex sets to the context.
157static int const MaxDisjunctsInContext = 4;
158
Tobias Grosser1eeedf42017-07-20 19:55:19 +0000159// The maximal number of dimensions we allow during invariant load construction.
160// More complex access ranges will result in very high compile time and are also
161// unlikely to result in good code. This value is very high and should only
162// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
163static int const MaxDimensionsInAccessRange = 9;
164
Tobias Grosser97715842017-05-19 04:01:52 +0000165static cl::opt<int>
166 OptComputeOut("polly-analysis-computeout",
167 cl::desc("Bound the scop analysis by a maximal amount of "
168 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000169 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000170 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000171
Johannes Doerfert2f705842016-04-12 16:09:44 +0000172static cl::opt<bool> PollyRemarksMinimal(
173 "polly-remarks-minimal",
174 cl::desc("Do not emit remarks about assumptions that are known"),
175 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
176
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000177static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
178 "polly-rtc-max-array-disjuncts",
179 cl::desc("The maximal number of disjunts allowed in memory accesses to "
180 "to build RTCs."),
181 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
182
Johannes Doerfert9143d672014-09-27 11:02:39 +0000183static cl::opt<unsigned> RunTimeChecksMaxParameters(
184 "polly-rtc-max-parameters",
185 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
186 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
187
Tobias Grosser71500722015-03-28 15:11:14 +0000188static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
189 "polly-rtc-max-arrays-per-group",
190 cl::desc("The maximal number of arrays to compare in each alias group."),
191 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000192
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000193static cl::opt<std::string> UserContextStr(
194 "polly-context", cl::value_desc("isl parameter set"),
195 cl::desc("Provide additional constraints on the context parameters"),
196 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000197
Tobias Grosser2937b592016-04-29 11:43:20 +0000198static cl::opt<bool>
199 IslOnErrorAbort("polly-on-isl-error-abort",
200 cl::desc("Abort if an isl error is encountered"),
201 cl::init(true), cl::cat(PollyCategory));
202
Tobias Grosserd7c49752017-02-28 09:45:54 +0000203static cl::opt<bool> PollyPreciseInbounds(
204 "polly-precise-inbounds",
205 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
206 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
207
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000208static cl::opt<bool>
209 PollyIgnoreInbounds("polly-ignore-inbounds",
210 cl::desc("Do not take inbounds assumptions at all"),
211 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
212
Tobias Grosser5842dee2017-03-17 13:00:53 +0000213static cl::opt<bool> PollyIgnoreParamBounds(
214 "polly-ignore-parameter-bounds",
215 cl::desc(
216 "Do not add parameter bounds and do no gist simplify sets accordingly"),
217 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
218
Siddharth Bhat7bc77e82017-08-21 11:57:04 +0000219static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams(
220 "polly-allow-dereference-of-all-function-parameters",
221 cl::desc(
222 "Treat all parameters to functions that are pointers as dereferencible."
223 " This is useful for invariant load hoisting, since we can generate"
224 " less runtime checks. This is only valid if all pointers to functions"
225 " are always initialized, so that Polly can choose to hoist"
226 " their loads. "),
227 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
228
Tobias Grosserc2f15102017-03-01 21:11:27 +0000229static cl::opt<bool> PollyPreciseFoldAccesses(
230 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000231 cl::desc("Fold memory accesses to model more possible delinearizations "
232 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000233 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000234
Michael Kruse5ae08c02017-05-06 14:03:58 +0000235bool polly::UseInstructionNames;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000236
Michael Kruse5ae08c02017-05-06 14:03:58 +0000237static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000238 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000239 cl::desc("Use LLVM-IR names when deriving statement names"),
240 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
241 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000242
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000243static cl::opt<bool> PollyPrintInstructions(
244 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
245 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
246
Michael Kruse7bf39442015-09-10 12:46:52 +0000247//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000248
Michael Kruse046dde42015-08-10 13:01:57 +0000249// Create a sequence of two schedules. Either argument may be null and is
250// interpreted as the empty schedule. Can also return null if both schedules are
251// empty.
252static __isl_give isl_schedule *
253combineInSequence(__isl_take isl_schedule *Prev,
254 __isl_take isl_schedule *Succ) {
255 if (!Prev)
256 return Succ;
257 if (!Succ)
258 return Prev;
259
260 return isl_schedule_sequence(Prev, Succ);
261}
262
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000263static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
264 int dim, isl::dim type) {
265 isl::val V;
266 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000267
Tobias Grosser3281f602017-02-16 18:39:14 +0000268 // The upper and lower bound for a parameter value is derived either from
269 // the data type of the parameter or from the - possibly more restrictive -
270 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000271 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
272 S = S.lower_bound_val(type, dim, V);
273 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
274 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000275
Tobias Grosser3281f602017-02-16 18:39:14 +0000276 if (Range.isFullSet())
277 return S;
278
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000279 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000280 return S;
281
Tobias Grosser3281f602017-02-16 18:39:14 +0000282 // In case of signed wrapping, we can refine the set of valid values by
283 // excluding the part not covered by the wrapping range.
284 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000285 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
286 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000287
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000288 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
289 V = V.sub_ui(1);
290 isl::set SUB = S.upper_bound_val(type, dim, V);
291 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000292 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000293
Tobias Grosser3281f602017-02-16 18:39:14 +0000294 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000295}
296
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000297static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
298 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
299 if (!BasePtrLI)
300 return nullptr;
301
Johannes Doerfert952b5302016-05-23 12:40:48 +0000302 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000303 return nullptr;
304
305 ScalarEvolution &SE = *S->getSE();
306
307 auto *OriginBaseSCEV =
308 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
309 if (!OriginBaseSCEV)
310 return nullptr;
311
312 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
313 if (!OriginBaseSCEVUnknown)
314 return nullptr;
315
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000316 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000317 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000318}
319
Tobias Grosser27db02b2017-08-06 17:25:05 +0000320ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000321 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000322 const DataLayout &DL, Scop *S,
323 const char *BaseName)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000324 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000325 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000326 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000327 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
328 Kind == MemoryKind::PHI ? "__phi" : "",
329 UseInstructionNames);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000330 Id = isl::id::alloc(Ctx, BasePtrName, this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000331
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000332 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000333
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000334 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000335 BasePtrOriginSAI = nullptr;
336 return;
337 }
338
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000339 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
340 if (BasePtrOriginSAI)
341 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000342}
343
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000344ScopArrayInfo::~ScopArrayInfo() = default;
345
Tobias Grosser77eef902017-07-21 23:07:56 +0000346isl::space ScopArrayInfo::getSpace() const {
347 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
348 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000349 return Space;
350}
351
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000352bool ScopArrayInfo::isReadOnly() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +0000353 isl::union_set WriteSet = S.getWrites().range();
Tobias Grosser77eef902017-07-21 23:07:56 +0000354 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000355 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000356
Tobias Grosser2ade9862017-05-23 06:41:04 +0000357 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000358}
359
Tobias Grosserf3adab42017-05-10 10:59:58 +0000360bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
361 if (Array->getElementType() != getElementType())
362 return false;
363
364 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
365 return false;
366
367 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
368 if (Array->getDimensionSize(i) != getDimensionSize(i))
369 return false;
370
371 return true;
372}
373
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000374void ScopArrayInfo::updateElementType(Type *NewElementType) {
375 if (NewElementType == ElementType)
376 return;
377
Tobias Grosserd840fc72016-02-04 13:18:42 +0000378 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
379 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
380
Johannes Doerferta7920982016-02-25 14:08:48 +0000381 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000382 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000383
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000384 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
385 ElementType = NewElementType;
386 } else {
387 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
388 ElementType = IntegerType::get(ElementType->getContext(), GCD);
389 }
390}
391
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000392/// Make the ScopArrayInfo model a Fortran Array
393void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
394 assert(FAD && "got invalid Fortran array descriptor");
395 if (this->FAD) {
396 assert(this->FAD == FAD &&
397 "receiving different array descriptors for same array");
398 return;
399 }
400
401 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
402 assert(!this->FAD);
403 this->FAD = FAD;
404
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000405 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000406
407 std::string param_name = getName();
408 param_name += "_fortranarr_size";
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000409 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000410
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000411 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
412 isl::pw_aff PwAff =
413 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000414
Tobias Grosser77eef902017-07-21 23:07:56 +0000415 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000416}
417
Tobias Grosserbedef002016-12-02 08:10:56 +0000418bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
419 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000420 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
421 int ExtraDimsNew = NewSizes.size() - SharedDims;
422 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000423
Tobias Grosserbedef002016-12-02 08:10:56 +0000424 if (CheckConsistency) {
425 for (int i = 0; i < SharedDims; i++) {
426 auto *NewSize = NewSizes[i + ExtraDimsNew];
427 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
428 if (NewSize && KnownSize && NewSize != KnownSize)
429 return false;
430 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000431
Tobias Grosserbedef002016-12-02 08:10:56 +0000432 if (DimensionSizes.size() >= NewSizes.size())
433 return true;
434 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000435
436 DimensionSizes.clear();
437 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
438 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000439 DimensionSizesPw.clear();
440 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000441 if (!Expr) {
442 DimensionSizesPw.push_back(nullptr);
443 continue;
444 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000445 isl::pw_aff Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000446 DimensionSizesPw.push_back(Size);
447 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000448 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000449}
450
Tobias Grosser77eef902017-07-21 23:07:56 +0000451std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000452
453int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000454 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000455}
456
Tobias Grosser77eef902017-07-21 23:07:56 +0000457isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000458
Michael Kruse5d518462017-07-21 15:54:07 +0000459#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000460LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000461#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000462
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000463void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000464 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000465 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000466 // If this is a Fortran array, then we can print the outermost dimension
467 // as a isl_pw_aff even though there is no SCEV information.
468 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
469
470 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
471 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000472 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000473 u++;
474 }
475 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000476 OS << "[";
477
Tobias Grosser26253842015-11-10 14:24:21 +0000478 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000479 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000480 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000481 } else {
482 OS << *getDimensionSize(u);
483 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000484
485 OS << "]";
486 }
487
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000488 OS << ";";
489
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000490 if (BasePtrOriginSAI)
491 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
492
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000493 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000494}
495
496const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000497ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
498 isl::id Id = PMA.get_tuple_id(isl::dim::out);
499 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000500 return getFromId(Id);
501}
502
Tobias Grosser206e9e32017-07-24 16:22:27 +0000503const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
504 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000505 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000506 return SAI;
507}
508
Michael Kruse3b425ff2016-04-11 14:34:08 +0000509void MemoryAccess::wrapConstantDimensions() {
510 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000511 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000512 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000513 unsigned DimsArray = SAI->getNumberOfDimensions();
514
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000515 isl::multi_aff DivModAff = isl::multi_aff::identity(
516 ArraySpace.map_from_domain_and_range(ArraySpace));
517 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000518
519 // Begin with last dimension, to iteratively carry into higher dimensions.
520 for (int i = DimsArray - 1; i > 0; i--) {
521 auto *DimSize = SAI->getDimensionSize(i);
522 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
523
524 // This transformation is not applicable to dimensions with dynamic size.
525 if (!DimSizeCst)
526 continue;
527
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000528 // This transformation is not applicable to dimensions of size zero.
529 if (DimSize->isZero())
530 continue;
531
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000532 isl::val DimSizeVal =
533 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
534 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
535 isl::aff PrevVar =
536 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000537
538 // Compute: index % size
539 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grossercb0224a2017-08-06 15:56:45 +0000540 isl::aff Modulo = Var.mod(DimSizeVal);
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000541 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000542
543 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000544 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
545 Divide = Divide.floor();
546 Divide = Divide.add(PrevVar);
547 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000548
549 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000550 DivModAff = DivModAff.set_aff(i, Modulo);
551 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000552 }
553
554 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000555 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000556 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
557 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000558 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000559}
560
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000561void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000562 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000563 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000564 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000565 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000566
Tobias Grosser7be82452017-05-21 20:38:33 +0000567 auto DimsArray = ArraySpace.dim(isl::dim::set);
568 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000569 auto DimsMissing = DimsArray - DimsAccess;
570
Michael Kruse375cb5f2016-02-24 22:08:24 +0000571 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000572 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000573 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000574 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000575
Tobias Grosser7be82452017-05-21 20:38:33 +0000576 isl::map Map = isl::map::from_domain_and_range(
577 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000578
579 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000580 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000581
582 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000583 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000584
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000585 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000586
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000587 // For the non delinearized arrays, divide the access function of the last
588 // subscript by the size of the elements in the array.
589 //
590 // A stride one array access in C expressed as A[i] is expressed in
591 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
592 // two subsequent values of 'i' index two values that are stored next to
593 // each other in memory. By this division we make this characteristic
594 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000595 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000596 // that divides the offsets of all accesses to this base pointer.
597 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000598 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000599 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000600 }
601
Michael Kruse3b425ff2016-04-11 14:34:08 +0000602 // We currently do this only if we added at least one dimension, which means
603 // some dimension's indices have not been specified, an indicator that some
604 // index values have been added together.
605 // TODO: Investigate general usefulness; Effect on unit tests is to make index
606 // expressions more complicated.
607 if (DimsMissing)
608 wrapConstantDimensions();
609
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000610 if (!isAffine())
611 computeBoundsOnAccessRelation(ArrayElemSize);
612
Tobias Grosserd840fc72016-02-04 13:18:42 +0000613 // Introduce multi-element accesses in case the type loaded by this memory
614 // access is larger than the canonical element type of the array.
615 //
616 // An access ((float *)A)[i] to an array char *A is modeled as
617 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000618 if (ElemBytes > ArrayElemSize) {
619 assert(ElemBytes % ArrayElemSize == 0 &&
620 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000621 isl::map Map = isl::map::from_domain_and_range(
622 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000623 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000624 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000625
Tobias Grosser7be82452017-05-21 20:38:33 +0000626 isl::constraint C;
627 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000628
Tobias Grosser7be82452017-05-21 20:38:33 +0000629 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000630 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
631
Tobias Grosser7be82452017-05-21 20:38:33 +0000632 C = isl::constraint::alloc_inequality(LS);
633 C = C.set_constant_val(isl::val(Ctx, Num - 1));
634 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
635 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
636 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000637
Tobias Grosser7be82452017-05-21 20:38:33 +0000638 C = isl::constraint::alloc_inequality(LS);
639 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
640 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
641 C = C.set_constant_val(isl::val(Ctx, 0));
642 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000643 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000644 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000645}
646
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000647const std::string
648MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
649 switch (RT) {
650 case MemoryAccess::RT_NONE:
651 llvm_unreachable("Requested a reduction operator string for a memory "
652 "access which isn't a reduction");
653 case MemoryAccess::RT_ADD:
654 return "+";
655 case MemoryAccess::RT_MUL:
656 return "*";
657 case MemoryAccess::RT_BOR:
658 return "|";
659 case MemoryAccess::RT_BXOR:
660 return "^";
661 case MemoryAccess::RT_BAND:
662 return "&";
663 }
664 llvm_unreachable("Unknown reduction type");
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000665}
666
Michael Kruse2fa35192016-09-01 19:53:31 +0000667const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000668 isl::id ArrayId = getArrayId();
669 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000670 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000671 return SAI;
672}
673
Michael Kruse2fa35192016-09-01 19:53:31 +0000674const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000675 isl::id ArrayId = getLatestArrayId();
676 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000677 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000678 return SAI;
679}
680
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000681isl::id MemoryAccess::getOriginalArrayId() const {
682 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000683}
684
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000685isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000686 if (!hasNewAccessRelation())
687 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000688 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000689}
690
Tobias Grosser6a870362017-07-23 04:08:45 +0000691isl::map MemoryAccess::getAddressFunction() const {
692 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000693}
694
Tobias Grosser3b196132017-07-23 04:08:52 +0000695isl::pw_multi_aff
696MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
697 isl::map Schedule, ScheduledAccRel;
698 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000699
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000700 UDomain = getStatement()->getDomain();
Tobias Grosser3b196132017-07-23 04:08:52 +0000701 USchedule = USchedule.intersect_domain(UDomain);
702 Schedule = isl::map::from_union_map(USchedule);
703 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
704 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000705}
706
Tobias Grosser22da5f02017-07-23 04:08:27 +0000707isl::map MemoryAccess::getOriginalAccessRelation() const {
708 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000709}
710
Johannes Doerferta99130f2014-10-13 12:58:03 +0000711std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000712 return stringFromIslObj(AccessRelation.get());
Tobias Grosser5d453812011-10-06 00:04:11 +0000713}
714
Tobias Grosser22da5f02017-07-23 04:08:27 +0000715isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
716 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000717}
718
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000719isl::map MemoryAccess::getNewAccessRelation() const {
720 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000721}
722
Tobias Grosser6f730082015-09-05 07:46:47 +0000723std::string MemoryAccess::getNewAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000724 return stringFromIslObj(NewAccessRelation.get());
Tobias Grosser6f730082015-09-05 07:46:47 +0000725}
726
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000727std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser2b7479b2017-08-06 11:41:10 +0000728 return getAccessRelation().to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000729}
730
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000731isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
732 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000733 Space = Space.align_params(Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000734
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000735 return isl::basic_map::from_domain_and_range(
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000736 isl::basic_set::universe(Statement->getDomainSpace()),
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000737 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000738}
739
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000740// Formalize no out-of-bound access assumption
741//
742// When delinearizing array accesses we optimistically assume that the
743// delinearized accesses do not access out of bound locations (the subscript
744// expression of each array evaluates for each statement instance that is
745// executed to a value that is larger than zero and strictly smaller than the
746// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000747// dimension for which we do not need to assume any upper bound. At this point
748// we formalize this assumption to ensure that at code generation time the
749// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000750//
751// To find the set of constraints necessary to avoid out of bound accesses, we
752// first build the set of data locations that are not within array bounds. We
753// then apply the reverse access relation to obtain the set of iterations that
754// may contain invalid accesses and reduce this set of iterations to the ones
755// that are actually executed by intersecting them with the domain of the
756// statement. If we now project out all loop dimensions, we obtain a set of
757// parameters that may cause statement instances to be executed that may
758// possibly yield out of bound memory accesses. The complement of these
759// constraints is the set of constraints that needs to be assumed to ensure such
760// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000761void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000762 if (PollyIgnoreInbounds)
763 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000764 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000765 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000766 isl::set Outside = isl::set::empty(Space);
767 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
768 isl::local_space LS(Space);
769 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
770 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000771
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000772 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000773 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000774 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
775 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
776 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000777
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000778 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000779 }
780
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000781 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000782 Outside = Outside.intersect(Statement->getDomain());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000783 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000784
785 // Remove divs to avoid the construction of overly complicated assumptions.
786 // Doing so increases the set of parameter combinations that are assumed to
787 // not appear. This is always save, but may make the resulting run-time check
788 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000789 Outside = Outside.remove_divs();
790 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000791 const auto &Loc = getAccessInstruction()
792 ? getAccessInstruction()->getDebugLoc()
793 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000794 if (!PollyPreciseInbounds)
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000795 Outside = Outside.gist_params(Statement->getDomain().params());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000796 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000797 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000798}
799
Johannes Doerfertcea61932016-02-21 19:13:19 +0000800void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000801 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000802 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000803
Tobias Grossercdf471b2017-07-24 16:36:34 +0000804 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000805 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000806
Tobias Grosser53fc3552017-05-23 07:07:09 +0000807 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000808 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000809 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000810 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000811 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000812 LengthMap = isl::map::from_pw_aff(LengthPWA);
813 isl::space RangeSpace = LengthMap.get_space().range();
814 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000815 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000816 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
817 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
818 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
819 LengthMap = LengthMap.sum(SubscriptMap);
820 AccessRelation =
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000821 LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000822}
823
Johannes Doerferte7044942015-02-24 11:58:30 +0000824void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
825 ScalarEvolution *SE = Statement->getParent()->getSE();
826
Johannes Doerfertcea61932016-02-21 19:13:19 +0000827 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000828 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000829 return;
830
831 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000832 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
833 return;
834
835 auto *PtrSCEV = SE->getSCEV(Ptr);
836 if (isa<SCEVCouldNotCompute>(PtrSCEV))
837 return;
838
839 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
840 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
841 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
842
843 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
844 if (Range.isFullSet())
845 return;
846
Michael Kruse960c0d02017-05-18 21:55:36 +0000847 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000848 return;
849
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000850 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000851
Johannes Doerferte7044942015-02-24 11:58:30 +0000852 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000853 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000854 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000855 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000856
857 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000858 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000859
Tobias Grosserb3a85882017-02-12 08:11:12 +0000860 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
861
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000862 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000863 isl::set AccessRange = Relation.range();
864 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
865 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000866 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000867}
868
Tobias Grosser491b7992016-12-02 05:21:22 +0000869void MemoryAccess::foldAccessRelation() {
870 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
871 return;
872
Michael Krusee2bccbb2015-09-18 19:59:43 +0000873 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000874
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000875 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000876
Tobias Grosser619190d2015-03-30 17:22:28 +0000877 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000878 isl::space Space;
879 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000880 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000881
Tobias Grossera32de132017-05-23 07:22:56 +0000882 isl::space SpaceSize = DimSize.get_space();
883 isl::id ParamId =
884 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000885
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000886 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000887 Space = Space.range().map_from_set();
888 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000889
Tobias Grossera32de132017-05-23 07:22:56 +0000890 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000891
Tobias Grossera32de132017-05-23 07:22:56 +0000892 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000893 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000894 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
895 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000896
Tobias Grossera32de132017-05-23 07:22:56 +0000897 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000898 for (int j = 0; j < Size; ++j)
899 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000900 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000901
Tobias Grossera32de132017-05-23 07:22:56 +0000902 isl::local_space LS(Space);
903 isl::constraint C;
904 C = isl::constraint::alloc_equality(LS);
905 C = C.set_constant_si(-1);
906 C = C.set_coefficient_si(isl::dim::in, i, 1);
907 C = C.set_coefficient_si(isl::dim::out, i, -1);
908 MapTwo = MapTwo.add_constraint(C);
909 C = isl::constraint::alloc_equality(LS);
910 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
911 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
912 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
913 MapTwo = MapTwo.add_constraint(C);
914 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000915
Tobias Grossera32de132017-05-23 07:22:56 +0000916 MapOne = MapOne.unite(MapTwo);
917 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000918 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000919
Tobias Grosser77eef902017-07-21 23:07:56 +0000920 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000921 isl::space Space = Statement->getDomainSpace();
Tobias Grossera32de132017-05-23 07:22:56 +0000922 NewAccessRelation = NewAccessRelation.set_tuple_id(
923 isl::dim::in, Space.get_tuple_id(isl::dim::set));
924 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000925 NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000926
927 // Access dimension folding might in certain cases increase the number of
928 // disjuncts in the memory access, which can possibly complicate the generated
929 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000930 if (!PollyPreciseFoldAccesses &&
931 isl_map_n_basic_map(NewAccessRelation.get()) >
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000932 isl_map_n_basic_map(AccessRelation.get())) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000933 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000934 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000935 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000936}
937
Tobias Grosserc80d6972016-09-02 06:33:33 +0000938/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000939static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000940 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000941 if (Size == 1)
942 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000943
944 // Only one factor needs to be divisible.
945 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
946 for (auto *FactorExpr : MulExpr->operands())
947 if (isDivisible(FactorExpr, Size, SE))
948 return true;
949 return false;
950 }
951
952 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000953 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000954 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
955 for (auto *OpExpr : NAryExpr->operands())
956 if (!isDivisible(OpExpr, Size, SE))
957 return false;
958 return true;
959 }
960
961 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
962 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
963 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
964 return MulSCEV == Expr;
965}
966
Michael Krusee2bccbb2015-09-18 19:59:43 +0000967void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000968 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000969
Johannes Doerfert85676e32016-04-23 14:32:34 +0000970 // Initialize the invalid domain which describes all iterations for which the
971 // access relation is not modeled correctly.
Tobias Grosser2332fa32017-08-06 15:36:48 +0000972 isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
Tobias Grosserb739cb42017-07-24 20:30:34 +0000973 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +0000974
Tobias Grosserb739cb42017-07-24 20:30:34 +0000975 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000976 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000977
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000978 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
979 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000980 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000981 return;
982 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000983
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000984 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000985 // We overapproximate non-affine accesses with a possible access to the
986 // whole array. For read accesses it does not make a difference, if an
987 // access must or may happen. However, for write accesses it is important to
988 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000989 if (AccessRelation.is_null())
990 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000991
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000992 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000993 return;
994 }
995
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000996 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
997 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000998
Michael Krusee2bccbb2015-09-18 19:59:43 +0000999 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +00001000 isl::pw_aff Affine = getPwAff(Subscripts[i]);
1001 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
1002 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001003 }
1004
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001005 Space = Statement->getDomainSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001006 AccessRelation = AccessRelation.set_tuple_id(
1007 isl::dim::in, Space.get_tuple_id(isl::dim::set));
1008 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001009
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001010 AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001011}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001012
Michael Krusecac948e2015-10-02 13:53:07 +00001013MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001014 AccessType AccType, Value *BaseAddress,
1015 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001016 ArrayRef<const SCEV *> Subscripts,
1017 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001018 MemoryKind Kind)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001019 : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(nullptr),
1020 BaseAddr(BaseAddress), ElementType(ElementType),
Tobias Grosser81331282017-05-03 07:57:35 +00001021 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1022 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001023 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001024 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001025 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001026 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001027
Tobias Grosser81331282017-05-03 07:57:35 +00001028 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001029 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001030}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001031
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001032MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001033 : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
1034 InvalidDomain(nullptr), AccessRelation(nullptr),
1035 NewAccessRelation(AccRel), FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +00001036 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001037 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1038 Sizes.push_back(nullptr);
1039 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1040 Sizes.push_back(SAI->getDimensionSize(i));
1041 ElementType = SAI->getElementType();
1042 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001043 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001044 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001045
Tobias Grosser81331282017-05-03 07:57:35 +00001046 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001047 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001048}
1049
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001050MemoryAccess::~MemoryAccess() = default;
1051
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001052void MemoryAccess::realignParams() {
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001053 isl::set Ctx = Statement->getParent()->getContext();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001054 InvalidDomain = InvalidDomain.gist_params(Ctx);
1055 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001056}
1057
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001058const std::string MemoryAccess::getReductionOperatorStr() const {
1059 return MemoryAccess::getReductionOperatorStr(getReductionType());
1060}
1061
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001062isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001063
Johannes Doerfertf6183392014-07-01 20:52:51 +00001064raw_ostream &polly::operator<<(raw_ostream &OS,
1065 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001066 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001067 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001068 else
1069 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001070 return OS;
1071}
1072
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001073void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001074
Tobias Grosser75805372011-04-29 06:27:02 +00001075void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001076 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001077 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001078 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001079 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001080 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001081 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001082 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001083 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001084 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001085 break;
1086 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001087
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001088 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001089
1090 if (FAD) {
1091 OS << "[Fortran array descriptor: " << FAD->getName();
1092 OS << "] ";
1093 };
1094
Tobias Grossera535dff2015-12-13 19:59:01 +00001095 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001096 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001097 if (hasNewAccessRelation())
1098 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001099}
1100
Michael Kruse5d518462017-07-21 15:54:07 +00001101#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001102LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001103#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001104
Tobias Grossercdf471b2017-07-24 16:36:34 +00001105isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001106 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001107 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001108 isl::set StmtDom = getStatement()->getDomain();
Tobias Grossercdf471b2017-07-24 16:36:34 +00001109 StmtDom = StmtDom.reset_tuple_id();
1110 isl::set NewInvalidDom = StmtDom.intersect(isl::manage(PWAC.second));
Tobias Grosserb739cb42017-07-24 20:30:34 +00001111 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Tobias Grossercdf471b2017-07-24 16:36:34 +00001112 return isl::manage(PWAC.first);
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001113}
1114
Tobias Grosser75805372011-04-29 06:27:02 +00001115// Create a map in the size of the provided set domain, that maps from the
1116// one element of the provided set domain to another element of the provided
1117// set domain.
1118// The mapping is limited to all points that are equal in all but the last
1119// dimension and for which the last dimension of the input is strict smaller
1120// than the last dimension of the output.
1121//
1122// getEqualAndLarger(set[i0, i1, ..., iX]):
1123//
1124// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1125// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1126//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001127static isl::map getEqualAndLarger(isl::space SetDomain) {
1128 isl::space Space = SetDomain.map_from_set();
1129 isl::map Map = isl::map::universe(Space);
1130 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001131
1132 // Set all but the last dimension to be equal for the input and output
1133 //
1134 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1135 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001136 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001137 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001138
1139 // Set the last dimension of the input to be strict smaller than the
1140 // last dimension of the output.
1141 //
1142 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001143 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001144 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001145}
1146
Tobias Grosserd7065e52017-07-24 20:50:22 +00001147isl::set MemoryAccess::getStride(isl::map Schedule) const {
1148 isl::map AccessRelation = getAccessRelation();
1149 isl::space Space = Schedule.get_space().range();
1150 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001151
Tobias Grosserd7065e52017-07-24 20:50:22 +00001152 Schedule = Schedule.reverse();
1153 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001154
Tobias Grosserd7065e52017-07-24 20:50:22 +00001155 NextScatt = NextScatt.apply_range(Schedule);
1156 NextScatt = NextScatt.apply_range(AccessRelation);
1157 NextScatt = NextScatt.apply_domain(Schedule);
1158 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001159
Tobias Grosserd7065e52017-07-24 20:50:22 +00001160 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001161 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001162}
1163
Tobias Grosserd7065e52017-07-24 20:50:22 +00001164bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1165 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001166 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001167
Sebastian Popa00a0292012-12-18 07:46:06 +00001168 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001169 StrideX = isl::set::universe(Stride.get_space());
1170 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1171 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1172 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1173 StrideWidth);
1174 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001175
Tobias Grosser28dd4862012-01-24 16:42:16 +00001176 return IsStrideX;
1177}
1178
Tobias Grosserd7065e52017-07-24 20:50:22 +00001179bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001180 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001181}
1182
Tobias Grosserd7065e52017-07-24 20:50:22 +00001183bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001184 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001185}
1186
Tobias Grosser6d588042017-08-02 19:27:16 +00001187void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1188 AccessRelation = NewAccess;
Tobias Grosserbedef002016-12-02 08:10:56 +00001189}
1190
Tobias Grosser7b45af12017-08-02 19:27:25 +00001191void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001192 assert(NewAccess);
1193
1194#ifndef NDEBUG
1195 // Check domain space compatibility.
Tobias Grosser7b45af12017-08-02 19:27:25 +00001196 isl::space NewSpace = NewAccess.get_space();
1197 isl::space NewDomainSpace = NewSpace.domain();
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001198 isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001199 assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
Michael Kruse772ce722016-09-01 19:16:58 +00001200
Michael Kruse706f79a2017-05-21 22:46:57 +00001201 // Reads must be executed unconditionally. Writes might be executed in a
1202 // subdomain only.
1203 if (isRead()) {
1204 // Check whether there is an access for every statement instance.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001205 isl::set StmtDomain = getStatement()->getDomain();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001206 StmtDomain =
1207 StmtDomain.intersect_params(getStatement()->getParent()->getContext());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001208 isl::set NewDomain = NewAccess.domain();
1209 assert(StmtDomain.is_subset(NewDomain) &&
Michael Kruse706f79a2017-05-21 22:46:57 +00001210 "Partial READ accesses not supported");
Michael Kruse706f79a2017-05-21 22:46:57 +00001211 }
Michael Kruse772ce722016-09-01 19:16:58 +00001212
Tobias Grosser7b45af12017-08-02 19:27:25 +00001213 isl::space NewAccessSpace = NewAccess.get_space();
1214 assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
Michael Kruse772ce722016-09-01 19:16:58 +00001215 "Must specify the array that is accessed");
Tobias Grosser7b45af12017-08-02 19:27:25 +00001216 isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1217 auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
Michael Kruse772ce722016-09-01 19:16:58 +00001218 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001219
1220 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1221 InvariantEquivClassTy *EqClass =
1222 getStatement()->getParent()->lookupInvariantEquivClass(
1223 SAI->getBasePtr());
1224 assert(EqClass &&
1225 "Access functions to indirect arrays must have an invariant and "
1226 "hoisted base pointer");
1227 }
1228
1229 // Check whether access dimensions correspond to number of dimensions of the
1230 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001231 auto Dims = SAI->getNumberOfDimensions();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001232 assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
Michael Kruse772ce722016-09-01 19:16:58 +00001233 "Access dims must match array dims");
Michael Kruse772ce722016-09-01 19:16:58 +00001234#endif
1235
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001236 NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001237 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001238}
Tobias Grosser75805372011-04-29 06:27:02 +00001239
Michael Kruse706f79a2017-05-21 22:46:57 +00001240bool MemoryAccess::isLatestPartialAccess() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001241 isl::set StmtDom = getStatement()->getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001242 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001243
1244 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1245}
1246
Tobias Grosser75805372011-04-29 06:27:02 +00001247//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001248
Tobias Grosser6ad16402017-08-06 17:45:28 +00001249isl::map ScopStmt::getSchedule() const {
Tobias Grosser1e09c132017-08-14 06:49:06 +00001250 isl::set Domain = getDomain();
1251 if (Domain.is_empty())
1252 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1253 auto Schedule = getParent()->getSchedule();
1254 if (!Schedule)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001255 return nullptr;
Tobias Grosser1e09c132017-08-14 06:49:06 +00001256 Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1257 if (Schedule.is_empty())
1258 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1259 isl::map M = M.from_union_map(Schedule);
1260 M = M.coalesce();
1261 M = M.gist_domain(Domain);
1262 M = M.coalesce();
1263 return M;
Tobias Grosser808cd692015-07-14 09:33:13 +00001264}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001265
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001266void ScopStmt::restrictDomain(isl::set NewDomain) {
1267 assert(NewDomain.is_subset(Domain) &&
Tobias Grosser37eb4222014-02-20 21:43:54 +00001268 "New domain is not a subset of old domain!");
Tobias Grosser37eb4222014-02-20 21:43:54 +00001269 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001270}
1271
Michael Kruse70af4f52017-08-07 18:40:29 +00001272void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
Michael Krusecac948e2015-10-02 13:53:07 +00001273 Instruction *AccessInst = Access->getAccessInstruction();
1274
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001275 if (Access->isArrayKind()) {
1276 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1277 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001278 } else if (Access->isValueKind() && Access->isWrite()) {
1279 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse436db622016-01-26 13:33:10 +00001280 assert(!ValueWrites.lookup(AccessVal));
1281
1282 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001283 } else if (Access->isValueKind() && Access->isRead()) {
1284 Value *AccessVal = Access->getAccessValue();
1285 assert(!ValueReads.lookup(AccessVal));
1286
1287 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001288 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001289 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001290 assert(!PHIWrites.lookup(PHI));
1291
1292 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001293 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1294 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1295 assert(!PHIReads.lookup(PHI));
1296
1297 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001298 }
1299
Michael Kruse70af4f52017-08-07 18:40:29 +00001300 if (Prepend) {
1301 MemAccs.insert(MemAccs.begin(), Access);
1302 return;
1303 }
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001304 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001305}
1306
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001307void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001308 for (MemoryAccess *MA : *this)
1309 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001310
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001311 isl::set Ctx = Parent.getContext();
Tobias Grosser2332fa32017-08-06 15:36:48 +00001312 InvalidDomain = InvalidDomain.gist_params(Ctx);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001313 Domain = Domain.gist_params(Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001314}
1315
Tobias Grosserc80d6972016-09-02 06:33:33 +00001316/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001317static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1318 void *User) {
1319 isl_set **BoundedParts = static_cast<isl_set **>(User);
1320 if (isl_basic_set_is_bounded(BSet))
1321 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1322 else
1323 isl_basic_set_free(BSet);
1324 return isl_stat_ok;
1325}
1326
Tobias Grosserc80d6972016-09-02 06:33:33 +00001327/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001328static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1329 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1330 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1331 isl_set_free(S);
1332 return BoundedParts;
1333}
1334
Tobias Grosserc80d6972016-09-02 06:33:33 +00001335/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001336///
1337/// @returns A separation of @p S into first an unbounded then a bounded subset,
1338/// both with regards to the dimension @p Dim.
1339static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1340partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001341 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001342 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001343
1344 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001345 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001346
1347 // Remove dimensions that are greater than Dim as they are not interesting.
1348 assert(NumDimsS >= Dim + 1);
1349 OnlyDimS =
1350 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1351
1352 // Create artificial parametric upper bounds for dimensions smaller than Dim
1353 // as we are not interested in them.
1354 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1355 for (unsigned u = 0; u < Dim; u++) {
1356 isl_constraint *C = isl_inequality_alloc(
1357 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1358 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1359 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1360 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1361 }
1362
1363 // Collect all bounded parts of OnlyDimS.
1364 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1365
1366 // Create the dimensions greater than Dim again.
1367 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1368 NumDimsS - Dim - 1);
1369
1370 // Remove the artificial upper bound parameters again.
1371 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1372
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001373 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001374 return std::make_pair(UnboundedParts, BoundedParts);
1375}
1376
Tobias Grosserc80d6972016-09-02 06:33:33 +00001377/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001378static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1379 __isl_take isl_set *To) {
1380 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1381 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1382 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1383 }
1384 return To;
1385}
1386
Tobias Grosserc80d6972016-09-02 06:33:33 +00001387/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001388static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001389 __isl_take isl_pw_aff *L,
1390 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001391 switch (Pred) {
1392 case ICmpInst::ICMP_EQ:
1393 return isl_pw_aff_eq_set(L, R);
1394 case ICmpInst::ICMP_NE:
1395 return isl_pw_aff_ne_set(L, R);
1396 case ICmpInst::ICMP_SLT:
1397 return isl_pw_aff_lt_set(L, R);
1398 case ICmpInst::ICMP_SLE:
1399 return isl_pw_aff_le_set(L, R);
1400 case ICmpInst::ICMP_SGT:
1401 return isl_pw_aff_gt_set(L, R);
1402 case ICmpInst::ICMP_SGE:
1403 return isl_pw_aff_ge_set(L, R);
1404 case ICmpInst::ICMP_ULT:
1405 return isl_pw_aff_lt_set(L, R);
1406 case ICmpInst::ICMP_UGT:
1407 return isl_pw_aff_gt_set(L, R);
1408 case ICmpInst::ICMP_ULE:
1409 return isl_pw_aff_le_set(L, R);
1410 case ICmpInst::ICMP_UGE:
1411 return isl_pw_aff_ge_set(L, R);
1412 default:
1413 llvm_unreachable("Non integer predicate not supported");
1414 }
1415}
1416
Tobias Grosserc80d6972016-09-02 06:33:33 +00001417/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001418///
1419/// Helper function that will make sure the dimensions of the result have the
1420/// same isl_id's as the @p Domain.
1421static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1422 __isl_take isl_pw_aff *L,
1423 __isl_take isl_pw_aff *R,
1424 __isl_keep isl_set *Domain) {
1425 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1426 return setDimensionIds(Domain, ConsequenceCondSet);
1427}
1428
Michael Kruse476f8552017-06-29 12:47:41 +00001429/// Compute the isl representation for the SCEV @p E in this BB.
1430///
1431/// @param S The Scop in which @p BB resides in.
1432/// @param BB The BB for which isl representation is to be
1433/// computed.
1434/// @param InvalidDomainMap A map of BB to their invalid domains.
1435/// @param E The SCEV that should be translated.
1436/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1437///
1438/// Note that this function will also adjust the invalid context accordingly.
1439
1440__isl_give isl_pw_aff *
1441getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001442 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1443 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001444 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001445 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001446 return PWAC.first;
1447}
1448
Tobias Grosserc80d6972016-09-02 06:33:33 +00001449/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001450///
1451/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001452/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1453/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001454static bool
1455buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1456 __isl_keep isl_set *Domain,
1457 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1458 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001459 Value *Condition = getConditionFromTerminator(SI);
1460 assert(Condition && "No condition for switch");
1461
1462 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001463 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001464 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001465
1466 unsigned NumSuccessors = SI->getNumSuccessors();
1467 ConditionSets.resize(NumSuccessors);
1468 for (auto &Case : SI->cases()) {
1469 unsigned Idx = Case.getSuccessorIndex();
1470 ConstantInt *CaseValue = Case.getCaseValue();
1471
Michael Kruse476f8552017-06-29 12:47:41 +00001472 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001473 isl_set *CaseConditionSet =
1474 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1475 ConditionSets[Idx] = isl_set_coalesce(
1476 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1477 }
1478
1479 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1480 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1481 for (unsigned u = 2; u < NumSuccessors; u++)
1482 ConditionSetUnion =
1483 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1484 ConditionSets[0] = setDimensionIds(
1485 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1486
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001487 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001488
1489 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001490}
1491
Michael Kruse08655852017-07-20 12:37:02 +00001492/// Build condition sets for unsigned ICmpInst(s).
1493/// Special handling is required for unsigned operands to ensure that if
1494/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1495/// it should wrap around.
1496///
1497/// @param IsStrictUpperBound holds information on the predicate relation
1498/// between TestVal and UpperBound, i.e,
1499/// TestVal < UpperBound OR TestVal <= UpperBound
1500static __isl_give isl_set *
1501buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1502 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1503 const SCEV *SCEV_UpperBound,
1504 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1505 bool IsStrictUpperBound) {
Michael Kruse08655852017-07-20 12:37:02 +00001506 // Do not take NonNeg assumption on TestVal
1507 // as it might have MSB (Sign bit) set.
1508 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1509 // Take NonNeg assumption on UpperBound.
1510 isl_pw_aff *UpperBound =
1511 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1512
1513 // 0 <= TestVal
1514 isl_set *First =
1515 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1516 isl_pw_aff_get_domain_space(TestVal))),
1517 isl_pw_aff_copy(TestVal));
1518
1519 isl_set *Second;
1520 if (IsStrictUpperBound)
1521 // TestVal < UpperBound
1522 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1523 else
1524 // TestVal <= UpperBound
1525 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1526
1527 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1528 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1529 return ConsequenceCondSet;
1530}
1531
Tobias Grosserc80d6972016-09-02 06:33:33 +00001532/// Build the conditions sets for the branch condition @p Condition in
1533/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001534///
1535/// This will fill @p ConditionSets with the conditions under which control
1536/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001537/// have as many elements as @p TI has successors. If @p TI is nullptr the
1538/// context under which @p Condition is true/false will be returned as the
1539/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001540static bool
1541buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1542 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1543 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1544 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001545 isl_set *ConsequenceCondSet = nullptr;
1546 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1547 if (CCond->isZero())
1548 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1549 else
1550 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1551 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1552 auto Opcode = BinOp->getOpcode();
1553 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1554
Michael Kruse476f8552017-06-29 12:47:41 +00001555 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1556 InvalidDomainMap, ConditionSets) &&
1557 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1558 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001559 if (!Valid) {
1560 while (!ConditionSets.empty())
1561 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001562 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001563 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001564
1565 isl_set_free(ConditionSets.pop_back_val());
1566 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1567 isl_set_free(ConditionSets.pop_back_val());
1568 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1569
1570 if (Opcode == Instruction::And)
1571 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1572 else
1573 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1574 } else {
1575 auto *ICond = dyn_cast<ICmpInst>(Condition);
1576 assert(ICond &&
1577 "Condition of exiting branch was neither constant nor ICmp!");
1578
1579 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001580 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001581 // For unsigned comparisons we assumed the signed bit of neither operand
1582 // to be set. The comparison is equal to a signed comparison under this
1583 // assumption.
1584 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001585 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1586 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1587
1588 switch (ICond->getPredicate()) {
1589 case ICmpInst::ICMP_ULT:
1590 ConsequenceCondSet =
1591 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1592 RightOperand, InvalidDomainMap, true);
1593 break;
1594 case ICmpInst::ICMP_ULE:
1595 ConsequenceCondSet =
1596 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1597 RightOperand, InvalidDomainMap, false);
1598 break;
1599 case ICmpInst::ICMP_UGT:
1600 ConsequenceCondSet =
1601 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1602 LeftOperand, InvalidDomainMap, true);
1603 break;
1604 case ICmpInst::ICMP_UGE:
1605 ConsequenceCondSet =
1606 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1607 LeftOperand, InvalidDomainMap, false);
1608 break;
1609 default:
1610 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1611 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1612 ConsequenceCondSet =
1613 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1614 break;
1615 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001616 }
1617
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001618 // If no terminator was given we are only looking for parameter constraints
1619 // under which @p Condition is true/false.
1620 if (!TI)
1621 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001622 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001623 ConsequenceCondSet = isl_set_coalesce(
1624 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001625
Johannes Doerfertb2885792016-04-26 09:20:41 +00001626 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001627 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001628 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001629
Michael Krusef7a4a942016-05-02 12:25:36 +00001630 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001631 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1632 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001633 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001634 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001635 }
1636
Michael Krusef7a4a942016-05-02 12:25:36 +00001637 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001638 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1639 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001640 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001641 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001642 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001643 }
1644
1645 ConditionSets.push_back(ConsequenceCondSet);
1646 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001647
1648 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001649}
1650
Tobias Grosserc80d6972016-09-02 06:33:33 +00001651/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001652///
1653/// This will fill @p ConditionSets with the conditions under which control
1654/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1655/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001656static bool
1657buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1658 __isl_keep isl_set *Domain,
1659 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1660 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001661 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001662 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1663 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001664
1665 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1666
1667 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001668 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001669 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001670 }
1671
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001672 Value *Condition = getConditionFromTerminator(TI);
1673 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001674
Michael Kruse476f8552017-06-29 12:47:41 +00001675 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1676 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001677}
1678
Tobias Grosserbd15d132017-08-31 03:15:56 +00001679ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop,
1680 std::vector<Instruction *> EntryBlockInstructions)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001681 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), R(&R),
Tobias Grosserbd15d132017-08-31 03:15:56 +00001682 Build(nullptr), SurroundingLoop(SurroundingLoop),
1683 Instructions(EntryBlockInstructions) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001684 BaseName = getIslCompatibleName(
1685 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001686}
1687
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001688ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
Michael Kruse59125512017-08-30 10:11:06 +00001689 std::vector<Instruction *> Instructions, int Count)
Johannes Doerferta3519512016-04-23 13:02:23 +00001690 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001691 Build(nullptr), SurroundingLoop(SurroundingLoop),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001692 Instructions(Instructions) {
Michael Kruse59125512017-08-30 10:11:06 +00001693 std::string S = "";
1694 if (Count != 0)
1695 S += std::to_string(Count);
1696 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), S,
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001697 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001698}
1699
Tobias Grosser85048ef2017-08-06 17:24:59 +00001700ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1701 isl::set NewDomain)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001702 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain),
1703 Build(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001704 BaseName = getIslCompatibleName("CopyStmt_", "",
1705 std::to_string(parent.getCopyStmtsNum()));
Tobias Grosser85048ef2017-08-06 17:24:59 +00001706 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1707 Domain = Domain.set_tuple_id(Id);
1708 TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1709 auto *Access =
1710 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001711 parent.addAccessFunction(Access);
1712 addAccess(Access);
Tobias Grosser85048ef2017-08-06 17:24:59 +00001713 SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1714 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001715 parent.addAccessFunction(Access);
1716 addAccess(Access);
1717}
1718
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001719ScopStmt::~ScopStmt() = default;
1720
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001721std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001722
Tobias Grosser54839312015-04-21 11:37:25 +00001723std::string ScopStmt::getScheduleStr() const {
Tobias Grosser6ad16402017-08-06 17:45:28 +00001724 auto *S = getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001725 if (!S)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001726 return {};
Tobias Grosser808cd692015-07-14 09:33:13 +00001727 auto Str = stringFromIslObj(S);
1728 isl_map_free(S);
1729 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001730}
1731
Tobias Grosser2332fa32017-08-06 15:36:48 +00001732void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
Johannes Doerfert7c013572016-04-12 09:57:34 +00001733
Michael Kruse375cb5f2016-02-24 22:08:24 +00001734BasicBlock *ScopStmt::getEntryBlock() const {
1735 if (isBlockStmt())
1736 return getBasicBlock();
1737 return getRegion()->getEntry();
1738}
1739
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001740unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001741
Tobias Grosser75805372011-04-29 06:27:02 +00001742const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1743
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001744Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001745 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001746}
1747
Tobias Grosser74394f02013-01-14 22:40:23 +00001748isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001749
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001750isl::set ScopStmt::getDomain() const { return Domain; }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001751
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001752isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001753
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001754isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001755
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001756void ScopStmt::printInstructions(raw_ostream &OS) const {
1757 OS << "Instructions {\n";
1758
1759 for (Instruction *Inst : Instructions)
1760 OS.indent(16) << *Inst << "\n";
1761
Michael Krusee52ebd12017-07-22 16:44:39 +00001762 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001763}
1764
Michael Krusecd4c9772017-07-21 15:35:53 +00001765void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001766 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001767 OS.indent(12) << "Domain :=\n";
1768
1769 if (Domain) {
1770 OS.indent(16) << getDomainStr() << ";\n";
1771 } else
1772 OS.indent(16) << "n/a\n";
1773
Tobias Grosser54839312015-04-21 11:37:25 +00001774 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001775
1776 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001777 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001778 } else
1779 OS.indent(16) << "n/a\n";
1780
Tobias Grosser083d3d32014-06-28 08:59:45 +00001781 for (MemoryAccess *Access : MemAccs)
1782 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001783
Tobias Grosserbd15d132017-08-31 03:15:56 +00001784 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001785 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001786}
1787
Michael Kruse5d518462017-07-21 15:54:07 +00001788#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001789LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001790#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001791
Michael Krusee60eca72017-05-11 22:56:12 +00001792void ScopStmt::removeAccessData(MemoryAccess *MA) {
1793 if (MA->isRead() && MA->isOriginalValueKind()) {
1794 bool Found = ValueReads.erase(MA->getAccessValue());
1795 (void)Found;
1796 assert(Found && "Expected access data not found");
1797 }
1798 if (MA->isWrite() && MA->isOriginalValueKind()) {
1799 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1800 (void)Found;
1801 assert(Found && "Expected access data not found");
1802 }
1803 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1804 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1805 (void)Found;
1806 assert(Found && "Expected access data not found");
1807 }
Michael Kruse3562f272017-07-20 16:47:57 +00001808 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
1809 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1810 (void)Found;
1811 assert(Found && "Expected access data not found");
1812 }
Michael Krusee60eca72017-05-11 22:56:12 +00001813}
1814
Michael Kruse10071822016-05-23 14:45:58 +00001815void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001816 // Remove the memory accesses from this statement together with all scalar
1817 // accesses that were caused by it. MemoryKind::Value READs have no access
1818 // instruction, hence would not be removed by this function. However, it is
1819 // only used for invariant LoadInst accesses, its arguments are always affine,
1820 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1821 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001822 auto Predicate = [&](MemoryAccess *Acc) {
1823 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1824 };
Michael Krusee60eca72017-05-11 22:56:12 +00001825 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00001826 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00001827 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00001828 Parent.removeAccessData(MA);
1829 }
Michael Krusee60eca72017-05-11 22:56:12 +00001830 }
Michael Kruse10071822016-05-23 14:45:58 +00001831 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1832 MemAccs.end());
1833 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001834}
1835
Michael Kruse0446d812017-03-10 16:05:24 +00001836void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1837 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1838 assert(MAIt != MemAccs.end());
1839 MemAccs.erase(MAIt);
1840
Michael Krusee60eca72017-05-11 22:56:12 +00001841 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00001842 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00001843
Michael Kruse0446d812017-03-10 16:05:24 +00001844 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1845 if (It != InstructionToAccess.end()) {
1846 It->second.remove(MA);
1847 if (It->second.empty())
1848 InstructionToAccess.erase(MA->getAccessInstruction());
1849 }
1850}
1851
Michael Kruse07e8c362017-07-24 12:43:27 +00001852MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
1853 MemoryAccess *Access = lookupInputAccessOf(V);
1854 if (Access)
1855 return Access;
1856
1857 ScopArrayInfo *SAI =
1858 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
1859 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
1860 true, {}, {}, V, MemoryKind::Value);
1861 Parent.addAccessFunction(Access);
1862 Access->buildAccessRelation(SAI);
1863 addAccess(Access);
1864 Parent.addAccessData(Access);
1865 return Access;
1866}
1867
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001868raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
1869 S.print(OS, PollyPrintInstructions);
1870 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00001871}
1872
Tobias Grosser75805372011-04-29 06:27:02 +00001873//===----------------------------------------------------------------------===//
1874/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001875
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001876void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001877 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1878 isl_set_free(Context);
1879 Context = NewContext;
1880}
1881
Eli Friedman5e589ea2017-06-20 22:53:02 +00001882namespace {
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001883
Tobias Grosserc80d6972016-09-02 06:33:33 +00001884/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001885struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001886 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001887 const ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001888
1889public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001890 SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
1891 ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001892 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001893
1894 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001895 const ValueToValueMap &VMap) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001896 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1897 return SSPR.visit(E);
1898 }
1899
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001900 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1901 auto *Start = visit(E->getStart());
1902 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1903 visit(E->getStepRecurrence(SE)),
1904 E->getLoop(), SCEV::FlagAnyWrap);
1905 return SE.getAddExpr(Start, AddRec);
1906 }
1907
1908 const SCEV *visitUnknown(const SCEVUnknown *E) {
1909 if (auto *NewValue = VMap.lookup(E->getValue()))
1910 return SE.getUnknown(NewValue);
1911 return E;
1912 }
1913};
1914
Eli Friedman5e589ea2017-06-20 22:53:02 +00001915/// Check whether we should remap a SCEV expression.
1916struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001917 const ValueToValueMap &VMap;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001918 bool FoundInside = false;
Tobias Grosserb5563c62017-08-03 13:51:15 +00001919 const Scop *S;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001920
1921public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001922 SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
1923 const Scop *S)
Eli Friedman5e589ea2017-06-20 22:53:02 +00001924 : SCEVTraversal(*this), VMap(VMap), S(S) {}
1925
1926 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001927 const ValueToValueMap &VMap, const Scop *S) {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001928 SCEVFindInsideScop SFIS(VMap, SE, S);
1929 SFIS.visitAll(E);
1930 return SFIS.FoundInside;
1931 }
1932
1933 bool follow(const SCEV *E) {
1934 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
1935 FoundInside |= S->getRegion().contains(AddRec->getLoop());
1936 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
1937 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
1938 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
1939 }
1940 return !FoundInside;
1941 }
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001942
Eli Friedman5e589ea2017-06-20 22:53:02 +00001943 bool isDone() { return FoundInside; }
1944};
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001945
1946} // end anonymous namespace
Eli Friedman5e589ea2017-06-20 22:53:02 +00001947
Tobias Grosserb5563c62017-08-03 13:51:15 +00001948const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001949 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
1950 // doesn't like addition between an AddRec and an expression that
1951 // doesn't have a dominance relationship with it.)
1952 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
1953 return E;
1954
1955 // Rewrite SCEV.
1956 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001957}
1958
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001959// This table of function names is used to translate parameter names in more
1960// human-readable names. This makes it easier to interpret Polly analysis
1961// results.
1962StringMap<std::string> KnownNames = {
1963 {"_Z13get_global_idj", "global_id"},
1964 {"_Z12get_local_idj", "local_id"},
1965 {"_Z15get_global_sizej", "global_size"},
1966 {"_Z14get_local_sizej", "local_size"},
1967 {"_Z12get_work_dimv", "work_dim"},
1968 {"_Z17get_global_offsetj", "global_offset"},
1969 {"_Z12get_group_idj", "group_id"},
1970 {"_Z14get_num_groupsj", "num_groups"},
1971};
1972
1973static std::string getCallParamName(CallInst *Call) {
1974 std::string Result;
1975 raw_string_ostream OS(Result);
1976 std::string Name = Call->getCalledFunction()->getName();
1977
1978 auto Iterator = KnownNames.find(Name);
1979 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00001980 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001981 OS << Name;
1982 for (auto &Operand : Call->arg_operands()) {
1983 ConstantInt *Op = cast<ConstantInt>(&Operand);
1984 OS << "_" << Op->getValue();
1985 }
1986 OS.flush();
1987 return Result;
1988}
1989
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001990void Scop::createParameterId(const SCEV *Parameter) {
1991 assert(Parameters.count(Parameter));
1992 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001993
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001994 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001995
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001996 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1997 Value *Val = ValueParameter->getValue();
1998 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001999
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002000 if (Call && isConstCall(Call)) {
2001 ParameterName = getCallParamName(Call);
2002 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002003 // If this parameter references a specific Value and this value has a name
2004 // we use this name as it is likely to be unique and more useful than just
2005 // a number.
2006 if (Val->hasName())
2007 ParameterName = Val->getName();
2008 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2009 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2010 if (LoadOrigin->hasName()) {
2011 ParameterName += "_loaded_from_";
2012 ParameterName +=
2013 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2014 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002015 }
2016 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002017
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002018 ParameterName = getIslCompatibleName("", ParameterName, "");
2019 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002020
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002021 isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002022 const_cast<void *>((const void *)Parameter));
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002023 ParameterIds[Parameter] = Id;
2024}
2025
2026void Scop::addParams(const ParameterSetTy &NewParameters) {
2027 for (const SCEV *Parameter : NewParameters) {
2028 // Normalize the SCEV to get the representing element for an invariant load.
2029 Parameter = extractConstantFactor(Parameter, *SE).second;
2030 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2031
2032 if (Parameters.insert(Parameter))
2033 createParameterId(Parameter);
2034 }
2035}
2036
Tobias Grosser9a635702017-08-06 19:31:27 +00002037isl::id Scop::getIdForParam(const SCEV *Parameter) const {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002038 // Normalize the SCEV to get the representing element for an invariant load.
2039 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002040 return ParameterIds.lookup(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00002041}
Tobias Grosser75805372011-04-29 06:27:02 +00002042
Tobias Grosser232fdad2017-08-06 20:19:26 +00002043isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002044 isl_set *DomainContext = isl_union_set_params(getDomains().release());
Tobias Grosser232fdad2017-08-06 20:19:26 +00002045 return isl::manage(isl_set_intersect_params(C.release(), DomainContext));
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002046}
2047
Johannes Doerferte0b08072016-05-23 12:43:44 +00002048bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2049 return DT.dominates(BB, getEntry());
2050}
2051
Michael Kruse476f8552017-06-29 12:47:41 +00002052void Scop::addUserAssumptions(
2053 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002054 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002055 for (auto &Assumption : AC.assumptions()) {
2056 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2057 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002058 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002059
Michael Kruse89b1f942017-03-17 13:56:53 +00002060 bool InScop = contains(CI);
2061 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2062 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002063
Michael Kruse89b1f942017-03-17 13:56:53 +00002064 auto *L = LI.getLoopFor(CI->getParent());
2065 auto *Val = CI->getArgOperand(0);
2066 ParameterSetTy DetectedParams;
2067 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002068 ORE.emit(
2069 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2070 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002071 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002072 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002073
2074 // Collect all newly introduced parameters.
2075 ParameterSetTy NewParams;
2076 for (auto *Param : DetectedParams) {
2077 Param = extractConstantFactor(Param, *SE).second;
2078 Param = getRepresentingInvariantLoadSCEV(Param);
2079 if (Parameters.count(Param))
2080 continue;
2081 NewParams.insert(Param);
2082 }
2083
2084 SmallVector<isl_set *, 2> ConditionSets;
2085 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
Michael Kruse1df1aac2017-07-26 13:25:28 +00002086 BasicBlock *BB = InScop ? CI->getParent() : getRegion().getEntry();
2087 auto *Dom = InScop ? DomainMap[BB].copy() : isl_set_copy(Context);
2088 assert(Dom && "Cannot propagate a nullptr.");
2089 bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2090 InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002091 isl_set_free(Dom);
2092
2093 if (!Valid)
2094 continue;
2095
2096 isl_set *AssumptionCtx = nullptr;
2097 if (InScop) {
2098 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2099 isl_set_free(ConditionSets[0]);
2100 } else {
2101 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2102 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2103 }
2104
2105 // Project out newly introduced parameters as they are not otherwise useful.
2106 if (!NewParams.empty()) {
2107 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2108 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2109 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2110 isl_id_free(Id);
2111
2112 if (!NewParams.count(Param))
2113 continue;
2114
2115 AssumptionCtx =
2116 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2117 }
2118 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002119 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2120 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002121 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002122 }
2123}
2124
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002125void Scop::addUserContext() {
2126 if (UserContextStr.empty())
2127 return;
2128
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002129 isl_set *UserContext =
2130 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002131 isl_space *Space = getParamSpace().release();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002132 if (isl_space_dim(Space, isl_dim_param) !=
2133 isl_set_dim(UserContext, isl_dim_param)) {
2134 auto SpaceStr = isl_space_to_str(Space);
2135 errs() << "Error: the context provided in -polly-context has not the same "
2136 << "number of dimensions than the computed context. Due to this "
2137 << "mismatch, the -polly-context option is ignored. Please provide "
2138 << "the context in the parameter space: " << SpaceStr << ".\n";
2139 free(SpaceStr);
2140 isl_set_free(UserContext);
2141 isl_space_free(Space);
2142 return;
2143 }
2144
2145 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002146 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2147 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002148
2149 if (strcmp(NameContext, NameUserContext) != 0) {
2150 auto SpaceStr = isl_space_to_str(Space);
2151 errs() << "Error: the name of dimension " << i
2152 << " provided in -polly-context "
2153 << "is '" << NameUserContext << "', but the name in the computed "
2154 << "context is '" << NameContext
2155 << "'. Due to this name mismatch, "
2156 << "the -polly-context option is ignored. Please provide "
2157 << "the context in the parameter space: " << SpaceStr << ".\n";
2158 free(SpaceStr);
2159 isl_set_free(UserContext);
2160 isl_space_free(Space);
2161 return;
2162 }
2163
2164 UserContext =
2165 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2166 isl_space_get_dim_id(Space, isl_dim_param, i));
2167 }
2168
2169 Context = isl_set_intersect(Context, UserContext);
2170 isl_space_free(Space);
2171}
2172
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002173void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002174 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002175
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002176 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002177 for (LoadInst *LInst : RIL) {
2178 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2179
Johannes Doerfert96e54712016-02-07 17:30:13 +00002180 Type *Ty = LInst->getType();
2181 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002182 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002183 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002184 continue;
2185 }
2186
2187 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002188 InvariantEquivClasses.emplace_back(
2189 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002190 }
2191}
2192
Tobias Grosser6be480c2011-11-08 15:41:13 +00002193void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002194 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002195 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002196 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002197 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002198}
2199
Tobias Grosser18daaca2012-05-22 10:47:27 +00002200void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002201 unsigned PDim = 0;
2202 for (auto *Parameter : Parameters) {
2203 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002204 Context =
2205 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2206 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002207 }
2208}
2209
Tobias Grosserb5563c62017-08-03 13:51:15 +00002210static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
2211 std::vector<isl::id> OutermostSizeIds;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002212 for (auto Array : Arrays) {
2213 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2214 // for its outermost dimension. Fortran arrays will have this since the
2215 // outermost dimension size can be picked up from their runtime description.
2216 // TODO: actually need to check if it has a FAD, but for now this works.
2217 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002218 isl::pw_aff PwAff = Array->getDimensionSizePw(0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002219 if (!PwAff)
2220 continue;
2221
Tobias Grosserb5563c62017-08-03 13:51:15 +00002222 isl::id Id =
2223 isl::manage(isl_pw_aff_get_dim_id(PwAff.get(), isl_dim_param, 0));
2224 assert(!Id.is_null() &&
2225 "Invalid Id for PwAff expression in Fortran array");
2226 Id.dump();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002227 OutermostSizeIds.push_back(Id);
2228 }
2229 }
Tobias Grosserb5563c62017-08-03 13:51:15 +00002230 return OutermostSizeIds;
2231}
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002232
Tobias Grosserb5563c62017-08-03 13:51:15 +00002233// The FORTRAN array size parameters are known to be non-negative.
2234static isl_set *boundFortranArrayParams(__isl_give isl_set *Context,
2235 Scop::array_range Arrays) {
2236 std::vector<isl::id> OutermostSizeIds;
2237 OutermostSizeIds = getFortranArrayIds(Arrays);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002238
Tobias Grosserb5563c62017-08-03 13:51:15 +00002239 for (isl::id Id : OutermostSizeIds) {
2240 int dim = isl_set_find_dim_by_id(Context, isl_dim_param, Id.get());
2241 Context = isl_set_lower_bound_si(Context, isl_dim_param, dim, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002242 }
2243
2244 return Context;
2245}
2246
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002247void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002248 if (PollyIgnoreParamBounds)
2249 return;
2250
Tobias Grosser6be480c2011-11-08 15:41:13 +00002251 // Add all parameters into a common model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002252 isl::space Space = getFullParamSpace();
Tobias Grosser6be480c2011-11-08 15:41:13 +00002253
2254 // Align the parameters of all data structures to the model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002255 Context = isl_set_align_params(Context, Space.copy());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002256
Tobias Grosserb5563c62017-08-03 13:51:15 +00002257 // Bound the size of the fortran array dimensions.
2258 Context = boundFortranArrayParams(Context, arrays());
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002259
Johannes Doerferta60ad842016-05-10 12:18:22 +00002260 // As all parameters are known add bounds to them.
2261 addParameterBounds();
2262
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002263 for (ScopStmt &Stmt : *this)
2264 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002265 // Simplify the schedule according to the context too.
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00002266 Schedule = isl_schedule_gist_domain_params(Schedule, getContext().release());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002267}
2268
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002269static __isl_give isl_set *
2270simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2271 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002272 // If we have modeled all blocks in the SCoP that have side effects we can
2273 // simplify the context with the constraints that are needed for anything to
2274 // be executed at all. However, if we have error blocks in the SCoP we already
2275 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002276 // domains, thus we cannot use the remaining domain to simplify the
2277 // assumptions.
2278 if (!S.hasErrorBlock()) {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002279 isl_set *DomainParameters = isl_union_set_params(S.getDomains().release());
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002280 AssumptionContext =
2281 isl_set_gist_params(AssumptionContext, DomainParameters);
2282 }
2283
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002284 AssumptionContext =
2285 isl_set_gist_params(AssumptionContext, S.getContext().release());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002286 return AssumptionContext;
2287}
2288
2289void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002290 // The parameter constraints of the iteration domains give us a set of
2291 // constraints that need to hold for all cases where at least a single
2292 // statement iteration is executed in the whole scop. We now simplify the
2293 // assumed context under the assumption that such constraints hold and at
2294 // least a single statement iteration is executed. For cases where no
2295 // statement instances are executed, the assumptions we have taken about
2296 // the executed code do not matter and can be changed.
2297 //
2298 // WARNING: This only holds if the assumptions we have taken do not reduce
2299 // the set of statement instances that are executed. Otherwise we
2300 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002301 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002302 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002303 // performed. In such a case, modifying the run-time conditions and
2304 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002305 // to not be executed.
2306 //
2307 // Example:
2308 //
2309 // When delinearizing the following code:
2310 //
2311 // for (long i = 0; i < 100; i++)
2312 // for (long j = 0; j < m; j++)
2313 // A[i+p][j] = 1.0;
2314 //
2315 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002316 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002317 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002318 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002319 InvalidContext =
2320 isl_set_align_params(InvalidContext, getParamSpace().release());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002321}
2322
Tobias Grosserc80d6972016-09-02 06:33:33 +00002323/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002324static isl::stat
2325buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2326 isl::pw_multi_aff MinPMA, MaxPMA;
2327 isl::pw_aff LastDimAff;
2328 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002329 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002330 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002331
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002332 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002333
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002334 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2335 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002336
Johannes Doerfert9143d672014-09-27 11:02:39 +00002337 // Restrict the number of parameters involved in the access as the lexmin/
2338 // lexmax computation will take too long if this number is high.
2339 //
2340 // Experiments with a simple test case using an i7 4800MQ:
2341 //
2342 // #Parameters involved | Time (in sec)
2343 // 6 | 0.01
2344 // 7 | 0.04
2345 // 8 | 0.12
2346 // 9 | 0.40
2347 // 10 | 1.54
2348 // 11 | 6.78
2349 // 12 | 30.38
2350 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002351 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002352 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002353 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2354 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002355 InvolvedParams++;
2356
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002357 if (InvolvedParams > RunTimeChecksMaxParameters)
2358 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002359 }
2360
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002361 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2362 return isl::stat::error;
2363
Tobias Grosser57a1d362017-06-23 08:05:27 +00002364 MinPMA = Set.lexmin_pw_multi_aff();
2365 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002366
Tobias Grosser57a1d362017-06-23 08:05:27 +00002367 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002368 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002369
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002370 MinPMA = MinPMA.coalesce();
2371 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002372
Johannes Doerfertb164c792014-09-18 11:17:17 +00002373 // Adjust the last dimension of the maximal access by one as we want to
2374 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2375 // we test during code generation might now point after the end of the
2376 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002377 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2378 Pos = MaxPMA.dim(isl::dim::out) - 1;
2379 LastDimAff = MaxPMA.get_pw_aff(Pos);
2380 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2381 OneAff = OneAff.add_constant_si(1);
2382 LastDimAff = LastDimAff.add(OneAff);
2383 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002384
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002385 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002386
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002387 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002388}
2389
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002390static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00002391 isl_set *Domain = MA->getStatement()->getDomain().release();
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002392 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2393 return isl_set_reset_tuple_id(Domain);
2394}
2395
Tobias Grosserc80d6972016-09-02 06:33:33 +00002396/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002397static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002398 Scop::MinMaxVectorTy &MinMaxAccesses) {
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002399 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002400
Tobias Grosser31df6f32017-08-06 21:42:25 +00002401 isl::union_set Domains = S.getDomains();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002402 isl::union_map Accesses = isl::union_map::empty(S.getParamSpace());
Tobias Grossere9522232017-01-16 15:49:04 +00002403
2404 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser1515f6b2017-07-23 04:08:38 +00002405 Accesses = Accesses.add_map(give(MA->getAccessRelation().release()));
Tobias Grossere9522232017-01-16 15:49:04 +00002406
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002407 Accesses = Accesses.intersect_domain(Domains);
2408 isl::union_set Locations = Accesses.range();
2409 Locations = Locations.coalesce();
2410 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002411
2412 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2413 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2414 };
2415 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002416}
2417
Tobias Grosserc80d6972016-09-02 06:33:33 +00002418/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002419///
2420///{
2421
Tobias Grosserc80d6972016-09-02 06:33:33 +00002422/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002423static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2424 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2425 : RN->getNodeAs<BasicBlock>();
2426}
2427
Tobias Grosserc80d6972016-09-02 06:33:33 +00002428/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002429static inline BasicBlock *
2430getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002431 if (RN->isSubRegion()) {
2432 assert(idx == 0);
2433 return RN->getNodeAs<Region>()->getExit();
2434 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002435 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002436}
2437
Tobias Grosserc80d6972016-09-02 06:33:33 +00002438/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002439static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002440 if (!RN->isSubRegion()) {
2441 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2442 Loop *L = LI.getLoopFor(BB);
2443
2444 // Unreachable statements are not considered to belong to a LLVM loop, as
2445 // they are not part of an actual loop in the control flow graph.
2446 // Nevertheless, we handle certain unreachable statements that are common
2447 // when modeling run-time bounds checks as being part of the loop to be
2448 // able to model them and to later eliminate the run-time bounds checks.
2449 //
2450 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002451 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002452 // basic blocks belong to the loop the predecessor belongs to. This
2453 // allows us to model the following code.
2454 //
2455 // for (i = 0; i < N; i++) {
2456 // if (i > 1024)
2457 // abort(); <- this abort might be translated to an
2458 // unreachable
2459 //
2460 // A[i] = ...
2461 // }
2462 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2463 L = LI.getLoopFor(BB->getPrevNode());
2464 return L;
2465 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002466
2467 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2468 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2469 while (L && NonAffineSubRegion->contains(L))
2470 L = L->getParentLoop();
2471 return L;
2472}
2473
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002474/// Get the number of blocks in @p L.
2475///
2476/// The number of blocks in a loop are the number of basic blocks actually
2477/// belonging to the loop, as well as all single basic blocks that the loop
2478/// exits to and which terminate in an unreachable instruction. We do not
2479/// allow such basic blocks in the exit of a scop, hence they belong to the
2480/// scop and represent run-time conditions which we want to model and
2481/// subsequently speculate away.
2482///
2483/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002484unsigned getNumBlocksInLoop(Loop *L) {
2485 unsigned NumBlocks = L->getNumBlocks();
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002486 SmallVector<BasicBlock *, 4> ExitBlocks;
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002487 L->getExitBlocks(ExitBlocks);
2488
2489 for (auto ExitBlock : ExitBlocks) {
2490 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2491 NumBlocks++;
2492 }
2493 return NumBlocks;
2494}
2495
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002496static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2497 if (!RN->isSubRegion())
2498 return 1;
2499
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002500 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002501 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002502}
2503
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002504static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2505 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002506 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002507 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002508 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002509 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002510 return true;
2511 return false;
2512}
2513
Johannes Doerfert96425c22015-08-30 21:13:53 +00002514///}
2515
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002516static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2517 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002518 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002519 isl_id *DimId =
2520 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2521 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2522}
2523
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002524isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002525 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002526}
2527
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002528isl::set Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002529 auto DIt = DomainMap.find(BB);
2530 if (DIt != DomainMap.end())
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002531 return DIt->getSecond();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002532
2533 auto &RI = *R.getRegionInfo();
2534 auto *BBR = RI.getRegionFor(BB);
2535 while (BBR->getEntry() == BB)
2536 BBR = BBR->getParent();
2537 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002538}
2539
Tobias Grosser13acbb92017-07-15 09:01:31 +00002540bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2541 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002542 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002543 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002544 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2545 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002546 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002547
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002548 while (LD-- >= 0) {
2549 S = addDomainDimId(S, LD + 1, L);
2550 L = L->getParentLoop();
2551 }
2552
Tobias Grosser13acbb92017-07-15 09:01:31 +00002553 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002554 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002555
Johannes Doerfert432658d2016-01-26 11:01:41 +00002556 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002557 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002558
Michael Kruse476f8552017-06-29 12:47:41 +00002559 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002560 return false;
2561
Michael Kruse476f8552017-06-29 12:47:41 +00002562 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002563 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002564
2565 // Error blocks and blocks dominated by them have been assumed to never be
2566 // executed. Representing them in the Scop does not add any value. In fact,
2567 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002568 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002569 // will cause problems when building up a ScopStmt for them.
2570 // Furthermore, basic blocks dominated by error blocks may reference
2571 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002572 // can themselves not be constructed properly. To this end we will replace
2573 // the domains of error blocks and those only reachable via error blocks
2574 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002575 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002576 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002577 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002578 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002579
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002580 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002581}
2582
Tobias Grosserc80d6972016-09-02 06:33:33 +00002583/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002584/// to be compatible to domains constructed for loop @p NewL.
2585///
2586/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2587/// edge from @p OldL to @p NewL.
2588static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2589 __isl_take isl_set *Dom,
2590 Loop *OldL, Loop *NewL) {
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002591 // If the loops are the same there is nothing to do.
2592 if (NewL == OldL)
2593 return Dom;
2594
2595 int OldDepth = S.getRelativeLoopDepth(OldL);
2596 int NewDepth = S.getRelativeLoopDepth(NewL);
2597 // If both loops are non-affine loops there is nothing to do.
2598 if (OldDepth == -1 && NewDepth == -1)
2599 return Dom;
2600
2601 // Distinguish three cases:
2602 // 1) The depth is the same but the loops are not.
2603 // => One loop was left one was entered.
2604 // 2) The depth increased from OldL to NewL.
2605 // => One loop was entered, none was left.
2606 // 3) The depth decreased from OldL to NewL.
2607 // => Loops were left were difference of the depths defines how many.
2608 if (OldDepth == NewDepth) {
2609 assert(OldL->getParentLoop() == NewL->getParentLoop());
2610 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2611 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2612 Dom = addDomainDimId(Dom, NewDepth, NewL);
2613 } else if (OldDepth < NewDepth) {
2614 assert(OldDepth + 1 == NewDepth);
2615 auto &R = S.getRegion();
2616 (void)R;
2617 assert(NewL->getParentLoop() == OldL ||
2618 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2619 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2620 Dom = addDomainDimId(Dom, NewDepth, NewL);
2621 } else {
2622 assert(OldDepth > NewDepth);
2623 int Diff = OldDepth - NewDepth;
2624 int NumDim = isl_set_n_dim(Dom);
2625 assert(NumDim >= Diff);
2626 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2627 }
2628
2629 return Dom;
2630}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002631
Michael Kruse476f8552017-06-29 12:47:41 +00002632bool Scop::propagateInvalidStmtDomains(
2633 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002634 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002635 ReversePostOrderTraversal<Region *> RTraversal(R);
2636 for (auto *RN : RTraversal) {
2637
2638 // Recurse for affine subregions but go on for basic blocks and non-affine
2639 // subregions.
2640 if (RN->isSubRegion()) {
2641 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002642 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002643 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002644 continue;
2645 }
2646 }
2647
2648 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2649 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002650 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002651 assert(Domain && "Cannot propagate a nullptr");
2652
Tobias Grosser325204a32017-07-15 12:41:32 +00002653 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002654
Tobias Grosser325204a32017-07-15 12:41:32 +00002655 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002656
Johannes Doerferta3519512016-04-23 13:02:23 +00002657 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002658 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002659 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002660 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002661 isl::set DomPar = Domain.params();
2662 recordAssumption(ERRORBLOCK, DomPar.release(),
2663 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002664 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002665 }
2666
Tobias Grosser325204a32017-07-15 12:41:32 +00002667 if (InvalidDomain.is_empty()) {
2668 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002669 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002670 }
2671
Johannes Doerferta3519512016-04-23 13:02:23 +00002672 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002673 auto *TI = BB->getTerminator();
2674 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2675 for (unsigned u = 0; u < NumSuccs; u++) {
2676 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002677
2678 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002679 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002680 continue;
2681
Johannes Doerferte4459a22016-04-25 13:34:50 +00002682 // Skip backedges.
2683 if (DT.dominates(SuccBB, BB))
2684 continue;
2685
Michael Kruse476f8552017-06-29 12:47:41 +00002686 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2687
Johannes Doerferta3519512016-04-23 13:02:23 +00002688 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002689 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002690
Tobias Grosser13acbb92017-07-15 09:01:31 +00002691 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002692 SuccInvalidDomain =
2693 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2694 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2695 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002696
Tobias Grosser13acbb92017-07-15 09:01:31 +00002697 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002698
Michael Krusebc150122016-05-02 12:25:18 +00002699 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002700 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002701 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002702 continue;
2703
Tobias Grosserf44f0052017-07-09 15:47:17 +00002704 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002705 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002706 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002707 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002708
Tobias Grosser325204a32017-07-15 12:41:32 +00002709 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002710 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002711
2712 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002713}
2714
Johannes Doerfert642594a2016-04-04 07:57:39 +00002715void Scop::propagateDomainConstraintsToRegionExit(
2716 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002717 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002718 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002719 // Check if the block @p BB is the entry of a region. If so we propagate it's
2720 // domain to the exit block of the region. Otherwise we are done.
2721 auto *RI = R.getRegionInfo();
2722 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2723 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002724 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002725 return;
2726
Johannes Doerfert642594a2016-04-04 07:57:39 +00002727 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002728 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002729 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002730 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002731 SmallVector<BasicBlock *, 4> LatchBBs;
2732 BBLoop->getLoopLatches(LatchBBs);
2733 for (auto *LatchBB : LatchBBs)
2734 if (BB != LatchBB && BBReg->contains(LatchBB))
2735 return;
2736 L = L->getParentLoop();
2737 }
2738
Tobias Grosser325204a32017-07-15 12:41:32 +00002739 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002740 assert(Domain && "Cannot propagate a nullptr");
2741
Michael Kruse476f8552017-06-29 12:47:41 +00002742 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002743
2744 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2745 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002746 isl::set AdjustedDomain = isl::manage(
2747 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2748 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002749
2750 // If the exit domain is not yet created we set it otherwise we "add" the
2751 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002752 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002753
Johannes Doerferta3519512016-04-23 13:02:23 +00002754 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002755 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002756
Johannes Doerfert642594a2016-04-04 07:57:39 +00002757 FinishedExitBlocks.insert(ExitBB);
2758}
2759
Michael Kruse476f8552017-06-29 12:47:41 +00002760bool Scop::buildDomainsWithBranchConstraints(
2761 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002762 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002763 // To create the domain for each block in R we iterate over all blocks and
2764 // subregions in R and propagate the conditions under which the current region
2765 // element is executed. To this end we iterate in reverse post order over R as
2766 // it ensures that we first visit all predecessors of a region node (either a
2767 // basic block or a subregion) before we visit the region node itself.
2768 // Initially, only the domain for the SCoP region entry block is set and from
2769 // there we propagate the current domain to all successors, however we add the
2770 // condition that the successor is actually executed next.
2771 // As we are only interested in non-loop carried constraints here we can
2772 // simply skip loop back edges.
2773
Johannes Doerfert642594a2016-04-04 07:57:39 +00002774 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002775 ReversePostOrderTraversal<Region *> RTraversal(R);
2776 for (auto *RN : RTraversal) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002777 // Recurse for affine subregions but go on for basic blocks and non-affine
2778 // subregions.
2779 if (RN->isSubRegion()) {
2780 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002781 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002782 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2783 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002784 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002785 continue;
2786 }
2787 }
2788
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002789 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002790 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002791
Johannes Doerfert96425c22015-08-30 21:13:53 +00002792 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002793 TerminatorInst *TI = BB->getTerminator();
2794
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002795 if (isa<UnreachableInst>(TI))
2796 continue;
2797
Tobias Grosser325204a32017-07-15 12:41:32 +00002798 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002799 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002800 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002801 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002802
Johannes Doerfert642594a2016-04-04 07:57:39 +00002803 auto *BBLoop = getRegionNodeLoop(RN, LI);
2804 // Propagate the domain from BB directly to blocks that have a superset
2805 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00002806 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2807 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002808
2809 // If all successors of BB have been set a domain through the propagation
2810 // above we do not need to build condition sets but can just skip this
2811 // block. However, it is important to note that this is a local property
2812 // with regards to the region @p R. To this end FinishedExitBlocks is a
2813 // local variable.
2814 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2815 return FinishedExitBlocks.count(SuccBB);
2816 };
2817 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2818 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002819
2820 // Build the condition sets for the successor nodes of the current region
2821 // node. If it is a non-affine subregion we will always execute the single
2822 // exit node, hence the single entry node domain is the condition set. For
2823 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002824 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002825 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00002826 ConditionSets.push_back(Domain.copy());
2827 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00002828 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002829 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002830
2831 // Now iterate over the successors and set their initial domain based on
2832 // their condition set. We skip back edges here and have to be careful when
2833 // we leave a loop not to keep constraints over a dimension that doesn't
2834 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002835 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002836 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002837 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002838 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002839
Johannes Doerfert535de032016-04-19 14:49:05 +00002840 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00002841 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00002842 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00002843
Johannes Doerfert642594a2016-04-04 07:57:39 +00002844 // If we propagate the domain of some block to "SuccBB" we do not have to
2845 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002846 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002847 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002848
Johannes Doerfert96425c22015-08-30 21:13:53 +00002849 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00002850 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00002851 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002852
Michael Kruse476f8552017-06-29 12:47:41 +00002853 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2854
Tobias Grosser325204a32017-07-15 12:41:32 +00002855 CondSet = isl::manage(
2856 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002857
2858 // Set the domain for the successor or merge it with an existing domain in
2859 // case there are multiple paths (without loop back edges) to the
2860 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00002861 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002862
Johannes Doerferta3519512016-04-23 13:02:23 +00002863 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002864 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00002865 } else {
2866 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002867 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002868 SuccDomain = CondSet;
2869 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002870
Tobias Grosser325204a32017-07-15 12:41:32 +00002871 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00002872
Michael Krusebc150122016-05-02 12:25:18 +00002873 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002874 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00002875 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002876 continue;
2877
2878 invalidate(COMPLEXITY, DebugLoc());
2879 while (++u < ConditionSets.size())
2880 isl_set_free(ConditionSets[u]);
2881 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002882 }
2883 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002884
2885 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002886}
2887
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002888isl::set Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
2889 DominatorTree &DT,
2890 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002891 // If @p BB is the ScopEntry we are done
2892 if (R.getEntry() == BB)
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002893 return isl::set::universe(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002894
Johannes Doerfert642594a2016-04-04 07:57:39 +00002895 // The region info of this function.
2896 auto &RI = *R.getRegionInfo();
2897
Michael Kruse476f8552017-06-29 12:47:41 +00002898 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002899
2900 // A domain to collect all predecessor domains, thus all conditions under
2901 // which the block is executed. To this end we start with the empty domain.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002902 isl::set PredDom = isl::set::empty(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002903
2904 // Set of regions of which the entry block domain has been propagated to BB.
2905 // all predecessors inside any of the regions can be skipped.
2906 SmallSet<Region *, 8> PropagatedRegions;
2907
2908 for (auto *PredBB : predecessors(BB)) {
2909 // Skip backedges.
2910 if (DT.dominates(BB, PredBB))
2911 continue;
2912
2913 // If the predecessor is in a region we used for propagation we can skip it.
2914 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2915 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2916 PredBBInRegion)) {
2917 continue;
2918 }
2919
2920 // Check if there is a valid region we can use for propagation, thus look
2921 // for a region that contains the predecessor and has @p BB as exit block.
2922 auto *PredR = RI.getRegionFor(PredBB);
2923 while (PredR->getExit() != BB && !PredR->contains(BB))
2924 PredR->getParent();
2925
2926 // If a valid region for propagation was found use the entry of that region
2927 // for propagation, otherwise the PredBB directly.
2928 if (PredR->getExit() == BB) {
2929 PredBB = PredR->getEntry();
2930 PropagatedRegions.insert(PredR);
2931 }
2932
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002933 auto *PredBBDom = getDomainConditions(PredBB).release();
Michael Kruse476f8552017-06-29 12:47:41 +00002934 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
2935
Johannes Doerfert642594a2016-04-04 07:57:39 +00002936 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2937
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002938 PredDom = PredDom.unite(isl::manage(PredBBDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002939 }
2940
2941 return PredDom;
2942}
2943
Michael Kruse476f8552017-06-29 12:47:41 +00002944bool Scop::propagateDomainConstraints(
2945 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002946 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002947 // Iterate over the region R and propagate the domain constrains from the
2948 // predecessors to the current node. In contrast to the
2949 // buildDomainsWithBranchConstraints function, this one will pull the domain
2950 // information from the predecessors instead of pushing it to the successors.
2951 // Additionally, we assume the domains to be already present in the domain
2952 // map here. However, we iterate again in reverse post order so we know all
2953 // predecessors have been visited before a block or non-affine subregion is
2954 // visited.
2955
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002956 ReversePostOrderTraversal<Region *> RTraversal(R);
2957 for (auto *RN : RTraversal) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002958 // Recurse for affine subregions but go on for basic blocks and non-affine
2959 // subregions.
2960 if (RN->isSubRegion()) {
2961 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002962 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002963 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002964 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002965 continue;
2966 }
2967 }
2968
2969 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002970 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002971 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002972
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002973 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002974 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser325204a32017-07-15 12:41:32 +00002975 Domain = Domain.intersect(PredDom).coalesce();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002976 Domain = Domain.align_params(getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002977
Johannes Doerfert642594a2016-04-04 07:57:39 +00002978 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002979 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00002980 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002981 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002982 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002983
2984 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002985}
2986
Tobias Grosserc80d6972016-09-02 06:33:33 +00002987/// Create a map to map from a given iteration to a subsequent iteration.
2988///
2989/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2990/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002991/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002992///
2993/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002994static __isl_give isl_map *
2995createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2996 auto *MapSpace = isl_space_map_from_set(SetSpace);
2997 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00002998 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002999 if (u != Dim)
3000 NextIterationMap =
3001 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3002 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3003 C = isl_constraint_set_constant_si(C, 1);
3004 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3005 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3006 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3007 return NextIterationMap;
3008}
3009
Michael Kruse476f8552017-06-29 12:47:41 +00003010bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003011 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003012 int LoopDepth = getRelativeLoopDepth(L);
3013 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003014
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003015 BasicBlock *HeaderBB = L->getHeader();
3016 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003017 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003018
Tobias Grosser325204a32017-07-15 12:41:32 +00003019 isl::map NextIterationMap = isl::manage(
3020 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003021
Tobias Grosser325204a32017-07-15 12:41:32 +00003022 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003023
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003024 SmallVector<BasicBlock *, 4> LatchBlocks;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003025 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003026
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003027 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003028 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003029 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003030 if (!LatchBBDom)
3031 continue;
3032
Tobias Grosser325204a32017-07-15 12:41:32 +00003033 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003034
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003035 TerminatorInst *TI = LatchBB->getTerminator();
3036 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003037 assert(BI && "Only branch instructions allowed in loop latches");
3038
3039 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003040 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003041 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003042 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003043 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003044 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3045 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003046 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003047
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003048 // Free the non back edge condition set as we do not need it.
3049 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003050
Tobias Grosser325204a32017-07-15 12:41:32 +00003051 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003052 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003053
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003054 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3055 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003056 BackedgeCondition = BackedgeCondition.project_out(
3057 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3058 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003059 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003060
Tobias Grosser325204a32017-07-15 12:41:32 +00003061 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003062 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003063 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003064
Tobias Grosser325204a32017-07-15 12:41:32 +00003065 isl::set UnionBackedgeConditionComplement =
3066 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003067 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003068 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3069 0);
3070 UnionBackedgeConditionComplement =
3071 UnionBackedgeConditionComplement.apply(ForwardMap);
3072 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3073 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003074
Tobias Grosser325204a32017-07-15 12:41:32 +00003075 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3076 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003077
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003078 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3079 // the bounded assumptions to the context as they are already implied by the
3080 // <nsw> tag.
3081 if (Affinator.hasNSWAddRecForLoop(L)) {
3082 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003083 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003084 }
3085
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003086 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003087 recordAssumption(INFINITELOOP, UnboundedCtx,
3088 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003089 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003090}
3091
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003092MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003093 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003094
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003095 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003096 if (!PointerBaseInst)
3097 return nullptr;
3098
3099 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3100 if (!BasePtrStmt)
3101 return nullptr;
3102
3103 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3104}
3105
3106bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003107 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003108 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003109 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003110 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003111
Tobias Grosserbe372d52017-02-09 10:11:58 +00003112 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003113 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003114 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003115 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003116
3117 return false;
3118}
3119
Johannes Doerfert5210da52016-06-02 11:06:54 +00003120bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003121 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003122 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003123
Johannes Doerfertcd195322016-11-17 21:41:08 +00003124 if (buildAliasGroups(AA)) {
3125 // Aliasing assumptions do not go through addAssumption but we still want to
3126 // collect statistics so we do it here explicitly.
3127 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003128 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003129 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003130 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003131
3132 // If a problem occurs while building the alias groups we need to delete
3133 // this SCoP and pretend it wasn't valid in the first place. To this end
3134 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003135 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003136
3137 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3138 << " could not be created as the number of parameters involved "
3139 "is too high. The SCoP will be "
3140 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3141 "the maximal number of parameters but be advised that the "
3142 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003143 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003144}
3145
Tobias Grosser889830b2017-02-09 23:12:22 +00003146std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003147Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003148 AliasSetTracker AST(AA);
3149
3150 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003151 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003152 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003153
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003154 isl_set *StmtDomain = Stmt.getDomain().release();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003155 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3156 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003157
3158 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003159 if (StmtDomainEmpty)
3160 continue;
3161
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003162 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003163 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003164 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003165 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003166 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003167 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003168 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003169 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003170 else
3171 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003172 AST.add(Acc);
3173 }
3174 }
3175
Tobias Grosser9edcf072017-01-16 14:07:57 +00003176 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003177 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003178 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003179 continue;
3180 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003181 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003182 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003183 if (AG.size() < 2)
3184 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003185 AliasGroups.push_back(std::move(AG));
3186 }
3187
Tobias Grosser9edcf072017-01-16 14:07:57 +00003188 return std::make_tuple(AliasGroups, HasWriteAccess);
3189}
3190
Tobias Grossere39f9122017-01-16 14:08:00 +00003191void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003192 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3193 AliasGroupTy NewAG;
3194 AliasGroupTy &AG = AliasGroups[u];
3195 AliasGroupTy::iterator AGI = AG.begin();
3196 isl_set *AGDomain = getAccessDomain(*AGI);
3197 while (AGI != AG.end()) {
3198 MemoryAccess *MA = *AGI;
3199 isl_set *MADomain = getAccessDomain(MA);
3200 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3201 NewAG.push_back(MA);
3202 AGI = AG.erase(AGI);
3203 isl_set_free(MADomain);
3204 } else {
3205 AGDomain = isl_set_union(AGDomain, MADomain);
3206 AGI++;
3207 }
3208 }
3209 if (NewAG.size() > 1)
3210 AliasGroups.push_back(std::move(NewAG));
3211 isl_set_free(AGDomain);
3212 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003213}
3214
3215bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3216 // To create sound alias checks we perform the following steps:
3217 // o) We partition each group into read only and non read only accesses.
3218 // o) For each group with more than one base pointer we then compute minimal
3219 // and maximal accesses to each array of a group in read only and non
3220 // read only partitions separately.
3221 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003222 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003223
3224 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3225
3226 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003227
Johannes Doerfert13771732014-10-01 12:40:46 +00003228 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003229 if (!hasFeasibleRuntimeContext())
3230 return false;
3231
Tobias Grosser57a1d362017-06-23 08:05:27 +00003232 {
3233 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3234 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3235 if (!Valid)
3236 return false;
3237 }
3238 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3239 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003240 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003241 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003242 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003243
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003244 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003245}
3246
Tobias Grosser77f32572017-01-16 15:49:07 +00003247bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003248 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003249 AliasGroupTy ReadOnlyAccesses;
3250 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003251 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003252 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003253
Tobias Grosser77f32572017-01-16 15:49:07 +00003254 if (AliasGroup.size() < 2)
3255 return true;
3256
3257 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003258 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3259 Access->getAccessInstruction())
3260 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003261 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3262 if (HasWriteAccess.count(Array)) {
3263 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003264 ReadWriteAccesses.push_back(Access);
3265 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003266 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003267 ReadOnlyAccesses.push_back(Access);
3268 }
3269 }
3270
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003271 // If there are no read-only pointers, and less than two read-write pointers,
3272 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003273 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003274 return true;
3275
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003276 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003277 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003278 return true;
3279
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003280 // For non-affine accesses, no alias check can be generated as we cannot
3281 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003282 for (MemoryAccess *MA : AliasGroup) {
3283 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003284 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3285 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003286 return false;
3287 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003288 }
3289
3290 // Ensure that for all memory accesses for which we generate alias checks,
3291 // their base pointers are available.
3292 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003293 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3294 addRequiredInvariantLoad(
3295 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3296 }
3297
3298 MinMaxAliasGroups.emplace_back();
3299 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3300 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3301 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3302
3303 bool Valid;
3304
3305 Valid =
3306 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3307
3308 if (!Valid)
3309 return false;
3310
3311 // Bail out if the number of values we need to compare is too large.
3312 // This is important as the number of comparisons grows quadratically with
3313 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003314 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003315 RunTimeChecksMaxArraysPerGroup)
3316 return false;
3317
3318 Valid =
3319 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3320
3321 if (!Valid)
3322 return false;
3323
3324 return true;
3325}
3326
Tobias Grosserc80d6972016-09-02 06:33:33 +00003327/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003328static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003329 // Start with the smallest loop containing the entry and expand that
3330 // loop until it contains all blocks in the region. If there is a loop
3331 // containing all blocks in the region check if it is itself contained
3332 // and if so take the parent loop as it will be the smallest containing
3333 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003334 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003335 while (L) {
3336 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003337 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003338 AllContained &= L->contains(BB);
3339 if (AllContained)
3340 break;
3341 L = L->getParentLoop();
3342 }
3343
Johannes Doerfertef744432016-05-23 12:42:38 +00003344 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003345}
3346
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003347int Scop::NextScopID = 0;
3348
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003349std::string Scop::CurrentFunc;
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003350
3351int Scop::getNextID(std::string ParentFunc) {
3352 if (ParentFunc != CurrentFunc) {
3353 CurrentFunc = ParentFunc;
3354 NextScopID = 0;
3355 }
3356 return NextScopID++;
3357}
3358
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003359Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003360 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003361 : SE(&ScalarEvolution), R(R), name(R.getNameStr()),
3362 HasSingleExitEdge(R.getExitingBlock()), DC(DC), ORE(ORE),
3363 IslCtx(isl_ctx_alloc(), isl_ctx_free), Affinator(this, LI),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003364 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003365 if (IslOnErrorAbort)
3366 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003367 buildContext();
3368}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003369
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003370Scop::~Scop() {
3371 isl_set_free(Context);
3372 isl_set_free(AssumedContext);
3373 isl_set_free(InvalidContext);
3374 isl_schedule_free(Schedule);
3375
3376 ParameterIds.clear();
3377
3378 for (auto &AS : RecordedAssumptions)
3379 isl_set_free(AS.Set);
3380
3381 // Free the alias groups
3382 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
3383 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
3384 isl_pw_multi_aff_free(MMA.first);
3385 isl_pw_multi_aff_free(MMA.second);
3386 }
3387 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
3388 isl_pw_multi_aff_free(MMA.first);
3389 isl_pw_multi_aff_free(MMA.second);
3390 }
3391 }
3392
3393 for (const auto &IAClass : InvariantEquivClasses)
3394 isl_set_free(IAClass.ExecutionContext);
3395
3396 // Explicitly release all Scop objects and the underlying isl objects before
3397 // we release the isl context.
3398 Stmts.clear();
3399 ScopArrayInfoSet.clear();
3400 ScopArrayInfoMap.clear();
3401 ScopArrayNameMap.clear();
3402 AccessFunctions.clear();
3403}
3404
Tobias Grosserbedef002016-12-02 08:10:56 +00003405void Scop::foldSizeConstantsToRight() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003406 isl_union_set *Accessed = isl_union_map_range(getAccesses().release());
Tobias Grosserbedef002016-12-02 08:10:56 +00003407
3408 for (auto Array : arrays()) {
3409 if (Array->getNumberOfDimensions() <= 1)
3410 continue;
3411
Tobias Grosser77eef902017-07-21 23:07:56 +00003412 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003413
3414 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3415
3416 if (!isl_union_set_contains(Accessed, Space)) {
3417 isl_space_free(Space);
3418 continue;
3419 }
3420
3421 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3422
3423 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003424 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003425
3426 std::vector<int> Int;
3427
3428 int Dims = isl_set_dim(Elements, isl_dim_set);
3429 for (int i = 0; i < Dims; i++) {
3430 isl_set *DimOnly =
3431 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3432 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3433 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3434
3435 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3436
3437 if (i == Dims - 1) {
3438 Int.push_back(1);
3439 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3440 isl_basic_set_free(DimHull);
3441 continue;
3442 }
3443
3444 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3445 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3446 isl_val *Val = isl_aff_get_denominator_val(Diff);
3447 isl_aff_free(Diff);
3448
3449 int ValInt = 1;
3450
3451 if (isl_val_is_int(Val))
3452 ValInt = isl_val_get_num_si(Val);
3453 isl_val_free(Val);
3454
3455 Int.push_back(ValInt);
3456
3457 isl_constraint *C = isl_constraint_alloc_equality(
3458 isl_local_space_from_space(isl_map_get_space(Transform)));
3459 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3460 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3461 Transform = isl_map_add_constraint(Transform, C);
3462 isl_basic_set_free(DimHull);
3463 continue;
3464 }
3465
3466 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3467 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3468
3469 int ValInt = 1;
3470 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3471 ValInt = 0;
3472 }
3473
3474 Int.push_back(ValInt);
3475 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3476 isl_basic_set_free(DimHull);
3477 isl_basic_set_free(ZeroSet);
3478 }
3479
3480 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3481
3482 if (!isl_set_is_subset(Elements, MappedElements)) {
3483 isl_set_free(Elements);
3484 isl_set_free(MappedElements);
3485 isl_map_free(Transform);
3486 continue;
3487 }
3488
3489 isl_set_free(MappedElements);
3490
3491 bool CanFold = true;
3492
3493 if (Int[0] <= 1)
3494 CanFold = false;
3495
3496 unsigned NumDims = Array->getNumberOfDimensions();
3497 for (unsigned i = 1; i < NumDims - 1; i++)
3498 if (Int[0] != Int[i] && Int[i])
3499 CanFold = false;
3500
3501 if (!CanFold) {
3502 isl_set_free(Elements);
3503 isl_map_free(Transform);
3504 continue;
3505 }
3506
Tobias Grosserbedef002016-12-02 08:10:56 +00003507 for (auto &Access : AccessFunctions)
3508 if (Access->getScopArrayInfo() == Array)
Tobias Grosser6d588042017-08-02 19:27:16 +00003509 Access->setAccessRelation(Access->getAccessRelation().apply_range(
3510 isl::manage(isl_map_copy(Transform))));
Tobias Grosserbedef002016-12-02 08:10:56 +00003511
3512 isl_map_free(Transform);
3513
3514 std::vector<const SCEV *> Sizes;
3515 for (unsigned i = 0; i < NumDims; i++) {
3516 auto Size = Array->getDimensionSize(i);
3517
3518 if (i == NumDims - 1)
3519 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3520 Sizes.push_back(Size);
3521 }
3522
3523 Array->updateSizes(Sizes, false /* CheckConsistency */);
3524
3525 isl_set_free(Elements);
3526 }
3527 isl_union_set_free(Accessed);
Tobias Grosserbedef002016-12-02 08:10:56 +00003528}
3529
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003530void Scop::markFortranArrays() {
3531 for (ScopStmt &Stmt : Stmts) {
3532 for (MemoryAccess *MemAcc : Stmt) {
3533 Value *FAD = MemAcc->getFortranArrayDescriptor();
3534 if (!FAD)
3535 continue;
3536
3537 // TODO: const_cast-ing to edit
3538 ScopArrayInfo *SAI =
3539 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3540 assert(SAI && "memory access into a Fortran array does not "
3541 "have an associated ScopArrayInfo");
3542 SAI->applyAndSetFAD(FAD);
3543 }
3544 }
3545}
3546
Tobias Grosser491b7992016-12-02 05:21:22 +00003547void Scop::finalizeAccesses() {
3548 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003549 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003550 foldAccessRelations();
3551 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003552 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003553}
3554
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003555void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003556 // Check all array accesses for each base pointer and find a (virtual) element
3557 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003558 for (ScopStmt &Stmt : *this)
3559 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003560 if (!Access->isArrayKind())
3561 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003562 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003563 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3564
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003565 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003566 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003567 unsigned DivisibleSize = Array->getElemSizeInBytes();
3568 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003569 while (!isDivisible(Subscript, DivisibleSize, *SE))
3570 DivisibleSize /= 2;
3571 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003572 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003573 }
3574
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003575 for (auto &Stmt : *this)
3576 for (auto &Access : Stmt)
3577 Access->updateDimensionality();
3578}
3579
Tobias Grosser491b7992016-12-02 05:21:22 +00003580void Scop::foldAccessRelations() {
3581 for (auto &Stmt : *this)
3582 for (auto &Access : Stmt)
3583 Access->foldAccessRelation();
3584}
3585
3586void Scop::assumeNoOutOfBounds() {
3587 for (auto &Stmt : *this)
3588 for (auto &Access : Stmt)
3589 Access->assumeNoOutOfBound();
3590}
3591
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003592void Scop::removeFromStmtMap(ScopStmt &Stmt) {
Tobias Grosserbd15d132017-08-31 03:15:56 +00003593 for (Instruction *Inst : Stmt.getInstructions())
3594 InstStmtMap.erase(Inst);
3595
3596 if (Stmt.isRegionStmt()) {
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003597 for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003598 StmtMap.erase(BB);
Tobias Grosserbd15d132017-08-31 03:15:56 +00003599 // Skip entry basic block, as its instructions are already deleted as
3600 // part of the statement's instruction list.
3601 if (BB == Stmt.getEntryBlock())
3602 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003603 for (Instruction &Inst : *BB)
3604 InstStmtMap.erase(&Inst);
3605 }
Tobias Grosserbd15d132017-08-31 03:15:56 +00003606 } else {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003607 StmtMap.erase(Stmt.getBasicBlock());
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003608 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003609}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003610
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003611void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3612 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3613 if (!ShouldDelete(*StmtIt)) {
3614 StmtIt++;
3615 continue;
3616 }
3617
3618 removeFromStmtMap(*StmtIt);
3619 StmtIt = Stmts.erase(StmtIt);
3620 }
3621}
3622
3623void Scop::removeStmtNotInDomainMap() {
3624 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003625 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003626 };
3627 removeStmts(ShouldDelete);
3628}
3629
3630void Scop::simplifySCoP(bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003631 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003632 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003633
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003634 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003635 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003636 bool OnlyRead = true;
3637 for (MemoryAccess *MA : Stmt) {
3638 if (MA->isRead())
3639 continue;
3640
3641 OnlyRead = false;
3642 break;
3643 }
3644
3645 RemoveStmt = OnlyRead;
3646 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003647 return RemoveStmt;
3648 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003649
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003650 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003651}
3652
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003653InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003654 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3655 if (!LInst)
3656 return nullptr;
3657
3658 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3659 LInst = cast<LoadInst>(Rep);
3660
Johannes Doerfert96e54712016-02-07 17:30:13 +00003661 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003662 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003663 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003664 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003665 continue;
3666
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003667 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003668 for (auto *MA : MAs)
3669 if (MA->getAccessInstruction() == Val)
3670 return &IAClass;
3671 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003672
3673 return nullptr;
3674}
3675
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003676bool isAParameter(llvm::Value *maybeParam, const Function &F) {
3677 for (const llvm::Argument &Arg : F.args())
3678 if (&Arg == maybeParam)
3679 return true;
3680
3681 return false;
Michael Kruse594386e2017-08-23 12:34:37 +00003682}
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003683
Tobias Grosser305d3162017-08-07 00:10:11 +00003684bool Scop::canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3685 bool MAInvalidCtxIsEmpty,
3686 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003687 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3688 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003689 if (PollyAllowDereferenceOfAllFunctionParams &&
3690 isAParameter(LInst->getPointerOperand(), getFunction()))
3691 return true;
3692
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003693 // TODO: We can provide more information for better but more expensive
3694 // results.
3695 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3696 LInst->getAlignment(), DL))
3697 return false;
3698
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003699 // If the location might be overwritten we do not hoist it unconditionally.
3700 //
Siddharth Bhat83fe6b52017-08-08 12:26:32 +00003701 // TODO: This is probably too conservative.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003702 if (!NonHoistableCtxIsEmpty)
3703 return false;
3704
Michael Krusea6d48f52017-06-08 12:06:15 +00003705 // If a dereferenceable load is in a statement that is modeled precisely we
3706 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003707 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003708 return true;
3709
3710 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003711 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003712 // statement domain.
3713 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3714 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3715 return false;
3716 return true;
3717}
3718
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003719void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003720 if (InvMAs.empty())
3721 return;
3722
Tobias Grosser2332fa32017-08-06 15:36:48 +00003723 isl::set StmtInvalidCtx = Stmt.getInvalidContext();
3724 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003725
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003726 // Get the context under which the statement is executed but remove the error
3727 // context under which this statement is reached.
Tobias Grossere69b2722017-08-06 23:50:25 +00003728 isl::set DomainCtx = Stmt.getDomain().params();
3729 DomainCtx = DomainCtx.subtract(StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003730
Tobias Grossere69b2722017-08-06 23:50:25 +00003731 if (isl_set_n_basic_set(DomainCtx.get()) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003732 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003733 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003734 return;
3735 }
3736
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003737 // Project out all parameters that relate to loads in the statement. Otherwise
3738 // we could have cyclic dependences on the constraints under which the
3739 // hoisted loads are executed and we could not determine an order in which to
3740 // pre-load them. This happens because not only lower bounds are part of the
3741 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003742 for (auto &InvMA : InvMAs) {
3743 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003744 Instruction *AccInst = MA->getAccessInstruction();
3745 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003746 SetVector<Value *> Values;
3747 for (const SCEV *Parameter : Parameters) {
3748 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003749 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003750 if (!Values.count(AccInst))
3751 continue;
3752
Tobias Grossere69b2722017-08-06 23:50:25 +00003753 if (isl::id ParamId = getIdForParam(Parameter)) {
3754 int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003755 if (Dim >= 0)
Tobias Grossere69b2722017-08-06 23:50:25 +00003756 DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003757 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003758 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003759 }
3760 }
3761
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003762 for (auto &InvMA : InvMAs) {
3763 auto *MA = InvMA.MA;
Tobias Grossere69b2722017-08-06 23:50:25 +00003764 isl::set NHCtx = InvMA.NonHoistableCtx;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003765
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003766 // Check for another invariant access that accesses the same location as
3767 // MA and if found consolidate them. Otherwise create a new equivalence
3768 // class at the end of InvariantEquivClasses.
3769 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003770 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003771 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3772
Tobias Grossere69b2722017-08-06 23:50:25 +00003773 isl::set MAInvalidCtx = MA->getInvalidContext();
3774 bool NonHoistableCtxIsEmpty = NHCtx.is_empty();
3775 bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty();
Johannes Doerfert85676e32016-04-23 14:32:34 +00003776
Tobias Grossere69b2722017-08-06 23:50:25 +00003777 isl::set MACtx;
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003778 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003779 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3780 NonHoistableCtxIsEmpty)) {
Tobias Grossere69b2722017-08-06 23:50:25 +00003781 MACtx = isl::set::universe(DomainCtx.get_space());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003782 } else {
Tobias Grossere69b2722017-08-06 23:50:25 +00003783 MACtx = DomainCtx;
3784 MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx));
3785 MACtx = MACtx.gist_params(getContext());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003786 }
3787
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003788 bool Consolidated = false;
3789 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003790 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003791 continue;
3792
Johannes Doerfertdf880232016-03-03 12:26:58 +00003793 // If the pointer and the type is equal check if the access function wrt.
3794 // to the domain is equal too. It can happen that the domain fixes
3795 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003796 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003797 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003798 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003799 if (!MAs.empty()) {
3800 auto *LastMA = MAs.front();
3801
Tobias Grossere69b2722017-08-06 23:50:25 +00003802 isl::set AR = MA->getAccessRelation().range();
3803 isl::set LastAR = LastMA->getAccessRelation().range();
3804 bool SameAR = AR.is_equal(LastAR);
Johannes Doerfertdf880232016-03-03 12:26:58 +00003805
3806 if (!SameAR)
3807 continue;
3808 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003809
3810 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003811 MAs.push_front(MA);
3812
Johannes Doerfertdf880232016-03-03 12:26:58 +00003813 Consolidated = true;
3814
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003815 // Unify the execution context of the class and this statement.
Tobias Grossere69b2722017-08-06 23:50:25 +00003816 isl::set IAClassDomainCtx = isl::manage(IAClass.ExecutionContext);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003817 if (IAClassDomainCtx)
Tobias Grossere69b2722017-08-06 23:50:25 +00003818 IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce();
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003819 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003820 IAClassDomainCtx = MACtx;
Tobias Grossere69b2722017-08-06 23:50:25 +00003821 IAClass.ExecutionContext = IAClassDomainCtx.release();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003822 break;
3823 }
3824
3825 if (Consolidated)
3826 continue;
3827
3828 // If we did not consolidate MA, thus did not find an equivalence class
3829 // for it, we create a new one.
Tobias Grossere69b2722017-08-06 23:50:25 +00003830 InvariantEquivClasses.emplace_back(InvariantEquivClassTy{
3831 PointerSCEV, MemoryAccessList{MA}, MACtx.release(), Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003832 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003833}
3834
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003835/// Check if an access range is too complex.
3836///
3837/// An access range is too complex, if it contains either many disjuncts or
3838/// very complex expressions. As a simple heuristic, we assume if a set to
3839/// be too complex if the sum of existentially quantified dimensions and
3840/// set dimensions is larger than a threshold. This reliably detects both
3841/// sets with many disjuncts as well as sets with many divisions as they
3842/// arise in h264.
3843///
3844/// @param AccessRange The range to check for complexity.
3845///
3846/// @returns True if the access range is too complex.
3847static bool isAccessRangeTooComplex(isl::set AccessRange) {
3848 unsigned NumTotalDims = 0;
3849
3850 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
3851 NumTotalDims += BSet.dim(isl::dim::div);
3852 NumTotalDims += BSet.dim(isl::dim::set);
3853 return isl::stat::ok;
3854 };
3855
3856 AccessRange.foreach_basic_set(CountDimensions);
3857
3858 if (NumTotalDims > MaxDimensionsInAccessRange)
3859 return true;
3860
3861 return false;
3862}
3863
Tobias Grosser4071cb52017-06-06 23:13:02 +00003864isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003865 // TODO: Loads that are not loop carried, hence are in a statement with
3866 // zero iterators, are by construction invariant, though we
3867 // currently "hoist" them anyway. This is necessary because we allow
3868 // them to be treated as parameters (e.g., in conditions) and our code
3869 // generation would otherwise use the old value.
3870
3871 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003872 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003873
Johannes Doerfertc9765462016-11-17 22:11:56 +00003874 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3875 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003876 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003877
3878 // Skip accesses that have an invariant base pointer which is defined but
3879 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3880 // returns a pointer that is used as a base address. However, as we want
3881 // to hoist indirect pointers, we allow the base pointer to be defined in
3882 // the region if it is also a memory access. Each ScopArrayInfo object
3883 // that has a base pointer origin has a base pointer that is loaded and
3884 // that it is invariant, thus it will be hoisted too. However, if there is
3885 // no base pointer origin we check that the base pointer is defined
3886 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003887 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003888 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003889 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003890
Tobias Grosser1515f6b2017-07-23 04:08:38 +00003891 isl::map AccessRelation = give(Access->getAccessRelation().release());
Tobias Grosser4071cb52017-06-06 23:13:02 +00003892 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003893
Tobias Grosser4071cb52017-06-06 23:13:02 +00003894 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003895 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003896
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003897 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
Tobias Grosser4071cb52017-06-06 23:13:02 +00003898 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003899
3900 auto &DL = getFunction().getParent()->getDataLayout();
3901 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3902 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003903 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003904 } else if (BB != LI->getParent()) {
3905 // Skip accesses in non-affine subregions as they might not be executed
3906 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003907 return nullptr;
3908 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003909 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003910 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003911
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003912 if (isAccessRangeTooComplex(AccessRelation.range()))
3913 return nullptr;
3914
Tobias Grosser4071cb52017-06-06 23:13:02 +00003915 isl::union_map Written = Writes.intersect_range(SafeToLoad);
3916 isl::set WrittenCtx = Written.params();
3917 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003918
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003919 if (!IsWritten)
3920 return WrittenCtx;
3921
Tobias Grosser4071cb52017-06-06 23:13:02 +00003922 WrittenCtx = WrittenCtx.remove_divs();
3923 bool TooComplex =
3924 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
3925 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003926 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003927
Tobias Grosser4071cb52017-06-06 23:13:02 +00003928 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00003929 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003930 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003931}
3932
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003933void Scop::verifyInvariantLoads() {
3934 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003935 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003936 assert(LI && contains(LI));
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003937 // If there exists a statement in the scop which has a memory access for
3938 // @p LI, then mark this scop as infeasible for optimization.
3939 for (ScopStmt &Stmt : Stmts)
3940 if (Stmt.getArrayAccessOrNULLFor(LI)) {
3941 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
3942 return;
3943 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003944 }
3945}
3946
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003947void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003948 if (!PollyInvariantLoadHoisting)
3949 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003950
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003951 isl::union_map Writes = getWrites();
Tobias Grosser0865e7752016-02-29 07:29:42 +00003952 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003953 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003954
Tobias Grosser0865e7752016-02-29 07:29:42 +00003955 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00003956 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
Tobias Grosserd16f9272017-08-06 17:25:14 +00003957 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003958
3959 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003960 for (auto InvMA : InvariantAccesses)
3961 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003962 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003963 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003964}
3965
Tobias Grosserf3adab42017-05-10 10:59:58 +00003966/// Find the canonical scop array info object for a set of invariant load
3967/// hoisted loads. The canonical array is the one that corresponds to the
3968/// first load in the list of accesses which is used as base pointer of a
3969/// scop array.
3970static const ScopArrayInfo *findCanonicalArray(Scop *S,
3971 MemoryAccessList &Accesses) {
3972 for (MemoryAccess *Access : Accesses) {
3973 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3974 Access->getAccessInstruction(), MemoryKind::Array);
3975 if (CanonicalArray)
3976 return CanonicalArray;
3977 }
3978 return nullptr;
3979}
3980
3981/// Check if @p Array severs as base array in an invariant load.
3982static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3983 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3984 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3985 if (Access2->getScopArrayInfo() == Array)
3986 return true;
3987 return false;
3988}
3989
3990/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3991/// with a reference to @p New.
3992static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3993 const ScopArrayInfo *New) {
3994 for (ScopStmt &Stmt : *S)
3995 for (MemoryAccess *Access : Stmt) {
3996 if (Access->getLatestScopArrayInfo() != Old)
3997 continue;
3998
Tobias Grosser6d588042017-08-02 19:27:16 +00003999 isl::id Id = New->getBasePtrId();
4000 isl::map Map = Access->getAccessRelation();
4001 Map = Map.set_tuple_id(isl::dim::out, Id);
Tobias Grosserf3adab42017-05-10 10:59:58 +00004002 Access->setAccessRelation(Map);
4003 }
4004}
4005
4006void Scop::canonicalizeDynamicBasePtrs() {
4007 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4008 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4009
4010 const ScopArrayInfo *CanonicalBasePtrSAI =
4011 findCanonicalArray(this, BasePtrAccesses);
4012
4013 if (!CanonicalBasePtrSAI)
4014 continue;
4015
4016 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4017 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4018 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4019 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4020 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4021 continue;
4022
4023 // we currently do not canonicalize arrays where some accesses are
4024 // hoisted as invariant loads. If we would, we need to update the access
4025 // function of the invariant loads as well. However, as this is not a
4026 // very common situation, we leave this for now to avoid further
4027 // complexity increases.
4028 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4029 continue;
4030
4031 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4032 }
4033 }
4034}
4035
Michael Kruseb738ffa2017-06-28 13:02:43 +00004036ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4037 ArrayRef<const SCEV *> Sizes,
4038 MemoryKind Kind,
4039 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004040 assert((BasePtr || BaseName) &&
4041 "BasePtr and BaseName can not be nullptr at the same time.");
4042 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4043 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4044 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004045 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004046 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004047 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004048 DL, this, BaseName));
4049 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004050 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004051 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004052 // In case of mismatching array sizes, we bail out by setting the run-time
4053 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004054 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004055 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004056 }
Tobias Grosserab671442015-05-23 05:58:27 +00004057 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004058}
4059
Michael Kruseb738ffa2017-06-28 13:02:43 +00004060ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4061 const std::string &BaseName,
4062 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004063 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4064 std::vector<const SCEV *> SCEVSizes;
4065
4066 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004067 if (size)
4068 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4069 else
4070 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004071
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004072 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4073 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004074 return SAI;
4075}
4076
Tobias Grosserf3adab42017-05-10 10:59:58 +00004077const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4078 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004079 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004080 return SAI;
4081}
4082
4083const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4084 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004085 assert(SAI && "No ScopArrayInfo available for this base pointer");
4086 return SAI;
4087}
4088
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004089std::string Scop::getContextStr() const { return getContext().to_str(); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004090
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004091std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004092 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004093 return stringFromIslObj(AssumedContext);
4094}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004095
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004096std::string Scop::getInvalidContextStr() const {
4097 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004098}
Tobias Grosser75805372011-04-29 06:27:02 +00004099
4100std::string Scop::getNameStr() const {
4101 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004102 std::tie(EntryName, ExitName) = getEntryExitStr();
4103 return EntryName + "---" + ExitName;
4104}
4105
4106std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4107 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004108 raw_string_ostream ExitStr(ExitName);
4109 raw_string_ostream EntryStr(EntryName);
4110
Tobias Grosserf240b482014-01-09 10:42:15 +00004111 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004112 EntryStr.str();
4113
4114 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004115 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004116 ExitStr.str();
4117 } else
4118 ExitName = "FunctionExit";
4119
Siddharth Bhat07bee292017-06-02 08:01:22 +00004120 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004121}
4122
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004123isl::set Scop::getContext() const { return isl::manage(isl_set_copy(Context)); }
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004124isl::space Scop::getParamSpace() const { return getContext().get_space(); }
Tobias Grosser37487052011-10-06 00:03:42 +00004125
Tobias Grosserb5563c62017-08-03 13:51:15 +00004126isl::space Scop::getFullParamSpace() const {
4127 std::vector<isl::id> FortranIDs;
4128 FortranIDs = getFortranArrayIds(arrays());
4129
4130 isl::space Space = isl::space::params_alloc(
4131 getIslCtx(), ParameterIds.size() + FortranIDs.size());
4132
4133 unsigned PDim = 0;
4134 for (const SCEV *Parameter : Parameters) {
Tobias Grosser9a635702017-08-06 19:31:27 +00004135 isl::id Id = getIdForParam(Parameter);
Tobias Grosserb5563c62017-08-03 13:51:15 +00004136 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4137 }
4138
4139 for (isl::id Id : FortranIDs)
4140 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4141
4142 return Space;
4143}
4144
Tobias Grossere1270332017-08-06 21:42:09 +00004145isl::set Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004146 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere1270332017-08-06 21:42:09 +00004147 return isl::manage(isl_set_copy(AssumedContext));
Tobias Grossere86109f2013-10-29 21:05:49 +00004148}
4149
Michael Krusef3091bf2017-03-17 13:09:52 +00004150bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004151 if (PollyProcessUnprofitable)
4152 return true;
4153
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004154 if (isEmpty())
4155 return false;
4156
4157 unsigned OptimizableStmtsOrLoops = 0;
4158 for (auto &Stmt : *this) {
4159 if (Stmt.getNumIterators() == 0)
4160 continue;
4161
4162 bool ContainsArrayAccs = false;
4163 bool ContainsScalarAccs = false;
4164 for (auto *MA : Stmt) {
4165 if (MA->isRead())
4166 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004167 ContainsArrayAccs |= MA->isLatestArrayKind();
4168 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004169 }
4170
Michael Krusef3091bf2017-03-17 13:09:52 +00004171 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004172 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4173 }
4174
4175 return OptimizableStmtsOrLoops > 1;
4176}
4177
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004178bool Scop::hasFeasibleRuntimeContext() const {
Tobias Grossere1270332017-08-06 21:42:09 +00004179 auto *PositiveContext = getAssumedContext().release();
Tobias Grosser04ec2eb2017-08-06 21:42:16 +00004180 auto *NegativeContext = getInvalidContext().release();
Tobias Grosser232fdad2017-08-06 20:19:26 +00004181 PositiveContext =
4182 addNonEmptyDomainConstraints(isl::manage(PositiveContext)).release();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004183 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4184 isl_set_is_subset(PositiveContext, NegativeContext));
4185 isl_set_free(PositiveContext);
4186 if (!IsFeasible) {
4187 isl_set_free(NegativeContext);
4188 return false;
4189 }
4190
Tobias Grosser31df6f32017-08-06 21:42:25 +00004191 auto *DomainContext = isl_union_set_params(getDomains().release());
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004192 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004193 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004194 isl_set_free(NegativeContext);
4195 isl_set_free(DomainContext);
4196
Johannes Doerfert43788c52015-08-20 05:58:56 +00004197 return IsFeasible;
4198}
4199
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004200static std::string toString(AssumptionKind Kind) {
4201 switch (Kind) {
4202 case ALIASING:
4203 return "No-aliasing";
4204 case INBOUNDS:
4205 return "Inbounds";
4206 case WRAPPING:
4207 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004208 case UNSIGNED:
4209 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004210 case COMPLEXITY:
4211 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004212 case PROFITABLE:
4213 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004214 case ERRORBLOCK:
4215 return "No-error";
4216 case INFINITELOOP:
4217 return "Finite loop";
4218 case INVARIANTLOAD:
4219 return "Invariant load";
4220 case DELINEARIZATION:
4221 return "Delinearization";
4222 }
4223 llvm_unreachable("Unknown AssumptionKind!");
4224}
4225
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004226bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4227 if (Sign == AS_ASSUMPTION) {
4228 if (isl_set_is_subset(Context, Set))
4229 return false;
4230
4231 if (isl_set_is_subset(AssumedContext, Set))
4232 return false;
4233 } else {
4234 if (isl_set_is_disjoint(Set, Context))
4235 return false;
4236
4237 if (isl_set_is_subset(Set, InvalidContext))
4238 return false;
4239 }
4240 return true;
4241}
4242
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004243bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004244 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004245 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4246 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004247
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004248 // Do never emit trivial assumptions as they only clutter the output.
4249 if (!PollyRemarksMinimal) {
4250 isl_set *Univ = nullptr;
4251 if (Sign == AS_ASSUMPTION)
4252 Univ = isl_set_universe(isl_set_get_space(Set));
4253
4254 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4255 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4256 isl_set_free(Univ);
4257
4258 if (IsTrivial)
4259 return false;
4260 }
4261
Johannes Doerfertcd195322016-11-17 21:41:08 +00004262 switch (Kind) {
4263 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004264 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004265 break;
4266 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004267 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004268 break;
4269 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004270 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004271 break;
4272 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004273 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004274 break;
4275 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004276 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004277 break;
4278 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004279 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004280 break;
4281 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004282 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004283 break;
4284 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004285 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004286 break;
4287 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004288 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004289 break;
4290 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004291 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004292 break;
4293 }
4294
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004295 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4296 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004297 if (BB)
4298 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4299 << Msg);
4300 else
4301 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4302 R.getEntry())
4303 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004304 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004305}
4306
4307void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004308 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004309 // Simplify the assumptions/restrictions first.
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004310 Set = isl_set_gist_params(Set, getContext().release());
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004311
Eli Friedmane737fc12017-07-17 23:58:33 +00004312 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004313 isl_set_free(Set);
4314 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004315 }
4316
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004317 if (Sign == AS_ASSUMPTION) {
4318 AssumedContext = isl_set_intersect(AssumedContext, Set);
4319 AssumedContext = isl_set_coalesce(AssumedContext);
4320 } else {
4321 InvalidContext = isl_set_union(InvalidContext, Set);
4322 InvalidContext = isl_set_coalesce(InvalidContext);
4323 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004324}
4325
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004326void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004327 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004328 assert((isl_set_is_params(Set) || BB) &&
4329 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004330 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004331}
4332
4333void Scop::addRecordedAssumptions() {
4334 while (!RecordedAssumptions.empty()) {
4335 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004336
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004337 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004338 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004339 continue;
4340 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004341
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004342 // If the domain was deleted the assumptions are void.
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004343 isl_set *Dom = getDomainConditions(AS.BB).release();
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004344 if (!Dom) {
4345 isl_set_free(AS.Set);
4346 continue;
4347 }
4348
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004349 // If a basic block was given use its domain to simplify the assumption.
4350 // In case of restrictions we know they only have to hold on the domain,
4351 // thus we can intersect them with the domain of the block. However, for
4352 // assumptions the domain has to imply them, thus:
4353 // _ _____
4354 // Dom => S <==> A v B <==> A - B
4355 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004356 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004357 // assumption.
4358 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004359 if (AS.Sign == AS_RESTRICTION)
4360 S = isl_set_params(isl_set_intersect(S, Dom));
4361 else /* (AS.Sign == AS_ASSUMPTION) */
4362 S = isl_set_params(isl_set_subtract(Dom, S));
4363
Eli Friedmane737fc12017-07-17 23:58:33 +00004364 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004365 }
4366}
4367
Eli Friedmane737fc12017-07-17 23:58:33 +00004368void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
Michael Kruse860870b2017-08-30 11:52:03 +00004369 DEBUG(dbgs() << "Invalidate SCoP because of reason " << Kind << "\n");
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004370 addAssumption(Kind, isl_set_empty(getParamSpace().release()), Loc,
4371 AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004372}
4373
Tobias Grosser04ec2eb2017-08-06 21:42:16 +00004374isl::set Scop::getInvalidContext() const {
4375 return isl::manage(isl_set_copy(InvalidContext));
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004376}
4377
Tobias Grosser75805372011-04-29 06:27:02 +00004378void Scop::printContext(raw_ostream &OS) const {
4379 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004380 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004381
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004382 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004383 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004384
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004385 OS.indent(4) << "Invalid Context:\n";
4386 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004387
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004388 unsigned Dim = 0;
4389 for (const SCEV *Parameter : Parameters)
4390 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004391}
4392
Johannes Doerfertb164c792014-09-18 11:17:17 +00004393void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004394 int noOfGroups = 0;
4395 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004396 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004397 noOfGroups += 1;
4398 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004399 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004400 }
4401
Tobias Grosserbb853c22015-07-25 12:31:03 +00004402 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004403 if (MinMaxAliasGroups.empty()) {
4404 OS.indent(8) << "n/a\n";
4405 return;
4406 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004407
Tobias Grosserbb853c22015-07-25 12:31:03 +00004408 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004409
4410 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004411 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004412 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004413 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004414 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4415 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004416 }
4417 OS << " ]]\n";
4418 }
4419
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004420 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004421 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004422 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004423 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004424 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4425 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004426 }
4427 OS << " ]]\n";
4428 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004429 }
4430}
4431
Michael Krusecd4c9772017-07-21 15:35:53 +00004432void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004433 OS << "Statements {\n";
4434
Michael Krusecd4c9772017-07-21 15:35:53 +00004435 for (const ScopStmt &Stmt : *this) {
4436 OS.indent(4);
4437 Stmt.print(OS, PrintInstructions);
4438 }
Tobias Grosser75805372011-04-29 06:27:02 +00004439
4440 OS.indent(4) << "}\n";
4441}
4442
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004443void Scop::printArrayInfo(raw_ostream &OS) const {
4444 OS << "Arrays {\n";
4445
Tobias Grosserab671442015-05-23 05:58:27 +00004446 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004447 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004448
4449 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004450
4451 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4452
4453 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004454 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004455
4456 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004457}
4458
Michael Krusecd4c9772017-07-21 15:35:53 +00004459void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004460 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004461 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004462 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004463 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004464 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004465 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004466 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004467 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004468 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004469 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004470 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4471 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004472 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004473 }
4474 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004475 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004476 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004477 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004478 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004479}
4480
Michael Kruse5d518462017-07-21 15:54:07 +00004481#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004482LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004483#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004484
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004485isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004486
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004487__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4488 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004489 // First try to use the SCEVAffinator to generate a piecewise defined
4490 // affine function from @p E in the context of @p BB. If that tasks becomes to
4491 // complex the affinator might return a nullptr. In such a case we invalidate
4492 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004493 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004494 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004495 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004496 // TODO: We could use a heuristic and either use:
4497 // SCEVAffinator::takeNonNegativeAssumption
4498 // or
4499 // SCEVAffinator::interpretAsUnsigned
4500 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004501 if (NonNegative)
4502 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004503 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004504 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004505
4506 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004507 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004508 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004509}
4510
Tobias Grosser31df6f32017-08-06 21:42:25 +00004511isl::union_set Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004512 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4513 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004514
Tobias Grosser808cd692015-07-14 09:33:13 +00004515 for (const ScopStmt &Stmt : *this)
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004516 Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004517
Tobias Grosser31df6f32017-08-06 21:42:25 +00004518 return isl::manage(Domain);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004519}
4520
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004521isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004522 PWACtx PWAC = getPwAff(E, BB);
4523 isl_set_free(PWAC.second);
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004524 return isl::manage(PWAC.first);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004525}
4526
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004527isl::union_map
Tobias Grossere5a35142015-11-12 14:07:09 +00004528Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004529 isl::union_map Accesses = isl::union_map::empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004530
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004531 for (ScopStmt &Stmt : *this) {
4532 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004533 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004534 continue;
4535
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004536 isl::set Domain = Stmt.getDomain();
4537 isl::map AccessDomain = MA->getAccessRelation();
4538 AccessDomain = AccessDomain.intersect_domain(Domain);
4539 Accesses = Accesses.add_map(AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004540 }
4541 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00004542
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004543 return Accesses.coalesce();
Tobias Grossere5a35142015-11-12 14:07:09 +00004544}
4545
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004546isl::union_map Scop::getMustWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004547 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004548}
4549
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004550isl::union_map Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004551 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004552}
4553
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004554isl::union_map Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004555 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004556}
4557
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004558isl::union_map Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004559 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004560}
4561
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004562isl::union_map Scop::getAccesses() {
Tobias Grosser2ac23382015-11-12 14:07:13 +00004563 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4564}
4565
Tobias Grosserfa03cb72017-08-17 22:04:53 +00004566isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
4567 return getAccessesOfType(
4568 [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
4569}
4570
Roman Gareevb3224ad2016-09-14 06:26:09 +00004571// Check whether @p Node is an extension node.
4572//
4573// @return true if @p Node is an extension node.
4574isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4575 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4576 return isl_bool_error;
4577 else
4578 return isl_bool_true;
4579}
4580
4581bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4582 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4583 nullptr) == isl_stat_error;
4584}
4585
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004586isl::union_map Scop::getSchedule() const {
4587 auto *Tree = getScheduleTree().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004588 if (containsExtensionNode(Tree)) {
4589 isl_schedule_free(Tree);
4590 return nullptr;
4591 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004592 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004593 isl_schedule_free(Tree);
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004594 return isl::manage(S);
Tobias Grosser808cd692015-07-14 09:33:13 +00004595}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004596
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004597isl::schedule Scop::getScheduleTree() const {
4598 return isl::manage(isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4599 getDomains().release()));
Tobias Grosser808cd692015-07-14 09:33:13 +00004600}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004601
Tobias Grosser808cd692015-07-14 09:33:13 +00004602void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
Tobias Grosser31df6f32017-08-06 21:42:25 +00004603 auto *S = isl_schedule_from_domain(getDomains().release());
Tobias Grosser808cd692015-07-14 09:33:13 +00004604 S = isl_schedule_insert_partial_schedule(
4605 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4606 isl_schedule_free(Schedule);
4607 Schedule = S;
4608}
4609
4610void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4611 isl_schedule_free(Schedule);
4612 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004613}
4614
Tobias Grosser990cbb42017-08-14 06:49:01 +00004615bool Scop::restrictDomains(isl::union_set Domain) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00004616 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004617 for (ScopStmt &Stmt : *this) {
Tobias Grosser990cbb42017-08-14 06:49:01 +00004618 isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
4619 isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
Tobias Grosser37eb4222014-02-20 21:43:54 +00004620
Tobias Grosser990cbb42017-08-14 06:49:01 +00004621 if (StmtDomain.is_subset(NewStmtDomain))
Tobias Grosser37eb4222014-02-20 21:43:54 +00004622 continue;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004623
4624 Changed = true;
4625
Tobias Grosser990cbb42017-08-14 06:49:01 +00004626 NewStmtDomain = NewStmtDomain.coalesce();
Tobias Grosser37eb4222014-02-20 21:43:54 +00004627
Tobias Grosser990cbb42017-08-14 06:49:01 +00004628 if (NewStmtDomain.is_empty())
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004629 Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
Tobias Grosser990cbb42017-08-14 06:49:01 +00004630 else
4631 Stmt.restrictDomain(isl::set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004632 }
Tobias Grosser37eb4222014-02-20 21:43:54 +00004633 return Changed;
4634}
4635
Tobias Grosser75805372011-04-29 06:27:02 +00004636ScalarEvolution *Scop::getSE() const { return SE; }
4637
Tobias Grosserc80d6972016-09-02 06:33:33 +00004638// Create an isl_multi_union_aff that defines an identity mapping from the
4639// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004640//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004641// # Example:
4642//
4643// Domain: { A[i,j]; B[i,j,k] }
4644// N: 1
4645//
4646// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4647//
4648// @param USet A union set describing the elements for which to generate a
4649// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004650// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004651// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004652static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004653 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004654 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004655 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004656
Tobias Grosser99320862017-05-26 17:22:03 +00004657 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004658
Tobias Grosser99320862017-05-26 17:22:03 +00004659 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4660 int Dim = S.dim(isl::dim::set);
4661 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4662 N, Dim - N);
4663 if (N > 1)
4664 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004665
Tobias Grosser99320862017-05-26 17:22:03 +00004666 Result = Result.add_pw_multi_aff(PMA);
4667 return isl::stat::ok;
4668 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004669
Tobias Grosser99320862017-05-26 17:22:03 +00004670 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004671 (void)Res;
4672
Tobias Grosser99320862017-05-26 17:22:03 +00004673 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004674
Tobias Grosser99320862017-05-26 17:22:03 +00004675 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004676}
4677
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004678void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
Michael Kruse59125512017-08-30 10:11:06 +00004679 std::vector<Instruction *> Instructions, int Count) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004680 assert(BB && "Unexpected nullptr!");
Michael Kruse59125512017-08-30 10:11:06 +00004681 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions, Count);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004682 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004683 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004684 for (Instruction *Inst : Instructions) {
4685 assert(!InstStmtMap.count(Inst) &&
4686 "Unexpected statement corresponding to the instruction.");
4687 InstStmtMap[Inst] = Stmt;
4688 }
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004689}
4690
Tobias Grosserbd15d132017-08-31 03:15:56 +00004691void Scop::addScopStmt(Region *R, Loop *SurroundingLoop,
4692 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004693 assert(R && "Unexpected nullptr!");
Tobias Grosserbd15d132017-08-31 03:15:56 +00004694 Stmts.emplace_back(*this, *R, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004695 auto *Stmt = &Stmts.back();
Tobias Grosserbd15d132017-08-31 03:15:56 +00004696
4697 for (Instruction *Inst : Instructions) {
4698 assert(!InstStmtMap.count(Inst) &&
4699 "Unexpected statement corresponding to the instruction.");
4700 InstStmtMap[Inst] = Stmt;
4701 }
4702
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004703 for (BasicBlock *BB : R->blocks()) {
Michael Kruse4dfa7322017-07-18 15:41:49 +00004704 StmtMap[BB].push_back(Stmt);
Tobias Grosserbd15d132017-08-31 03:15:56 +00004705 if (BB == R->getEntry())
4706 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004707 for (Instruction &Inst : *BB) {
4708 assert(!InstStmtMap.count(&Inst) &&
4709 "Unexpected statement corresponding to the instruction.");
4710 InstStmtMap[&Inst] = Stmt;
4711 }
4712 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004713}
4714
Tobias Grosser85048ef2017-08-06 17:24:59 +00004715ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
4716 isl::set Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004717#ifndef NDEBUG
Tobias Grosser85048ef2017-08-06 17:24:59 +00004718 isl::set SourceDomain = SourceRel.domain();
4719 isl::set TargetDomain = TargetRel.domain();
4720 assert(Domain.is_subset(TargetDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004721 "Target access not defined for complete statement domain");
Tobias Grosser85048ef2017-08-06 17:24:59 +00004722 assert(Domain.is_subset(SourceDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004723 "Source access not defined for complete statement domain");
Tobias Grossereba86a12016-11-09 04:24:49 +00004724#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004725 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4726 CopyStmtsNum++;
4727 return &(Stmts.back());
4728}
4729
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004730void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004731 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004732 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004733 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004734 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4735 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004736}
4737
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004738/// To generate a schedule for the elements in a Region we traverse the Region
4739/// in reverse-post-order and add the contained RegionNodes in traversal order
4740/// to the schedule of the loop that is currently at the top of the LoopStack.
4741/// For loop-free codes, this results in a correct sequential ordering.
4742///
4743/// Example:
4744/// bb1(0)
4745/// / \.
4746/// bb2(1) bb3(2)
4747/// \ / \.
4748/// bb4(3) bb5(4)
4749/// \ /
4750/// bb6(5)
4751///
4752/// Including loops requires additional processing. Whenever a loop header is
4753/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4754/// from an empty schedule, we first process all RegionNodes that are within
4755/// this loop and complete the sequential schedule at this loop-level before
4756/// processing about any other nodes. To implement this
4757/// loop-nodes-first-processing, the reverse post-order traversal is
4758/// insufficient. Hence, we additionally check if the traversal yields
4759/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4760/// These region-nodes are then queue and only traverse after the all nodes
4761/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004762void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004763 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004764
4765 ReversePostOrderTraversal<Region *> RTraversal(R);
4766 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4767 std::deque<RegionNode *> DelayList;
4768 bool LastRNWaiting = false;
4769
4770 // Iterate over the region @p R in reverse post-order but queue
4771 // sub-regions/blocks iff they are not part of the last encountered but not
4772 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4773 // that we queued the last sub-region/block from the reverse post-order
4774 // iterator. If it is set we have to explore the next sub-region/block from
4775 // the iterator (if any) to guarantee progress. If it is not set we first try
4776 // the next queued sub-region/blocks.
4777 while (!WorkList.empty() || !DelayList.empty()) {
4778 RegionNode *RN;
4779
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004780 if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004781 RN = WorkList.front();
4782 WorkList.pop_front();
4783 LastRNWaiting = false;
4784 } else {
4785 RN = DelayList.front();
4786 DelayList.pop_front();
4787 }
4788
4789 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004790 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004791 L = OuterScopLoop;
4792
Tobias Grosser151ae322016-04-03 19:36:52 +00004793 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004794 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004795 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004796 LastRNWaiting = true;
4797 DelayList.push_back(RN);
4798 continue;
4799 }
4800 LoopStack.push_back({L, nullptr, 0});
4801 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004802 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004803 }
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004804}
4805
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004806void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004807 if (RN->isSubRegion()) {
4808 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004809 if (!isNonAffineSubRegion(LocalRegion)) {
4810 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004811 return;
4812 }
4813 }
Michael Kruse046dde42015-08-10 13:01:57 +00004814
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004815 auto &LoopData = LoopStack.back();
4816 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004817
Michael Kruse1ce67912017-07-20 17:18:58 +00004818 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004819 auto *UDomain = isl_union_set_from_set(Stmt->getDomain().release());
Tobias Grosser8362c262016-01-06 15:30:06 +00004820 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004821 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004822 }
4823
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004824 // Check if we just processed the last node in this loop. If we did, finalize
4825 // the loop by:
4826 //
4827 // - adding new schedule dimensions
4828 // - folding the resulting schedule into the parent loop schedule
4829 // - dropping the loop schedule from the LoopStack.
4830 //
4831 // Then continue to check surrounding loops, which might also have been
4832 // completed by this node.
4833 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004834 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004835 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004836 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004837
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004838 LoopStack.pop_back();
4839 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004840
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004841 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00004842 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
4843 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
4844 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004845 NextLoopData.Schedule =
4846 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004847 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004848
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004849 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4850 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004851 }
Tobias Grosser75805372011-04-29 06:27:02 +00004852}
4853
Michael Kruse6eba4b12017-07-20 17:08:50 +00004854ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
4855 auto StmtMapIt = StmtMap.find(BB);
4856 if (StmtMapIt == StmtMap.end())
4857 return {};
Michael Kruse6eba4b12017-07-20 17:08:50 +00004858 return StmtMapIt->second;
4859}
4860
4861ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
4862 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004863 if (!StmtList.empty())
Michael Kruse6eba4b12017-07-20 17:08:50 +00004864 return StmtList.back();
4865 return nullptr;
4866}
4867
Michael Kruse1ce67912017-07-20 17:18:58 +00004868ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004869 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00004870 return getStmtListFor(RN->getNodeAs<Region>());
4871 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00004872}
4873
Michael Kruse1ce67912017-07-20 17:18:58 +00004874ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
4875 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00004876}
4877
Johannes Doerfert96425c22015-08-30 21:13:53 +00004878int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004879 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00004880 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004881 // outermostLoopInRegion always returns nullptr for top level regions
4882 if (R.isTopLevelRegion()) {
4883 // LoopInfo's depths start at 1, we start at 0
4884 return L->getLoopDepth() - 1;
4885 } else {
4886 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4887 assert(OuterLoop);
4888 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4889 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00004890}
4891
Roman Gareevd7754a12016-07-30 09:25:51 +00004892ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4893 for (auto &SAI : arrays()) {
4894 if (SAI->getName() == BaseName)
4895 return SAI;
4896 }
4897 return nullptr;
4898}
4899
Michael Kruse8b805802017-07-19 17:11:25 +00004900void Scop::addAccessData(MemoryAccess *Access) {
4901 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
4902 assert(SAI && "can only use after access relations have been constructed");
4903
4904 if (Access->isOriginalValueKind() && Access->isRead())
4905 ValueUseAccs[SAI].push_back(Access);
4906 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
4907 PHIIncomingAccs[SAI].push_back(Access);
4908}
4909
4910void Scop::removeAccessData(MemoryAccess *Access) {
4911 if (Access->isOriginalValueKind() && Access->isRead()) {
4912 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
4913 std::remove(Uses.begin(), Uses.end(), Access);
4914 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
4915 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
4916 std::remove(Incomings.begin(), Incomings.end(), Access);
4917 }
4918}
4919
4920MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
4921 assert(SAI->isValueKind());
4922
4923 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
4924 if (!Val)
4925 return nullptr;
4926
4927 ScopStmt *Stmt = getStmtFor(Val);
4928 if (!Stmt)
4929 return nullptr;
4930
4931 return Stmt->lookupValueWriteOf(Val);
4932}
4933
4934ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
4935 assert(SAI->isValueKind());
4936 auto It = ValueUseAccs.find(SAI);
4937 if (It == ValueUseAccs.end())
4938 return {};
4939 return It->second;
4940}
4941
4942MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
4943 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4944
4945 if (SAI->isExitPHIKind())
4946 return nullptr;
4947
4948 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
4949 ScopStmt *Stmt = getStmtFor(PHI);
4950 assert(Stmt && "PHINode must be within the SCoP");
4951
4952 return Stmt->lookupPHIReadOf(PHI);
4953}
4954
4955ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
4956 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4957 auto It = PHIIncomingAccs.find(SAI);
4958 if (It == PHIIncomingAccs.end())
4959 return {};
4960 return It->second;
4961}
4962
Michael Krusea508a4e2017-07-27 14:39:52 +00004963bool Scop::isEscaping(Instruction *Inst) {
4964 assert(contains(Inst) && "The concept of escaping makes only sense for "
4965 "values defined inside the SCoP");
4966
4967 for (Use &Use : Inst->uses()) {
4968 BasicBlock *UserBB = getUseBlock(Use);
4969 if (!contains(UserBB))
4970 return true;
4971
4972 // When the SCoP region exit needs to be simplified, PHIs in the region exit
4973 // move to a new basic block such that its incoming blocks are not in the
4974 // SCoP anymore.
4975 if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
4976 isExit(cast<PHINode>(Use.getUser())->getParent()))
4977 return true;
4978 }
4979 return false;
4980}
4981
Michael Kruse06ed5292017-08-23 13:50:30 +00004982Scop::ScopStatistics Scop::getStatistics() const {
4983 ScopStatistics Result;
4984#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
4985 auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
4986
4987 int NumTotalLoops = LoopStat.NumLoops;
4988 Result.NumBoxedLoops = getBoxedLoops().size();
4989 Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
4990
4991 for (const ScopStmt &Stmt : *this) {
4992 isl::set Domain = Stmt.getDomain().intersect_params(getContext());
4993 bool IsInLoop = Stmt.getNumIterators() >= 1;
4994 for (MemoryAccess *MA : Stmt) {
4995 if (!MA->isWrite())
4996 continue;
4997
4998 if (MA->isLatestValueKind()) {
4999 Result.NumValueWrites += 1;
5000 if (IsInLoop)
5001 Result.NumValueWritesInLoops += 1;
5002 }
5003
5004 if (MA->isLatestAnyPHIKind()) {
5005 Result.NumPHIWrites += 1;
5006 if (IsInLoop)
5007 Result.NumPHIWritesInLoops += 1;
5008 }
5009
5010 isl::set AccSet =
5011 MA->getAccessRelation().intersect_domain(Domain).range();
5012 if (AccSet.is_singleton()) {
5013 Result.NumSingletonWrites += 1;
5014 if (IsInLoop)
5015 Result.NumSingletonWritesInLoops += 1;
5016 }
5017 }
5018 }
5019#endif
5020 return Result;
5021}
5022
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00005023raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
5024 scop.print(OS, PollyPrintInstructions);
5025 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00005026}
5027
Johannes Doerfert99191c72016-05-31 09:41:04 +00005028//===----------------------------------------------------------------------===//
5029void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5030 AU.addRequired<LoopInfoWrapperPass>();
5031 AU.addRequired<RegionInfoPass>();
5032 AU.addRequired<DominatorTreeWrapperPass>();
5033 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005034 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005035 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005036 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00005037 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005038 AU.setPreservesAll();
5039}
5040
Michael Kruse06ed5292017-08-23 13:50:30 +00005041void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
5042 Scop::ScopStatistics ScopStats) {
5043 assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
5044
5045 NumScops++;
Tobias Grossercd01a362017-02-17 08:12:36 +00005046 NumLoopsInScop += Stats.NumLoops;
5047 MaxNumLoopsInScop =
5048 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5049
Tobias Grossercd01a362017-02-17 08:12:36 +00005050 if (Stats.MaxDepth == 1)
5051 NumScopsDepthOne++;
5052 else if (Stats.MaxDepth == 2)
5053 NumScopsDepthTwo++;
5054 else if (Stats.MaxDepth == 3)
5055 NumScopsDepthThree++;
5056 else if (Stats.MaxDepth == 4)
5057 NumScopsDepthFour++;
5058 else if (Stats.MaxDepth == 5)
5059 NumScopsDepthFive++;
5060 else
5061 NumScopsDepthLarger++;
Michael Kruse06ed5292017-08-23 13:50:30 +00005062
5063 NumAffineLoops += ScopStats.NumAffineLoops;
5064 NumBoxedLoops += ScopStats.NumBoxedLoops;
5065
5066 NumValueWrites += ScopStats.NumValueWrites;
5067 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
5068 NumPHIWrites += ScopStats.NumPHIWrites;
5069 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
5070 NumSingletonWrites += ScopStats.NumSingletonWrites;
5071 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
Tobias Grossercd01a362017-02-17 08:12:36 +00005072}
5073
Johannes Doerfert99191c72016-05-31 09:41:04 +00005074bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005075 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005076
5077 if (!SD.isMaxRegionInScop(*R))
5078 return false;
5079
5080 Function *F = R->getEntry()->getParent();
5081 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5082 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5083 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5084 auto const &DL = F->getParent()->getDataLayout();
5085 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005086 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005087 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005088
Michael Krusea4f447c2017-08-28 14:07:33 +00005089 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005090 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005091
Michael Kruse06ed5292017-08-23 13:50:30 +00005092#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Tobias Grossercd01a362017-02-17 08:12:36 +00005093 if (S) {
5094 ScopDetection::LoopStats Stats =
5095 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005096 updateLoopCountStatistic(Stats, S->getStatistics());
Tobias Grossercd01a362017-02-17 08:12:36 +00005097 }
Michael Kruse06ed5292017-08-23 13:50:30 +00005098#endif
Tobias Grossercd01a362017-02-17 08:12:36 +00005099
Tobias Grosser75805372011-04-29 06:27:02 +00005100 return false;
5101}
5102
Johannes Doerfert99191c72016-05-31 09:41:04 +00005103void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005104 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005105 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005106 else
5107 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005108}
Tobias Grosser75805372011-04-29 06:27:02 +00005109
Johannes Doerfert99191c72016-05-31 09:41:04 +00005110char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005111
Johannes Doerfert99191c72016-05-31 09:41:04 +00005112Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5113
5114INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005115 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005116 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005117INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005118INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005119INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005120INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005121INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005122INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005123INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005124INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005125 "Polly - Create polyhedral description of Scops", false,
5126 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005127
5128//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005129ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5130 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
Michael Krusea4f447c2017-08-28 14:07:33 +00005131 AssumptionCache &AC, OptimizationRemarkEmitter &ORE)
5132 : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC), ORE(ORE) {
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005133 recompute();
5134}
5135
5136void ScopInfo::recompute() {
5137 RegionToScopMap.clear();
Michael Krusea6d48f52017-06-08 12:06:15 +00005138 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005139 /// function.
5140 for (auto &It : SD) {
5141 Region *R = const_cast<Region *>(It);
5142 if (!SD.isMaxRegionInScop(*R))
5143 continue;
5144
Michael Krusea4f447c2017-08-28 14:07:33 +00005145 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005146 std::unique_ptr<Scop> S = SB.getScop();
5147 if (!S)
5148 continue;
Michael Kruse06ed5292017-08-23 13:50:30 +00005149#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Philip Pfaffeead67db2017-08-02 11:14:41 +00005150 ScopDetection::LoopStats Stats =
5151 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005152 updateLoopCountStatistic(Stats, S->getStatistics());
5153#endif
Philip Pfaffe838e0882017-05-15 12:55:14 +00005154 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5155 assert(Inserted && "Building Scop for the same region twice!");
5156 (void)Inserted;
5157 }
5158}
5159
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005160bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
5161 FunctionAnalysisManager::Invalidator &Inv) {
5162 // Check whether the analysis, all analyses on functions have been preserved
5163 // or anything we're holding references to is being invalidated
5164 auto PAC = PA.getChecker<ScopInfoAnalysis>();
5165 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
5166 Inv.invalidate<ScopAnalysis>(F, PA) ||
5167 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
5168 Inv.invalidate<LoopAnalysis>(F, PA) ||
5169 Inv.invalidate<AAManager>(F, PA) ||
5170 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
5171 Inv.invalidate<AssumptionAnalysis>(F, PA);
5172}
5173
Philip Pfaffe838e0882017-05-15 12:55:14 +00005174AnalysisKey ScopInfoAnalysis::Key;
5175
5176ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5177 FunctionAnalysisManager &FAM) {
5178 auto &SD = FAM.getResult<ScopAnalysis>(F);
5179 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5180 auto &LI = FAM.getResult<LoopAnalysis>(F);
5181 auto &AA = FAM.getResult<AAManager>(F);
5182 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5183 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5184 auto &DL = F.getParent()->getDataLayout();
Michael Krusea4f447c2017-08-28 14:07:33 +00005185 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5186 return {DL, SD, SE, LI, AA, DT, AC, ORE};
Philip Pfaffe838e0882017-05-15 12:55:14 +00005187}
5188
5189PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5190 FunctionAnalysisManager &FAM) {
5191 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
Philip Pfaffe96d21432017-08-04 11:28:51 +00005192 // Since the legacy PM processes Scops in bottom up, we print them in reverse
5193 // order here to keep the output persistent
5194 for (auto &It : reverse(SI)) {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005195 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005196 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005197 else
5198 Stream << "Invalid Scop!\n";
5199 }
5200 return PreservedAnalyses::all();
5201}
5202
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005203void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5204 AU.addRequired<LoopInfoWrapperPass>();
5205 AU.addRequired<RegionInfoPass>();
5206 AU.addRequired<DominatorTreeWrapperPass>();
5207 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005208 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005209 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005210 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00005211 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005212 AU.setPreservesAll();
5213}
5214
5215bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005216 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005217 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5218 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5219 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5220 auto const &DL = F.getParent()->getDataLayout();
5221 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005222 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005223 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005224
Michael Krusea4f447c2017-08-28 14:07:33 +00005225 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC, ORE});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005226 return false;
5227}
5228
5229void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005230 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005231 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005232 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005233 else
5234 OS << "Invalid Scop!\n";
5235 }
5236}
5237
5238char ScopInfoWrapperPass::ID = 0;
5239
5240Pass *polly::createScopInfoWrapperPassPass() {
5241 return new ScopInfoWrapperPass();
5242}
5243
5244INITIALIZE_PASS_BEGIN(
5245 ScopInfoWrapperPass, "polly-function-scops",
5246 "Polly - Create polyhedral description of all Scops of a function", false,
5247 false);
5248INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005249INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005250INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5251INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5252INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005253INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005254INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5255INITIALIZE_PASS_END(
5256 ScopInfoWrapperPass, "polly-function-scops",
5257 "Polly - Create polyhedral description of all Scops of a function", false,
5258 false)