blob: 24ab38bb056700b4aca1135c307d3fa38557844c [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
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000177// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000178// operations can overflow easily. Additive reductions and bit operations
179// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000180static cl::opt<bool> DisableMultiplicativeReductions(
181 "polly-disable-multiplicative-reductions",
182 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
183 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000184
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000185static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
186 "polly-rtc-max-array-disjuncts",
187 cl::desc("The maximal number of disjunts allowed in memory accesses to "
188 "to build RTCs."),
189 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
190
Johannes Doerfert9143d672014-09-27 11:02:39 +0000191static cl::opt<unsigned> RunTimeChecksMaxParameters(
192 "polly-rtc-max-parameters",
193 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
194 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
195
Tobias Grosser71500722015-03-28 15:11:14 +0000196static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
197 "polly-rtc-max-arrays-per-group",
198 cl::desc("The maximal number of arrays to compare in each alias group."),
199 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000200
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000201static cl::opt<std::string> UserContextStr(
202 "polly-context", cl::value_desc("isl parameter set"),
203 cl::desc("Provide additional constraints on the context parameters"),
204 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000205
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000206static cl::opt<bool> DetectReductions("polly-detect-reductions",
207 cl::desc("Detect and exploit reductions"),
208 cl::Hidden, cl::ZeroOrMore,
209 cl::init(true), cl::cat(PollyCategory));
210
Tobias Grosser2937b592016-04-29 11:43:20 +0000211static cl::opt<bool>
212 IslOnErrorAbort("polly-on-isl-error-abort",
213 cl::desc("Abort if an isl error is encountered"),
214 cl::init(true), cl::cat(PollyCategory));
215
Tobias Grosserd7c49752017-02-28 09:45:54 +0000216static cl::opt<bool> PollyPreciseInbounds(
217 "polly-precise-inbounds",
218 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
219 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
220
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000221static cl::opt<bool>
222 PollyIgnoreInbounds("polly-ignore-inbounds",
223 cl::desc("Do not take inbounds assumptions at all"),
224 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
225
Tobias Grosser5842dee2017-03-17 13:00:53 +0000226static cl::opt<bool> PollyIgnoreParamBounds(
227 "polly-ignore-parameter-bounds",
228 cl::desc(
229 "Do not add parameter bounds and do no gist simplify sets accordingly"),
230 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
231
Siddharth Bhat7bc77e82017-08-21 11:57:04 +0000232static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams(
233 "polly-allow-dereference-of-all-function-parameters",
234 cl::desc(
235 "Treat all parameters to functions that are pointers as dereferencible."
236 " This is useful for invariant load hoisting, since we can generate"
237 " less runtime checks. This is only valid if all pointers to functions"
238 " are always initialized, so that Polly can choose to hoist"
239 " their loads. "),
240 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
241
Tobias Grosserc2f15102017-03-01 21:11:27 +0000242static cl::opt<bool> PollyPreciseFoldAccesses(
243 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000244 cl::desc("Fold memory accesses to model more possible delinearizations "
245 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000246 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000247
Michael Kruse5ae08c02017-05-06 14:03:58 +0000248bool polly::UseInstructionNames;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000249
Michael Kruse5ae08c02017-05-06 14:03:58 +0000250static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000251 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000252 cl::desc("Use LLVM-IR names when deriving statement names"),
253 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
254 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000255
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000256static cl::opt<bool> PollyPrintInstructions(
257 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
258 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
259
Michael Kruse7bf39442015-09-10 12:46:52 +0000260//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000261
Michael Kruse046dde42015-08-10 13:01:57 +0000262// Create a sequence of two schedules. Either argument may be null and is
263// interpreted as the empty schedule. Can also return null if both schedules are
264// empty.
265static __isl_give isl_schedule *
266combineInSequence(__isl_take isl_schedule *Prev,
267 __isl_take isl_schedule *Succ) {
268 if (!Prev)
269 return Succ;
270 if (!Succ)
271 return Prev;
272
273 return isl_schedule_sequence(Prev, Succ);
274}
275
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000276static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
277 int dim, isl::dim type) {
278 isl::val V;
279 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000280
Tobias Grosser3281f602017-02-16 18:39:14 +0000281 // The upper and lower bound for a parameter value is derived either from
282 // the data type of the parameter or from the - possibly more restrictive -
283 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000284 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
285 S = S.lower_bound_val(type, dim, V);
286 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
287 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000288
Tobias Grosser3281f602017-02-16 18:39:14 +0000289 if (Range.isFullSet())
290 return S;
291
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000292 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000293 return S;
294
Tobias Grosser3281f602017-02-16 18:39:14 +0000295 // In case of signed wrapping, we can refine the set of valid values by
296 // excluding the part not covered by the wrapping range.
297 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000298 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
299 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000300
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000301 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
302 V = V.sub_ui(1);
303 isl::set SUB = S.upper_bound_val(type, dim, V);
304 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000305 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000306
Tobias Grosser3281f602017-02-16 18:39:14 +0000307 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000308}
309
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000310static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
311 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
312 if (!BasePtrLI)
313 return nullptr;
314
Johannes Doerfert952b5302016-05-23 12:40:48 +0000315 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000316 return nullptr;
317
318 ScalarEvolution &SE = *S->getSE();
319
320 auto *OriginBaseSCEV =
321 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
322 if (!OriginBaseSCEV)
323 return nullptr;
324
325 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
326 if (!OriginBaseSCEVUnknown)
327 return nullptr;
328
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000329 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000330 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000331}
332
Tobias Grosser27db02b2017-08-06 17:25:05 +0000333ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000334 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000335 const DataLayout &DL, Scop *S,
336 const char *BaseName)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000337 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000338 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000339 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000340 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
341 Kind == MemoryKind::PHI ? "__phi" : "",
342 UseInstructionNames);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000343 Id = isl::id::alloc(Ctx, BasePtrName, this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000344
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000345 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000346
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000347 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000348 BasePtrOriginSAI = nullptr;
349 return;
350 }
351
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000352 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
353 if (BasePtrOriginSAI)
354 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000355}
356
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000357ScopArrayInfo::~ScopArrayInfo() = default;
358
Tobias Grosser77eef902017-07-21 23:07:56 +0000359isl::space ScopArrayInfo::getSpace() const {
360 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
361 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000362 return Space;
363}
364
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000365bool ScopArrayInfo::isReadOnly() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +0000366 isl::union_set WriteSet = S.getWrites().range();
Tobias Grosser77eef902017-07-21 23:07:56 +0000367 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000368 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000369
Tobias Grosser2ade9862017-05-23 06:41:04 +0000370 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000371}
372
Tobias Grosserf3adab42017-05-10 10:59:58 +0000373bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
374 if (Array->getElementType() != getElementType())
375 return false;
376
377 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
378 return false;
379
380 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
381 if (Array->getDimensionSize(i) != getDimensionSize(i))
382 return false;
383
384 return true;
385}
386
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000387void ScopArrayInfo::updateElementType(Type *NewElementType) {
388 if (NewElementType == ElementType)
389 return;
390
Tobias Grosserd840fc72016-02-04 13:18:42 +0000391 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
392 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
393
Johannes Doerferta7920982016-02-25 14:08:48 +0000394 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000395 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000396
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000397 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
398 ElementType = NewElementType;
399 } else {
400 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
401 ElementType = IntegerType::get(ElementType->getContext(), GCD);
402 }
403}
404
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000405/// Make the ScopArrayInfo model a Fortran Array
406void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
407 assert(FAD && "got invalid Fortran array descriptor");
408 if (this->FAD) {
409 assert(this->FAD == FAD &&
410 "receiving different array descriptors for same array");
411 return;
412 }
413
414 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
415 assert(!this->FAD);
416 this->FAD = FAD;
417
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000418 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000419
420 std::string param_name = getName();
421 param_name += "_fortranarr_size";
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000422 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000423
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000424 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
425 isl::pw_aff PwAff =
426 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000427
Tobias Grosser77eef902017-07-21 23:07:56 +0000428 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000429}
430
Tobias Grosserbedef002016-12-02 08:10:56 +0000431bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
432 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000433 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
434 int ExtraDimsNew = NewSizes.size() - SharedDims;
435 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000436
Tobias Grosserbedef002016-12-02 08:10:56 +0000437 if (CheckConsistency) {
438 for (int i = 0; i < SharedDims; i++) {
439 auto *NewSize = NewSizes[i + ExtraDimsNew];
440 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
441 if (NewSize && KnownSize && NewSize != KnownSize)
442 return false;
443 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000444
Tobias Grosserbedef002016-12-02 08:10:56 +0000445 if (DimensionSizes.size() >= NewSizes.size())
446 return true;
447 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000448
449 DimensionSizes.clear();
450 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
451 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000452 DimensionSizesPw.clear();
453 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000454 if (!Expr) {
455 DimensionSizesPw.push_back(nullptr);
456 continue;
457 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000458 isl::pw_aff Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000459 DimensionSizesPw.push_back(Size);
460 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000461 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000462}
463
Tobias Grosser77eef902017-07-21 23:07:56 +0000464std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000465
466int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000467 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000468}
469
Tobias Grosser77eef902017-07-21 23:07:56 +0000470isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000471
Michael Kruse5d518462017-07-21 15:54:07 +0000472#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000473LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000474#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000475
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000476void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000477 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000478 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000479 // If this is a Fortran array, then we can print the outermost dimension
480 // as a isl_pw_aff even though there is no SCEV information.
481 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
482
483 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
484 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000485 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000486 u++;
487 }
488 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000489 OS << "[";
490
Tobias Grosser26253842015-11-10 14:24:21 +0000491 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000492 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000493 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000494 } else {
495 OS << *getDimensionSize(u);
496 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000497
498 OS << "]";
499 }
500
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000501 OS << ";";
502
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000503 if (BasePtrOriginSAI)
504 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
505
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000506 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000507}
508
509const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000510ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
511 isl::id Id = PMA.get_tuple_id(isl::dim::out);
512 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000513 return getFromId(Id);
514}
515
Tobias Grosser206e9e32017-07-24 16:22:27 +0000516const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
517 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000518 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000519 return SAI;
520}
521
Michael Kruse3b425ff2016-04-11 14:34:08 +0000522void MemoryAccess::wrapConstantDimensions() {
523 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000524 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000525 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000526 unsigned DimsArray = SAI->getNumberOfDimensions();
527
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000528 isl::multi_aff DivModAff = isl::multi_aff::identity(
529 ArraySpace.map_from_domain_and_range(ArraySpace));
530 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000531
532 // Begin with last dimension, to iteratively carry into higher dimensions.
533 for (int i = DimsArray - 1; i > 0; i--) {
534 auto *DimSize = SAI->getDimensionSize(i);
535 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
536
537 // This transformation is not applicable to dimensions with dynamic size.
538 if (!DimSizeCst)
539 continue;
540
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000541 // This transformation is not applicable to dimensions of size zero.
542 if (DimSize->isZero())
543 continue;
544
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000545 isl::val DimSizeVal =
546 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
547 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
548 isl::aff PrevVar =
549 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000550
551 // Compute: index % size
552 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grossercb0224a2017-08-06 15:56:45 +0000553 isl::aff Modulo = Var.mod(DimSizeVal);
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000554 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000555
556 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000557 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
558 Divide = Divide.floor();
559 Divide = Divide.add(PrevVar);
560 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000561
562 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000563 DivModAff = DivModAff.set_aff(i, Modulo);
564 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000565 }
566
567 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000568 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000569 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
570 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000571 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000572}
573
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000574void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000575 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000576 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000577 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000578 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000579
Tobias Grosser7be82452017-05-21 20:38:33 +0000580 auto DimsArray = ArraySpace.dim(isl::dim::set);
581 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000582 auto DimsMissing = DimsArray - DimsAccess;
583
Michael Kruse375cb5f2016-02-24 22:08:24 +0000584 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000585 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000586 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000587 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000588
Tobias Grosser7be82452017-05-21 20:38:33 +0000589 isl::map Map = isl::map::from_domain_and_range(
590 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000591
592 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000593 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000594
595 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000596 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000597
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000598 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000599
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000600 // For the non delinearized arrays, divide the access function of the last
601 // subscript by the size of the elements in the array.
602 //
603 // A stride one array access in C expressed as A[i] is expressed in
604 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
605 // two subsequent values of 'i' index two values that are stored next to
606 // each other in memory. By this division we make this characteristic
607 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000608 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000609 // that divides the offsets of all accesses to this base pointer.
610 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000611 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000612 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000613 }
614
Michael Kruse3b425ff2016-04-11 14:34:08 +0000615 // We currently do this only if we added at least one dimension, which means
616 // some dimension's indices have not been specified, an indicator that some
617 // index values have been added together.
618 // TODO: Investigate general usefulness; Effect on unit tests is to make index
619 // expressions more complicated.
620 if (DimsMissing)
621 wrapConstantDimensions();
622
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000623 if (!isAffine())
624 computeBoundsOnAccessRelation(ArrayElemSize);
625
Tobias Grosserd840fc72016-02-04 13:18:42 +0000626 // Introduce multi-element accesses in case the type loaded by this memory
627 // access is larger than the canonical element type of the array.
628 //
629 // An access ((float *)A)[i] to an array char *A is modeled as
630 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000631 if (ElemBytes > ArrayElemSize) {
632 assert(ElemBytes % ArrayElemSize == 0 &&
633 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000634 isl::map Map = isl::map::from_domain_and_range(
635 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000636 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000637 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000638
Tobias Grosser7be82452017-05-21 20:38:33 +0000639 isl::constraint C;
640 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000641
Tobias Grosser7be82452017-05-21 20:38:33 +0000642 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000643 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
644
Tobias Grosser7be82452017-05-21 20:38:33 +0000645 C = isl::constraint::alloc_inequality(LS);
646 C = C.set_constant_val(isl::val(Ctx, Num - 1));
647 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
648 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
649 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000650
Tobias Grosser7be82452017-05-21 20:38:33 +0000651 C = isl::constraint::alloc_inequality(LS);
652 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
653 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
654 C = C.set_constant_val(isl::val(Ctx, 0));
655 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000656 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000657 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000658}
659
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000660const std::string
661MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
662 switch (RT) {
663 case MemoryAccess::RT_NONE:
664 llvm_unreachable("Requested a reduction operator string for a memory "
665 "access which isn't a reduction");
666 case MemoryAccess::RT_ADD:
667 return "+";
668 case MemoryAccess::RT_MUL:
669 return "*";
670 case MemoryAccess::RT_BOR:
671 return "|";
672 case MemoryAccess::RT_BXOR:
673 return "^";
674 case MemoryAccess::RT_BAND:
675 return "&";
676 }
677 llvm_unreachable("Unknown reduction type");
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000678}
679
Tobias Grosserc80d6972016-09-02 06:33:33 +0000680/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000681static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
682 const Instruction *Load) {
683 if (!BinOp)
684 return MemoryAccess::RT_NONE;
685 switch (BinOp->getOpcode()) {
686 case Instruction::FAdd:
687 if (!BinOp->hasUnsafeAlgebra())
688 return MemoryAccess::RT_NONE;
689 // Fall through
690 case Instruction::Add:
691 return MemoryAccess::RT_ADD;
692 case Instruction::Or:
693 return MemoryAccess::RT_BOR;
694 case Instruction::Xor:
695 return MemoryAccess::RT_BXOR;
696 case Instruction::And:
697 return MemoryAccess::RT_BAND;
698 case Instruction::FMul:
699 if (!BinOp->hasUnsafeAlgebra())
700 return MemoryAccess::RT_NONE;
701 // Fall through
702 case Instruction::Mul:
703 if (DisableMultiplicativeReductions)
704 return MemoryAccess::RT_NONE;
705 return MemoryAccess::RT_MUL;
706 default:
707 return MemoryAccess::RT_NONE;
708 }
709}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000710
Michael Kruse2fa35192016-09-01 19:53:31 +0000711const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000712 isl::id ArrayId = getArrayId();
713 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000714 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000715 return SAI;
716}
717
Michael Kruse2fa35192016-09-01 19:53:31 +0000718const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000719 isl::id ArrayId = getLatestArrayId();
720 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000721 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000722 return SAI;
723}
724
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000725isl::id MemoryAccess::getOriginalArrayId() const {
726 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000727}
728
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000729isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000730 if (!hasNewAccessRelation())
731 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000732 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000733}
734
Tobias Grosser6a870362017-07-23 04:08:45 +0000735isl::map MemoryAccess::getAddressFunction() const {
736 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000737}
738
Tobias Grosser3b196132017-07-23 04:08:52 +0000739isl::pw_multi_aff
740MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
741 isl::map Schedule, ScheduledAccRel;
742 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000743
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000744 UDomain = getStatement()->getDomain();
Tobias Grosser3b196132017-07-23 04:08:52 +0000745 USchedule = USchedule.intersect_domain(UDomain);
746 Schedule = isl::map::from_union_map(USchedule);
747 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
748 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000749}
750
Tobias Grosser22da5f02017-07-23 04:08:27 +0000751isl::map MemoryAccess::getOriginalAccessRelation() const {
752 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000753}
754
Johannes Doerferta99130f2014-10-13 12:58:03 +0000755std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000756 return stringFromIslObj(AccessRelation.get());
Tobias Grosser5d453812011-10-06 00:04:11 +0000757}
758
Tobias Grosser22da5f02017-07-23 04:08:27 +0000759isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
760 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000761}
762
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000763isl::map MemoryAccess::getNewAccessRelation() const {
764 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000765}
766
Tobias Grosser6f730082015-09-05 07:46:47 +0000767std::string MemoryAccess::getNewAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000768 return stringFromIslObj(NewAccessRelation.get());
Tobias Grosser6f730082015-09-05 07:46:47 +0000769}
770
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000771std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser2b7479b2017-08-06 11:41:10 +0000772 return getAccessRelation().to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000773}
774
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000775isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
776 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000777 Space = Space.align_params(Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000778
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000779 return isl::basic_map::from_domain_and_range(
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000780 isl::basic_set::universe(Statement->getDomainSpace()),
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000781 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000782}
783
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000784// Formalize no out-of-bound access assumption
785//
786// When delinearizing array accesses we optimistically assume that the
787// delinearized accesses do not access out of bound locations (the subscript
788// expression of each array evaluates for each statement instance that is
789// executed to a value that is larger than zero and strictly smaller than the
790// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000791// dimension for which we do not need to assume any upper bound. At this point
792// we formalize this assumption to ensure that at code generation time the
793// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000794//
795// To find the set of constraints necessary to avoid out of bound accesses, we
796// first build the set of data locations that are not within array bounds. We
797// then apply the reverse access relation to obtain the set of iterations that
798// may contain invalid accesses and reduce this set of iterations to the ones
799// that are actually executed by intersecting them with the domain of the
800// statement. If we now project out all loop dimensions, we obtain a set of
801// parameters that may cause statement instances to be executed that may
802// possibly yield out of bound memory accesses. The complement of these
803// constraints is the set of constraints that needs to be assumed to ensure such
804// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000805void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000806 if (PollyIgnoreInbounds)
807 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000808 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000809 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000810 isl::set Outside = isl::set::empty(Space);
811 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
812 isl::local_space LS(Space);
813 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
814 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000815
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000816 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000817 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000818 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
819 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
820 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000821
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000822 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000823 }
824
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000825 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000826 Outside = Outside.intersect(Statement->getDomain());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000827 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000828
829 // Remove divs to avoid the construction of overly complicated assumptions.
830 // Doing so increases the set of parameter combinations that are assumed to
831 // not appear. This is always save, but may make the resulting run-time check
832 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000833 Outside = Outside.remove_divs();
834 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000835 const auto &Loc = getAccessInstruction()
836 ? getAccessInstruction()->getDebugLoc()
837 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000838 if (!PollyPreciseInbounds)
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000839 Outside = Outside.gist_params(Statement->getDomain().params());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000840 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000841 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000842}
843
Johannes Doerfertcea61932016-02-21 19:13:19 +0000844void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000845 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000846 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000847
Tobias Grossercdf471b2017-07-24 16:36:34 +0000848 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000849 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000850
Tobias Grosser53fc3552017-05-23 07:07:09 +0000851 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000852 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000853 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000854 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000855 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000856 LengthMap = isl::map::from_pw_aff(LengthPWA);
857 isl::space RangeSpace = LengthMap.get_space().range();
858 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000859 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000860 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
861 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
862 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
863 LengthMap = LengthMap.sum(SubscriptMap);
864 AccessRelation =
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000865 LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000866}
867
Johannes Doerferte7044942015-02-24 11:58:30 +0000868void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
869 ScalarEvolution *SE = Statement->getParent()->getSE();
870
Johannes Doerfertcea61932016-02-21 19:13:19 +0000871 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000872 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000873 return;
874
875 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000876 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
877 return;
878
879 auto *PtrSCEV = SE->getSCEV(Ptr);
880 if (isa<SCEVCouldNotCompute>(PtrSCEV))
881 return;
882
883 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
884 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
885 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
886
887 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
888 if (Range.isFullSet())
889 return;
890
Michael Kruse960c0d02017-05-18 21:55:36 +0000891 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000892 return;
893
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000894 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000895
Johannes Doerferte7044942015-02-24 11:58:30 +0000896 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000897 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000898 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000899 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000900
901 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000902 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000903
Tobias Grosserb3a85882017-02-12 08:11:12 +0000904 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
905
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000906 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000907 isl::set AccessRange = Relation.range();
908 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
909 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000910 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000911}
912
Tobias Grosser491b7992016-12-02 05:21:22 +0000913void MemoryAccess::foldAccessRelation() {
914 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
915 return;
916
Michael Krusee2bccbb2015-09-18 19:59:43 +0000917 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000918
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000919 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000920
Tobias Grosser619190d2015-03-30 17:22:28 +0000921 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000922 isl::space Space;
923 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000924 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000925
Tobias Grossera32de132017-05-23 07:22:56 +0000926 isl::space SpaceSize = DimSize.get_space();
927 isl::id ParamId =
928 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000929
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000930 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000931 Space = Space.range().map_from_set();
932 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000933
Tobias Grossera32de132017-05-23 07:22:56 +0000934 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000935
Tobias Grossera32de132017-05-23 07:22:56 +0000936 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000937 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000938 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
939 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000940
Tobias Grossera32de132017-05-23 07:22:56 +0000941 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000942 for (int j = 0; j < Size; ++j)
943 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000944 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000945
Tobias Grossera32de132017-05-23 07:22:56 +0000946 isl::local_space LS(Space);
947 isl::constraint C;
948 C = isl::constraint::alloc_equality(LS);
949 C = C.set_constant_si(-1);
950 C = C.set_coefficient_si(isl::dim::in, i, 1);
951 C = C.set_coefficient_si(isl::dim::out, i, -1);
952 MapTwo = MapTwo.add_constraint(C);
953 C = isl::constraint::alloc_equality(LS);
954 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
955 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
956 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
957 MapTwo = MapTwo.add_constraint(C);
958 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000959
Tobias Grossera32de132017-05-23 07:22:56 +0000960 MapOne = MapOne.unite(MapTwo);
961 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000962 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000963
Tobias Grosser77eef902017-07-21 23:07:56 +0000964 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000965 isl::space Space = Statement->getDomainSpace();
Tobias Grossera32de132017-05-23 07:22:56 +0000966 NewAccessRelation = NewAccessRelation.set_tuple_id(
967 isl::dim::in, Space.get_tuple_id(isl::dim::set));
968 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000969 NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000970
971 // Access dimension folding might in certain cases increase the number of
972 // disjuncts in the memory access, which can possibly complicate the generated
973 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000974 if (!PollyPreciseFoldAccesses &&
975 isl_map_n_basic_map(NewAccessRelation.get()) >
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000976 isl_map_n_basic_map(AccessRelation.get())) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000977 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000978 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000979 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000980}
981
Tobias Grosserc80d6972016-09-02 06:33:33 +0000982/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000983static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000984 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000985 if (Size == 1)
986 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000987
988 // Only one factor needs to be divisible.
989 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
990 for (auto *FactorExpr : MulExpr->operands())
991 if (isDivisible(FactorExpr, Size, SE))
992 return true;
993 return false;
994 }
995
996 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000997 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000998 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
999 for (auto *OpExpr : NAryExpr->operands())
1000 if (!isDivisible(OpExpr, Size, SE))
1001 return false;
1002 return true;
1003 }
1004
1005 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
1006 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
1007 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
1008 return MulSCEV == Expr;
1009}
1010
Michael Krusee2bccbb2015-09-18 19:59:43 +00001011void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001012 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +00001013
Johannes Doerfert85676e32016-04-23 14:32:34 +00001014 // Initialize the invalid domain which describes all iterations for which the
1015 // access relation is not modeled correctly.
Tobias Grosser2332fa32017-08-06 15:36:48 +00001016 isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001017 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +00001018
Tobias Grosserb739cb42017-07-24 20:30:34 +00001019 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001020 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +00001021
Eli Friedmanb9c6f012016-11-01 20:53:11 +00001022 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
1023 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001024 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +00001025 return;
1026 }
Johannes Doerfertcea61932016-02-21 19:13:19 +00001027
Eli Friedmanb9c6f012016-11-01 20:53:11 +00001028 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +00001029 // We overapproximate non-affine accesses with a possible access to the
1030 // whole array. For read accesses it does not make a difference, if an
1031 // access must or may happen. However, for write accesses it is important to
1032 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001033 if (AccessRelation.is_null())
1034 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001035
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001036 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +00001037 return;
1038 }
1039
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001040 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
1041 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +00001042
Michael Krusee2bccbb2015-09-18 19:59:43 +00001043 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +00001044 isl::pw_aff Affine = getPwAff(Subscripts[i]);
1045 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
1046 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001047 }
1048
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001049 Space = Statement->getDomainSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001050 AccessRelation = AccessRelation.set_tuple_id(
1051 isl::dim::in, Space.get_tuple_id(isl::dim::set));
1052 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001053
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001054 AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001055}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001056
Michael Krusecac948e2015-10-02 13:53:07 +00001057MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001058 AccessType AccType, Value *BaseAddress,
1059 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001060 ArrayRef<const SCEV *> Subscripts,
1061 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001062 MemoryKind Kind)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001063 : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(nullptr),
1064 BaseAddr(BaseAddress), ElementType(ElementType),
Tobias Grosser81331282017-05-03 07:57:35 +00001065 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1066 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001067 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001068 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001069 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001070 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001071
Tobias Grosser81331282017-05-03 07:57:35 +00001072 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001073 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001074}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001075
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001076MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001077 : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
1078 InvalidDomain(nullptr), AccessRelation(nullptr),
1079 NewAccessRelation(AccRel), FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +00001080 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001081 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1082 Sizes.push_back(nullptr);
1083 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1084 Sizes.push_back(SAI->getDimensionSize(i));
1085 ElementType = SAI->getElementType();
1086 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001087 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001088 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001089
Tobias Grosser81331282017-05-03 07:57:35 +00001090 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001091 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001092}
1093
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001094MemoryAccess::~MemoryAccess() = default;
1095
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001096void MemoryAccess::realignParams() {
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001097 isl::set Ctx = Statement->getParent()->getContext();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001098 InvalidDomain = InvalidDomain.gist_params(Ctx);
1099 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001100}
1101
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001102const std::string MemoryAccess::getReductionOperatorStr() const {
1103 return MemoryAccess::getReductionOperatorStr(getReductionType());
1104}
1105
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001106isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001107
Johannes Doerfertf6183392014-07-01 20:52:51 +00001108raw_ostream &polly::operator<<(raw_ostream &OS,
1109 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001110 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001111 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001112 else
1113 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001114 return OS;
1115}
1116
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001117void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001118
Tobias Grosser75805372011-04-29 06:27:02 +00001119void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001120 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001121 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001122 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001123 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001124 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001125 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001126 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001127 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001128 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001129 break;
1130 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001131
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001132 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001133
1134 if (FAD) {
1135 OS << "[Fortran array descriptor: " << FAD->getName();
1136 OS << "] ";
1137 };
1138
Tobias Grossera535dff2015-12-13 19:59:01 +00001139 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001140 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001141 if (hasNewAccessRelation())
1142 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001143}
1144
Michael Kruse5d518462017-07-21 15:54:07 +00001145#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001146LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001147#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001148
Tobias Grossercdf471b2017-07-24 16:36:34 +00001149isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001150 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001151 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001152 isl::set StmtDom = getStatement()->getDomain();
Tobias Grossercdf471b2017-07-24 16:36:34 +00001153 StmtDom = StmtDom.reset_tuple_id();
1154 isl::set NewInvalidDom = StmtDom.intersect(isl::manage(PWAC.second));
Tobias Grosserb739cb42017-07-24 20:30:34 +00001155 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Tobias Grossercdf471b2017-07-24 16:36:34 +00001156 return isl::manage(PWAC.first);
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001157}
1158
Tobias Grosser75805372011-04-29 06:27:02 +00001159// Create a map in the size of the provided set domain, that maps from the
1160// one element of the provided set domain to another element of the provided
1161// set domain.
1162// The mapping is limited to all points that are equal in all but the last
1163// dimension and for which the last dimension of the input is strict smaller
1164// than the last dimension of the output.
1165//
1166// getEqualAndLarger(set[i0, i1, ..., iX]):
1167//
1168// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1169// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1170//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001171static isl::map getEqualAndLarger(isl::space SetDomain) {
1172 isl::space Space = SetDomain.map_from_set();
1173 isl::map Map = isl::map::universe(Space);
1174 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001175
1176 // Set all but the last dimension to be equal for the input and output
1177 //
1178 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1179 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001180 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001181 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001182
1183 // Set the last dimension of the input to be strict smaller than the
1184 // last dimension of the output.
1185 //
1186 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001187 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001188 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001189}
1190
Tobias Grosserd7065e52017-07-24 20:50:22 +00001191isl::set MemoryAccess::getStride(isl::map Schedule) const {
1192 isl::map AccessRelation = getAccessRelation();
1193 isl::space Space = Schedule.get_space().range();
1194 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001195
Tobias Grosserd7065e52017-07-24 20:50:22 +00001196 Schedule = Schedule.reverse();
1197 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001198
Tobias Grosserd7065e52017-07-24 20:50:22 +00001199 NextScatt = NextScatt.apply_range(Schedule);
1200 NextScatt = NextScatt.apply_range(AccessRelation);
1201 NextScatt = NextScatt.apply_domain(Schedule);
1202 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001203
Tobias Grosserd7065e52017-07-24 20:50:22 +00001204 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001205 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001206}
1207
Tobias Grosserd7065e52017-07-24 20:50:22 +00001208bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1209 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001210 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001211
Sebastian Popa00a0292012-12-18 07:46:06 +00001212 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001213 StrideX = isl::set::universe(Stride.get_space());
1214 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1215 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1216 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1217 StrideWidth);
1218 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001219
Tobias Grosser28dd4862012-01-24 16:42:16 +00001220 return IsStrideX;
1221}
1222
Tobias Grosserd7065e52017-07-24 20:50:22 +00001223bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001224 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001225}
1226
Tobias Grosserd7065e52017-07-24 20:50:22 +00001227bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001228 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001229}
1230
Tobias Grosser6d588042017-08-02 19:27:16 +00001231void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1232 AccessRelation = NewAccess;
Tobias Grosserbedef002016-12-02 08:10:56 +00001233}
1234
Tobias Grosser7b45af12017-08-02 19:27:25 +00001235void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001236 assert(NewAccess);
1237
1238#ifndef NDEBUG
1239 // Check domain space compatibility.
Tobias Grosser7b45af12017-08-02 19:27:25 +00001240 isl::space NewSpace = NewAccess.get_space();
1241 isl::space NewDomainSpace = NewSpace.domain();
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001242 isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001243 assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
Michael Kruse772ce722016-09-01 19:16:58 +00001244
Michael Kruse706f79a2017-05-21 22:46:57 +00001245 // Reads must be executed unconditionally. Writes might be executed in a
1246 // subdomain only.
1247 if (isRead()) {
1248 // Check whether there is an access for every statement instance.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001249 isl::set StmtDomain = getStatement()->getDomain();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001250 StmtDomain =
1251 StmtDomain.intersect_params(getStatement()->getParent()->getContext());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001252 isl::set NewDomain = NewAccess.domain();
1253 assert(StmtDomain.is_subset(NewDomain) &&
Michael Kruse706f79a2017-05-21 22:46:57 +00001254 "Partial READ accesses not supported");
Michael Kruse706f79a2017-05-21 22:46:57 +00001255 }
Michael Kruse772ce722016-09-01 19:16:58 +00001256
Tobias Grosser7b45af12017-08-02 19:27:25 +00001257 isl::space NewAccessSpace = NewAccess.get_space();
1258 assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
Michael Kruse772ce722016-09-01 19:16:58 +00001259 "Must specify the array that is accessed");
Tobias Grosser7b45af12017-08-02 19:27:25 +00001260 isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1261 auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
Michael Kruse772ce722016-09-01 19:16:58 +00001262 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001263
1264 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1265 InvariantEquivClassTy *EqClass =
1266 getStatement()->getParent()->lookupInvariantEquivClass(
1267 SAI->getBasePtr());
1268 assert(EqClass &&
1269 "Access functions to indirect arrays must have an invariant and "
1270 "hoisted base pointer");
1271 }
1272
1273 // Check whether access dimensions correspond to number of dimensions of the
1274 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001275 auto Dims = SAI->getNumberOfDimensions();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001276 assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
Michael Kruse772ce722016-09-01 19:16:58 +00001277 "Access dims must match array dims");
Michael Kruse772ce722016-09-01 19:16:58 +00001278#endif
1279
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001280 NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001281 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001282}
Tobias Grosser75805372011-04-29 06:27:02 +00001283
Michael Kruse706f79a2017-05-21 22:46:57 +00001284bool MemoryAccess::isLatestPartialAccess() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001285 isl::set StmtDom = getStatement()->getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001286 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001287
1288 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1289}
1290
Tobias Grosser75805372011-04-29 06:27:02 +00001291//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001292
Tobias Grosser6ad16402017-08-06 17:45:28 +00001293isl::map ScopStmt::getSchedule() const {
Tobias Grosser1e09c132017-08-14 06:49:06 +00001294 isl::set Domain = getDomain();
1295 if (Domain.is_empty())
1296 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1297 auto Schedule = getParent()->getSchedule();
1298 if (!Schedule)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001299 return nullptr;
Tobias Grosser1e09c132017-08-14 06:49:06 +00001300 Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1301 if (Schedule.is_empty())
1302 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1303 isl::map M = M.from_union_map(Schedule);
1304 M = M.coalesce();
1305 M = M.gist_domain(Domain);
1306 M = M.coalesce();
1307 return M;
Tobias Grosser808cd692015-07-14 09:33:13 +00001308}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001309
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001310void ScopStmt::restrictDomain(isl::set NewDomain) {
1311 assert(NewDomain.is_subset(Domain) &&
Tobias Grosser37eb4222014-02-20 21:43:54 +00001312 "New domain is not a subset of old domain!");
Tobias Grosser37eb4222014-02-20 21:43:54 +00001313 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001314}
1315
Michael Krusecac948e2015-10-02 13:53:07 +00001316void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001317 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001318 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001319 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001320
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001321 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001322 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001323 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001324 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001325 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001326 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001327 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001328 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001329 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001330
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001331 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1332 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001333 Access->buildAccessRelation(SAI);
Michael Kruse8b805802017-07-19 17:11:25 +00001334 S.addAccessData(Access);
Tobias Grosser75805372011-04-29 06:27:02 +00001335 }
1336}
1337
Michael Kruse70af4f52017-08-07 18:40:29 +00001338void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
Michael Krusecac948e2015-10-02 13:53:07 +00001339 Instruction *AccessInst = Access->getAccessInstruction();
1340
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001341 if (Access->isArrayKind()) {
1342 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1343 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001344 } else if (Access->isValueKind() && Access->isWrite()) {
1345 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse436db622016-01-26 13:33:10 +00001346 assert(!ValueWrites.lookup(AccessVal));
1347
1348 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001349 } else if (Access->isValueKind() && Access->isRead()) {
1350 Value *AccessVal = Access->getAccessValue();
1351 assert(!ValueReads.lookup(AccessVal));
1352
1353 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001354 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001355 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001356 assert(!PHIWrites.lookup(PHI));
1357
1358 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001359 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1360 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1361 assert(!PHIReads.lookup(PHI));
1362
1363 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001364 }
1365
Michael Kruse70af4f52017-08-07 18:40:29 +00001366 if (Prepend) {
1367 MemAccs.insert(MemAccs.begin(), Access);
1368 return;
1369 }
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001370 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001371}
1372
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001373void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001374 for (MemoryAccess *MA : *this)
1375 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001376
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001377 isl::set Ctx = Parent.getContext();
Tobias Grosser2332fa32017-08-06 15:36:48 +00001378 InvalidDomain = InvalidDomain.gist_params(Ctx);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001379 Domain = Domain.gist_params(Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001380}
1381
Tobias Grosserc80d6972016-09-02 06:33:33 +00001382/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001383static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1384 void *User) {
1385 isl_set **BoundedParts = static_cast<isl_set **>(User);
1386 if (isl_basic_set_is_bounded(BSet))
1387 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1388 else
1389 isl_basic_set_free(BSet);
1390 return isl_stat_ok;
1391}
1392
Tobias Grosserc80d6972016-09-02 06:33:33 +00001393/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001394static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1395 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1396 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1397 isl_set_free(S);
1398 return BoundedParts;
1399}
1400
Tobias Grosserc80d6972016-09-02 06:33:33 +00001401/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001402///
1403/// @returns A separation of @p S into first an unbounded then a bounded subset,
1404/// both with regards to the dimension @p Dim.
1405static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1406partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001407 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001408 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001409
1410 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001411 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001412
1413 // Remove dimensions that are greater than Dim as they are not interesting.
1414 assert(NumDimsS >= Dim + 1);
1415 OnlyDimS =
1416 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1417
1418 // Create artificial parametric upper bounds for dimensions smaller than Dim
1419 // as we are not interested in them.
1420 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1421 for (unsigned u = 0; u < Dim; u++) {
1422 isl_constraint *C = isl_inequality_alloc(
1423 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1424 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1425 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1426 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1427 }
1428
1429 // Collect all bounded parts of OnlyDimS.
1430 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1431
1432 // Create the dimensions greater than Dim again.
1433 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1434 NumDimsS - Dim - 1);
1435
1436 // Remove the artificial upper bound parameters again.
1437 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1438
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001439 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001440 return std::make_pair(UnboundedParts, BoundedParts);
1441}
1442
Tobias Grosserc80d6972016-09-02 06:33:33 +00001443/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001444static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1445 __isl_take isl_set *To) {
1446 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1447 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1448 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1449 }
1450 return To;
1451}
1452
Tobias Grosserc80d6972016-09-02 06:33:33 +00001453/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001454static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001455 __isl_take isl_pw_aff *L,
1456 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001457 switch (Pred) {
1458 case ICmpInst::ICMP_EQ:
1459 return isl_pw_aff_eq_set(L, R);
1460 case ICmpInst::ICMP_NE:
1461 return isl_pw_aff_ne_set(L, R);
1462 case ICmpInst::ICMP_SLT:
1463 return isl_pw_aff_lt_set(L, R);
1464 case ICmpInst::ICMP_SLE:
1465 return isl_pw_aff_le_set(L, R);
1466 case ICmpInst::ICMP_SGT:
1467 return isl_pw_aff_gt_set(L, R);
1468 case ICmpInst::ICMP_SGE:
1469 return isl_pw_aff_ge_set(L, R);
1470 case ICmpInst::ICMP_ULT:
1471 return isl_pw_aff_lt_set(L, R);
1472 case ICmpInst::ICMP_UGT:
1473 return isl_pw_aff_gt_set(L, R);
1474 case ICmpInst::ICMP_ULE:
1475 return isl_pw_aff_le_set(L, R);
1476 case ICmpInst::ICMP_UGE:
1477 return isl_pw_aff_ge_set(L, R);
1478 default:
1479 llvm_unreachable("Non integer predicate not supported");
1480 }
1481}
1482
Tobias Grosserc80d6972016-09-02 06:33:33 +00001483/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001484///
1485/// Helper function that will make sure the dimensions of the result have the
1486/// same isl_id's as the @p Domain.
1487static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1488 __isl_take isl_pw_aff *L,
1489 __isl_take isl_pw_aff *R,
1490 __isl_keep isl_set *Domain) {
1491 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1492 return setDimensionIds(Domain, ConsequenceCondSet);
1493}
1494
Michael Kruse476f8552017-06-29 12:47:41 +00001495/// Compute the isl representation for the SCEV @p E in this BB.
1496///
1497/// @param S The Scop in which @p BB resides in.
1498/// @param BB The BB for which isl representation is to be
1499/// computed.
1500/// @param InvalidDomainMap A map of BB to their invalid domains.
1501/// @param E The SCEV that should be translated.
1502/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1503///
1504/// Note that this function will also adjust the invalid context accordingly.
1505
1506__isl_give isl_pw_aff *
1507getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001508 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1509 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001510 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001511 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001512 return PWAC.first;
1513}
1514
Tobias Grosserc80d6972016-09-02 06:33:33 +00001515/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001516///
1517/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001518/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1519/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001520static bool
1521buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1522 __isl_keep isl_set *Domain,
1523 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1524 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001525 Value *Condition = getConditionFromTerminator(SI);
1526 assert(Condition && "No condition for switch");
1527
1528 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001529 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001530 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001531
1532 unsigned NumSuccessors = SI->getNumSuccessors();
1533 ConditionSets.resize(NumSuccessors);
1534 for (auto &Case : SI->cases()) {
1535 unsigned Idx = Case.getSuccessorIndex();
1536 ConstantInt *CaseValue = Case.getCaseValue();
1537
Michael Kruse476f8552017-06-29 12:47:41 +00001538 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001539 isl_set *CaseConditionSet =
1540 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1541 ConditionSets[Idx] = isl_set_coalesce(
1542 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1543 }
1544
1545 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1546 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1547 for (unsigned u = 2; u < NumSuccessors; u++)
1548 ConditionSetUnion =
1549 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1550 ConditionSets[0] = setDimensionIds(
1551 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1552
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001553 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001554
1555 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001556}
1557
Michael Kruse08655852017-07-20 12:37:02 +00001558/// Build condition sets for unsigned ICmpInst(s).
1559/// Special handling is required for unsigned operands to ensure that if
1560/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1561/// it should wrap around.
1562///
1563/// @param IsStrictUpperBound holds information on the predicate relation
1564/// between TestVal and UpperBound, i.e,
1565/// TestVal < UpperBound OR TestVal <= UpperBound
1566static __isl_give isl_set *
1567buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1568 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1569 const SCEV *SCEV_UpperBound,
1570 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1571 bool IsStrictUpperBound) {
Michael Kruse08655852017-07-20 12:37:02 +00001572 // Do not take NonNeg assumption on TestVal
1573 // as it might have MSB (Sign bit) set.
1574 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1575 // Take NonNeg assumption on UpperBound.
1576 isl_pw_aff *UpperBound =
1577 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1578
1579 // 0 <= TestVal
1580 isl_set *First =
1581 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1582 isl_pw_aff_get_domain_space(TestVal))),
1583 isl_pw_aff_copy(TestVal));
1584
1585 isl_set *Second;
1586 if (IsStrictUpperBound)
1587 // TestVal < UpperBound
1588 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1589 else
1590 // TestVal <= UpperBound
1591 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1592
1593 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1594 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1595 return ConsequenceCondSet;
1596}
1597
Tobias Grosserc80d6972016-09-02 06:33:33 +00001598/// Build the conditions sets for the branch condition @p Condition in
1599/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001600///
1601/// This will fill @p ConditionSets with the conditions under which control
1602/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001603/// have as many elements as @p TI has successors. If @p TI is nullptr the
1604/// context under which @p Condition is true/false will be returned as the
1605/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001606static bool
1607buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1608 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1609 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1610 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001611 isl_set *ConsequenceCondSet = nullptr;
1612 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1613 if (CCond->isZero())
1614 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1615 else
1616 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1617 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1618 auto Opcode = BinOp->getOpcode();
1619 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1620
Michael Kruse476f8552017-06-29 12:47:41 +00001621 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1622 InvalidDomainMap, ConditionSets) &&
1623 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1624 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001625 if (!Valid) {
1626 while (!ConditionSets.empty())
1627 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001628 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001629 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001630
1631 isl_set_free(ConditionSets.pop_back_val());
1632 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1633 isl_set_free(ConditionSets.pop_back_val());
1634 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1635
1636 if (Opcode == Instruction::And)
1637 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1638 else
1639 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1640 } else {
1641 auto *ICond = dyn_cast<ICmpInst>(Condition);
1642 assert(ICond &&
1643 "Condition of exiting branch was neither constant nor ICmp!");
1644
1645 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001646 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001647 // For unsigned comparisons we assumed the signed bit of neither operand
1648 // to be set. The comparison is equal to a signed comparison under this
1649 // assumption.
1650 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001651 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1652 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1653
1654 switch (ICond->getPredicate()) {
1655 case ICmpInst::ICMP_ULT:
1656 ConsequenceCondSet =
1657 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1658 RightOperand, InvalidDomainMap, true);
1659 break;
1660 case ICmpInst::ICMP_ULE:
1661 ConsequenceCondSet =
1662 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1663 RightOperand, InvalidDomainMap, false);
1664 break;
1665 case ICmpInst::ICMP_UGT:
1666 ConsequenceCondSet =
1667 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1668 LeftOperand, InvalidDomainMap, true);
1669 break;
1670 case ICmpInst::ICMP_UGE:
1671 ConsequenceCondSet =
1672 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1673 LeftOperand, InvalidDomainMap, false);
1674 break;
1675 default:
1676 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1677 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1678 ConsequenceCondSet =
1679 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1680 break;
1681 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001682 }
1683
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001684 // If no terminator was given we are only looking for parameter constraints
1685 // under which @p Condition is true/false.
1686 if (!TI)
1687 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001688 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001689 ConsequenceCondSet = isl_set_coalesce(
1690 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001691
Johannes Doerfertb2885792016-04-26 09:20:41 +00001692 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001693 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001694 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001695
Michael Krusef7a4a942016-05-02 12:25:36 +00001696 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001697 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1698 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001699 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001700 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001701 }
1702
Michael Krusef7a4a942016-05-02 12:25:36 +00001703 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001704 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1705 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001706 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001707 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001708 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001709 }
1710
1711 ConditionSets.push_back(ConsequenceCondSet);
1712 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001713
1714 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001715}
1716
Tobias Grosserc80d6972016-09-02 06:33:33 +00001717/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001718///
1719/// This will fill @p ConditionSets with the conditions under which control
1720/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1721/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001722static bool
1723buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1724 __isl_keep isl_set *Domain,
1725 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1726 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001727 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001728 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1729 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001730
1731 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1732
1733 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001734 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001735 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001736 }
1737
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001738 Value *Condition = getConditionFromTerminator(TI);
1739 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001740
Michael Kruse476f8552017-06-29 12:47:41 +00001741 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1742 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001743}
1744
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001745void ScopStmt::buildDomain() {
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001746 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001747
Tobias Grosser61bd3a42017-08-06 21:42:38 +00001748 Domain = getParent()->getDomainConditions(this);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001749 Domain = Domain.set_tuple_id(Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001750}
1751
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001752void ScopStmt::collectSurroundingLoops() {
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001753 for (unsigned u = 0, e = Domain.dim(isl::dim::set); u < e; u++) {
1754 isl::id DimId = Domain.get_dim_id(isl::dim::set, u);
1755 NestLoops.push_back(static_cast<Loop *>(DimId.get_user()));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001756 }
1757}
1758
Michael Kruse55454072017-03-15 22:16:43 +00001759ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001760 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), R(&R),
1761 Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001762 BaseName = getIslCompatibleName(
1763 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001764}
1765
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001766ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
Michael Kruse59125512017-08-30 10:11:06 +00001767 std::vector<Instruction *> Instructions, int Count)
Johannes Doerferta3519512016-04-23 13:02:23 +00001768 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001769 Build(nullptr), SurroundingLoop(SurroundingLoop),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001770 Instructions(Instructions) {
Michael Kruse59125512017-08-30 10:11:06 +00001771 std::string S = "";
1772 if (Count != 0)
1773 S += std::to_string(Count);
1774 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), S,
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001775 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001776}
1777
Tobias Grosser85048ef2017-08-06 17:24:59 +00001778ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1779 isl::set NewDomain)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001780 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain),
1781 Build(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001782 BaseName = getIslCompatibleName("CopyStmt_", "",
1783 std::to_string(parent.getCopyStmtsNum()));
Tobias Grosser85048ef2017-08-06 17:24:59 +00001784 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1785 Domain = Domain.set_tuple_id(Id);
1786 TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1787 auto *Access =
1788 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001789 parent.addAccessFunction(Access);
1790 addAccess(Access);
Tobias Grosser85048ef2017-08-06 17:24:59 +00001791 SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1792 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001793 parent.addAccessFunction(Access);
1794 addAccess(Access);
1795}
1796
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001797ScopStmt::~ScopStmt() = default;
1798
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001799void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001800 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001801
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001802 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001803 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001804 buildAccessRelations();
1805
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001806 if (DetectReductions)
1807 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001808}
1809
Tobias Grosserc80d6972016-09-02 06:33:33 +00001810/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001811///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001812/// Check if the stored value for @p StoreMA is a binary operator with one or
1813/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001814/// used only once (by @p StoreMA) and its load operands are also used only
1815/// once, we have found a possible reduction chain. It starts at an operand
1816/// load and includes the binary operator and @p StoreMA.
1817///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001818/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001819/// escape this block or into any other store except @p StoreMA.
1820void ScopStmt::collectCandiateReductionLoads(
1821 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1822 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1823 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001824 return;
1825
1826 // Skip if there is not one binary operator between the load and the store
1827 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001828 if (!BinOp)
1829 return;
1830
1831 // Skip if the binary operators has multiple uses
1832 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001833 return;
1834
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001835 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001836 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1837 return;
1838
Johannes Doerfert9890a052014-07-01 00:32:29 +00001839 // Skip if the binary operator is outside the current SCoP
1840 if (BinOp->getParent() != Store->getParent())
1841 return;
1842
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001843 // Skip if it is a multiplicative reduction and we disabled them
1844 if (DisableMultiplicativeReductions &&
1845 (BinOp->getOpcode() == Instruction::Mul ||
1846 BinOp->getOpcode() == Instruction::FMul))
1847 return;
1848
Johannes Doerferte58a0122014-06-27 20:31:28 +00001849 // Check the binary operator operands for a candidate load
1850 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1851 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1852 if (!PossibleLoad0 && !PossibleLoad1)
1853 return;
1854
1855 // A load is only a candidate if it cannot escape (thus has only this use)
1856 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001857 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001858 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001859 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001860 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001861 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001862}
1863
Tobias Grosserc80d6972016-09-02 06:33:33 +00001864/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001865///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001866/// Iterate over all store memory accesses and check for valid binary reduction
1867/// like chains. For all candidates we check if they have the same base address
1868/// and there are no other accesses which overlap with them. The base address
1869/// check rules out impossible reductions candidates early. The overlap check,
1870/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001871/// guarantees that none of the intermediate results will escape during
1872/// execution of the loop nest. We basically check here that no other memory
1873/// access can access the same memory as the potential reduction.
1874void ScopStmt::checkForReductions() {
1875 SmallVector<MemoryAccess *, 2> Loads;
1876 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1877
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001878 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001879 // stores and collecting possible reduction loads.
1880 for (MemoryAccess *StoreMA : MemAccs) {
1881 if (StoreMA->isRead())
1882 continue;
1883
1884 Loads.clear();
1885 collectCandiateReductionLoads(StoreMA, Loads);
1886 for (MemoryAccess *LoadMA : Loads)
1887 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1888 }
1889
1890 // Then check each possible candidate pair.
1891 for (const auto &CandidatePair : Candidates) {
1892 bool Valid = true;
Tobias Grosserb8417532017-08-15 03:45:55 +00001893 isl::map LoadAccs = CandidatePair.first->getAccessRelation();
1894 isl::map StoreAccs = CandidatePair.second->getAccessRelation();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001895
1896 // Skip those with obviously unequal base addresses.
Tobias Grosserb8417532017-08-15 03:45:55 +00001897 if (!LoadAccs.has_equal_space(StoreAccs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001898 continue;
1899 }
1900
1901 // And check if the remaining for overlap with other memory accesses.
Tobias Grosserb8417532017-08-15 03:45:55 +00001902 isl::map AllAccsRel = LoadAccs.unite(StoreAccs);
1903 AllAccsRel = AllAccsRel.intersect_domain(getDomain());
1904 isl::set AllAccs = AllAccsRel.range();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001905
1906 for (MemoryAccess *MA : MemAccs) {
1907 if (MA == CandidatePair.first || MA == CandidatePair.second)
1908 continue;
1909
Tobias Grosserb8417532017-08-15 03:45:55 +00001910 isl::map AccRel = MA->getAccessRelation().intersect_domain(getDomain());
1911 isl::set Accs = AccRel.range();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001912
Tobias Grosserb8417532017-08-15 03:45:55 +00001913 if (AllAccs.has_equal_space(Accs)) {
1914 isl::set OverlapAccs = Accs.intersect(AllAccs);
1915 Valid = Valid && OverlapAccs.is_empty();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001916 }
1917 }
1918
Johannes Doerferte58a0122014-06-27 20:31:28 +00001919 if (!Valid)
1920 continue;
1921
Johannes Doerfertf6183392014-07-01 20:52:51 +00001922 const LoadInst *Load =
1923 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1924 MemoryAccess::ReductionType RT =
1925 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1926
Johannes Doerferte58a0122014-06-27 20:31:28 +00001927 // If no overlapping access was found we mark the load and store as
1928 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001929 CandidatePair.first->markAsReductionLike(RT);
1930 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001931 }
Tobias Grosser75805372011-04-29 06:27:02 +00001932}
1933
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001934std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001935
Tobias Grosser54839312015-04-21 11:37:25 +00001936std::string ScopStmt::getScheduleStr() const {
Tobias Grosser6ad16402017-08-06 17:45:28 +00001937 auto *S = getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001938 if (!S)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001939 return {};
Tobias Grosser808cd692015-07-14 09:33:13 +00001940 auto Str = stringFromIslObj(S);
1941 isl_map_free(S);
1942 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001943}
1944
Tobias Grosser2332fa32017-08-06 15:36:48 +00001945void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
Johannes Doerfert7c013572016-04-12 09:57:34 +00001946
Michael Kruse375cb5f2016-02-24 22:08:24 +00001947BasicBlock *ScopStmt::getEntryBlock() const {
1948 if (isBlockStmt())
1949 return getBasicBlock();
1950 return getRegion()->getEntry();
1951}
1952
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001953unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001954
Tobias Grosser75805372011-04-29 06:27:02 +00001955const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1956
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001957Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001958 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001959}
1960
Tobias Grosser74394f02013-01-14 22:40:23 +00001961isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001962
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001963isl::set ScopStmt::getDomain() const { return Domain; }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001964
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001965isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001966
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001967isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001968
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001969void ScopStmt::printInstructions(raw_ostream &OS) const {
1970 OS << "Instructions {\n";
1971
1972 for (Instruction *Inst : Instructions)
1973 OS.indent(16) << *Inst << "\n";
1974
Michael Krusee52ebd12017-07-22 16:44:39 +00001975 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001976}
1977
Michael Krusecd4c9772017-07-21 15:35:53 +00001978void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001979 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001980 OS.indent(12) << "Domain :=\n";
1981
1982 if (Domain) {
1983 OS.indent(16) << getDomainStr() << ";\n";
1984 } else
1985 OS.indent(16) << "n/a\n";
1986
Tobias Grosser54839312015-04-21 11:37:25 +00001987 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001988
1989 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001990 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001991 } else
1992 OS.indent(16) << "n/a\n";
1993
Tobias Grosser083d3d32014-06-28 08:59:45 +00001994 for (MemoryAccess *Access : MemAccs)
1995 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001996
Michael Kruseeca86ce2017-07-26 22:01:33 +00001997 if (PrintInstructions && isBlockStmt())
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001998 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001999}
2000
Michael Kruse5d518462017-07-21 15:54:07 +00002001#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00002002LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00002003#endif
Tobias Grosser75805372011-04-29 06:27:02 +00002004
Michael Krusee60eca72017-05-11 22:56:12 +00002005void ScopStmt::removeAccessData(MemoryAccess *MA) {
2006 if (MA->isRead() && MA->isOriginalValueKind()) {
2007 bool Found = ValueReads.erase(MA->getAccessValue());
2008 (void)Found;
2009 assert(Found && "Expected access data not found");
2010 }
2011 if (MA->isWrite() && MA->isOriginalValueKind()) {
2012 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
2013 (void)Found;
2014 assert(Found && "Expected access data not found");
2015 }
2016 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
2017 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
2018 (void)Found;
2019 assert(Found && "Expected access data not found");
2020 }
Michael Kruse3562f272017-07-20 16:47:57 +00002021 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
2022 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
2023 (void)Found;
2024 assert(Found && "Expected access data not found");
2025 }
Michael Krusee60eca72017-05-11 22:56:12 +00002026}
2027
Michael Kruse10071822016-05-23 14:45:58 +00002028void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00002029 // Remove the memory accesses from this statement together with all scalar
2030 // accesses that were caused by it. MemoryKind::Value READs have no access
2031 // instruction, hence would not be removed by this function. However, it is
2032 // only used for invariant LoadInst accesses, its arguments are always affine,
2033 // hence synthesizable, and therefore there are no MemoryKind::Value READ
2034 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00002035 auto Predicate = [&](MemoryAccess *Acc) {
2036 return Acc->getAccessInstruction() == MA->getAccessInstruction();
2037 };
Michael Krusee60eca72017-05-11 22:56:12 +00002038 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00002039 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00002040 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002041 Parent.removeAccessData(MA);
2042 }
Michael Krusee60eca72017-05-11 22:56:12 +00002043 }
Michael Kruse10071822016-05-23 14:45:58 +00002044 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
2045 MemAccs.end());
2046 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002047}
2048
Michael Kruse0446d812017-03-10 16:05:24 +00002049void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
2050 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
2051 assert(MAIt != MemAccs.end());
2052 MemAccs.erase(MAIt);
2053
Michael Krusee60eca72017-05-11 22:56:12 +00002054 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002055 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00002056
Michael Kruse0446d812017-03-10 16:05:24 +00002057 auto It = InstructionToAccess.find(MA->getAccessInstruction());
2058 if (It != InstructionToAccess.end()) {
2059 It->second.remove(MA);
2060 if (It->second.empty())
2061 InstructionToAccess.erase(MA->getAccessInstruction());
2062 }
2063}
2064
Michael Kruse07e8c362017-07-24 12:43:27 +00002065MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
2066 MemoryAccess *Access = lookupInputAccessOf(V);
2067 if (Access)
2068 return Access;
2069
2070 ScopArrayInfo *SAI =
2071 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
2072 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
2073 true, {}, {}, V, MemoryKind::Value);
2074 Parent.addAccessFunction(Access);
2075 Access->buildAccessRelation(SAI);
2076 addAccess(Access);
2077 Parent.addAccessData(Access);
2078 return Access;
2079}
2080
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002081raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
2082 S.print(OS, PollyPrintInstructions);
2083 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00002084}
2085
Tobias Grosser75805372011-04-29 06:27:02 +00002086//===----------------------------------------------------------------------===//
2087/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00002088
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00002089void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00002090 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
2091 isl_set_free(Context);
2092 Context = NewContext;
2093}
2094
Eli Friedman5e589ea2017-06-20 22:53:02 +00002095namespace {
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002096
Tobias Grosserc80d6972016-09-02 06:33:33 +00002097/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002098struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002099 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002100 const ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002101
2102public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00002103 SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
2104 ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002105 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002106
2107 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002108 const ValueToValueMap &VMap) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002109 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2110 return SSPR.visit(E);
2111 }
2112
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002113 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2114 auto *Start = visit(E->getStart());
2115 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2116 visit(E->getStepRecurrence(SE)),
2117 E->getLoop(), SCEV::FlagAnyWrap);
2118 return SE.getAddExpr(Start, AddRec);
2119 }
2120
2121 const SCEV *visitUnknown(const SCEVUnknown *E) {
2122 if (auto *NewValue = VMap.lookup(E->getValue()))
2123 return SE.getUnknown(NewValue);
2124 return E;
2125 }
2126};
2127
Eli Friedman5e589ea2017-06-20 22:53:02 +00002128/// Check whether we should remap a SCEV expression.
2129struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002130 const ValueToValueMap &VMap;
Eli Friedman5e589ea2017-06-20 22:53:02 +00002131 bool FoundInside = false;
Tobias Grosserb5563c62017-08-03 13:51:15 +00002132 const Scop *S;
Eli Friedman5e589ea2017-06-20 22:53:02 +00002133
2134public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00002135 SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
2136 const Scop *S)
Eli Friedman5e589ea2017-06-20 22:53:02 +00002137 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2138
2139 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002140 const ValueToValueMap &VMap, const Scop *S) {
Eli Friedman5e589ea2017-06-20 22:53:02 +00002141 SCEVFindInsideScop SFIS(VMap, SE, S);
2142 SFIS.visitAll(E);
2143 return SFIS.FoundInside;
2144 }
2145
2146 bool follow(const SCEV *E) {
2147 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2148 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2149 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2150 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2151 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2152 }
2153 return !FoundInside;
2154 }
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002155
Eli Friedman5e589ea2017-06-20 22:53:02 +00002156 bool isDone() { return FoundInside; }
2157};
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002158
2159} // end anonymous namespace
Eli Friedman5e589ea2017-06-20 22:53:02 +00002160
Tobias Grosserb5563c62017-08-03 13:51:15 +00002161const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
Eli Friedman5e589ea2017-06-20 22:53:02 +00002162 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2163 // doesn't like addition between an AddRec and an expression that
2164 // doesn't have a dominance relationship with it.)
2165 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2166 return E;
2167
2168 // Rewrite SCEV.
2169 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002170}
2171
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002172// This table of function names is used to translate parameter names in more
2173// human-readable names. This makes it easier to interpret Polly analysis
2174// results.
2175StringMap<std::string> KnownNames = {
2176 {"_Z13get_global_idj", "global_id"},
2177 {"_Z12get_local_idj", "local_id"},
2178 {"_Z15get_global_sizej", "global_size"},
2179 {"_Z14get_local_sizej", "local_size"},
2180 {"_Z12get_work_dimv", "work_dim"},
2181 {"_Z17get_global_offsetj", "global_offset"},
2182 {"_Z12get_group_idj", "group_id"},
2183 {"_Z14get_num_groupsj", "num_groups"},
2184};
2185
2186static std::string getCallParamName(CallInst *Call) {
2187 std::string Result;
2188 raw_string_ostream OS(Result);
2189 std::string Name = Call->getCalledFunction()->getName();
2190
2191 auto Iterator = KnownNames.find(Name);
2192 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002193 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002194 OS << Name;
2195 for (auto &Operand : Call->arg_operands()) {
2196 ConstantInt *Op = cast<ConstantInt>(&Operand);
2197 OS << "_" << Op->getValue();
2198 }
2199 OS.flush();
2200 return Result;
2201}
2202
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002203void Scop::createParameterId(const SCEV *Parameter) {
2204 assert(Parameters.count(Parameter));
2205 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002206
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002207 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002208
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002209 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2210 Value *Val = ValueParameter->getValue();
2211 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002212
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002213 if (Call && isConstCall(Call)) {
2214 ParameterName = getCallParamName(Call);
2215 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002216 // If this parameter references a specific Value and this value has a name
2217 // we use this name as it is likely to be unique and more useful than just
2218 // a number.
2219 if (Val->hasName())
2220 ParameterName = Val->getName();
2221 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2222 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2223 if (LoadOrigin->hasName()) {
2224 ParameterName += "_loaded_from_";
2225 ParameterName +=
2226 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2227 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002228 }
2229 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002230
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002231 ParameterName = getIslCompatibleName("", ParameterName, "");
2232 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002233
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002234 isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002235 const_cast<void *>((const void *)Parameter));
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002236 ParameterIds[Parameter] = Id;
2237}
2238
2239void Scop::addParams(const ParameterSetTy &NewParameters) {
2240 for (const SCEV *Parameter : NewParameters) {
2241 // Normalize the SCEV to get the representing element for an invariant load.
2242 Parameter = extractConstantFactor(Parameter, *SE).second;
2243 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2244
2245 if (Parameters.insert(Parameter))
2246 createParameterId(Parameter);
2247 }
2248}
2249
Tobias Grosser9a635702017-08-06 19:31:27 +00002250isl::id Scop::getIdForParam(const SCEV *Parameter) const {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002251 // Normalize the SCEV to get the representing element for an invariant load.
2252 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002253 return ParameterIds.lookup(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00002254}
Tobias Grosser75805372011-04-29 06:27:02 +00002255
Tobias Grosser232fdad2017-08-06 20:19:26 +00002256isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002257 isl_set *DomainContext = isl_union_set_params(getDomains().release());
Tobias Grosser232fdad2017-08-06 20:19:26 +00002258 return isl::manage(isl_set_intersect_params(C.release(), DomainContext));
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002259}
2260
Johannes Doerferte0b08072016-05-23 12:43:44 +00002261bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2262 return DT.dominates(BB, getEntry());
2263}
2264
Michael Kruse476f8552017-06-29 12:47:41 +00002265void Scop::addUserAssumptions(
2266 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002267 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002268 for (auto &Assumption : AC.assumptions()) {
2269 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2270 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002271 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002272
Michael Kruse89b1f942017-03-17 13:56:53 +00002273 bool InScop = contains(CI);
2274 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2275 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002276
Michael Kruse89b1f942017-03-17 13:56:53 +00002277 auto *L = LI.getLoopFor(CI->getParent());
2278 auto *Val = CI->getArgOperand(0);
2279 ParameterSetTy DetectedParams;
2280 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002281 ORE.emit(
2282 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2283 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002284 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002285 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002286
2287 // Collect all newly introduced parameters.
2288 ParameterSetTy NewParams;
2289 for (auto *Param : DetectedParams) {
2290 Param = extractConstantFactor(Param, *SE).second;
2291 Param = getRepresentingInvariantLoadSCEV(Param);
2292 if (Parameters.count(Param))
2293 continue;
2294 NewParams.insert(Param);
2295 }
2296
2297 SmallVector<isl_set *, 2> ConditionSets;
2298 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
Michael Kruse1df1aac2017-07-26 13:25:28 +00002299 BasicBlock *BB = InScop ? CI->getParent() : getRegion().getEntry();
2300 auto *Dom = InScop ? DomainMap[BB].copy() : isl_set_copy(Context);
2301 assert(Dom && "Cannot propagate a nullptr.");
2302 bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2303 InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002304 isl_set_free(Dom);
2305
2306 if (!Valid)
2307 continue;
2308
2309 isl_set *AssumptionCtx = nullptr;
2310 if (InScop) {
2311 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2312 isl_set_free(ConditionSets[0]);
2313 } else {
2314 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2315 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2316 }
2317
2318 // Project out newly introduced parameters as they are not otherwise useful.
2319 if (!NewParams.empty()) {
2320 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2321 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2322 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2323 isl_id_free(Id);
2324
2325 if (!NewParams.count(Param))
2326 continue;
2327
2328 AssumptionCtx =
2329 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2330 }
2331 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002332 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2333 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002334 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002335 }
2336}
2337
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002338void Scop::addUserContext() {
2339 if (UserContextStr.empty())
2340 return;
2341
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002342 isl_set *UserContext =
2343 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002344 isl_space *Space = getParamSpace().release();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002345 if (isl_space_dim(Space, isl_dim_param) !=
2346 isl_set_dim(UserContext, isl_dim_param)) {
2347 auto SpaceStr = isl_space_to_str(Space);
2348 errs() << "Error: the context provided in -polly-context has not the same "
2349 << "number of dimensions than the computed context. Due to this "
2350 << "mismatch, the -polly-context option is ignored. Please provide "
2351 << "the context in the parameter space: " << SpaceStr << ".\n";
2352 free(SpaceStr);
2353 isl_set_free(UserContext);
2354 isl_space_free(Space);
2355 return;
2356 }
2357
2358 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002359 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2360 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002361
2362 if (strcmp(NameContext, NameUserContext) != 0) {
2363 auto SpaceStr = isl_space_to_str(Space);
2364 errs() << "Error: the name of dimension " << i
2365 << " provided in -polly-context "
2366 << "is '" << NameUserContext << "', but the name in the computed "
2367 << "context is '" << NameContext
2368 << "'. Due to this name mismatch, "
2369 << "the -polly-context option is ignored. Please provide "
2370 << "the context in the parameter space: " << SpaceStr << ".\n";
2371 free(SpaceStr);
2372 isl_set_free(UserContext);
2373 isl_space_free(Space);
2374 return;
2375 }
2376
2377 UserContext =
2378 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2379 isl_space_get_dim_id(Space, isl_dim_param, i));
2380 }
2381
2382 Context = isl_set_intersect(Context, UserContext);
2383 isl_space_free(Space);
2384}
2385
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002386void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002387 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002388
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002389 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002390 for (LoadInst *LInst : RIL) {
2391 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2392
Johannes Doerfert96e54712016-02-07 17:30:13 +00002393 Type *Ty = LInst->getType();
2394 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002395 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002396 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002397 continue;
2398 }
2399
2400 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002401 InvariantEquivClasses.emplace_back(
2402 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002403 }
2404}
2405
Tobias Grosser6be480c2011-11-08 15:41:13 +00002406void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002407 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002408 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002409 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002410 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002411}
2412
Tobias Grosser18daaca2012-05-22 10:47:27 +00002413void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002414 unsigned PDim = 0;
2415 for (auto *Parameter : Parameters) {
2416 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002417 Context =
2418 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2419 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002420 }
2421}
2422
Tobias Grosserb5563c62017-08-03 13:51:15 +00002423static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
2424 std::vector<isl::id> OutermostSizeIds;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002425 for (auto Array : Arrays) {
2426 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2427 // for its outermost dimension. Fortran arrays will have this since the
2428 // outermost dimension size can be picked up from their runtime description.
2429 // TODO: actually need to check if it has a FAD, but for now this works.
2430 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002431 isl::pw_aff PwAff = Array->getDimensionSizePw(0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002432 if (!PwAff)
2433 continue;
2434
Tobias Grosserb5563c62017-08-03 13:51:15 +00002435 isl::id Id =
2436 isl::manage(isl_pw_aff_get_dim_id(PwAff.get(), isl_dim_param, 0));
2437 assert(!Id.is_null() &&
2438 "Invalid Id for PwAff expression in Fortran array");
2439 Id.dump();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002440 OutermostSizeIds.push_back(Id);
2441 }
2442 }
Tobias Grosserb5563c62017-08-03 13:51:15 +00002443 return OutermostSizeIds;
2444}
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002445
Tobias Grosserb5563c62017-08-03 13:51:15 +00002446// The FORTRAN array size parameters are known to be non-negative.
2447static isl_set *boundFortranArrayParams(__isl_give isl_set *Context,
2448 Scop::array_range Arrays) {
2449 std::vector<isl::id> OutermostSizeIds;
2450 OutermostSizeIds = getFortranArrayIds(Arrays);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002451
Tobias Grosserb5563c62017-08-03 13:51:15 +00002452 for (isl::id Id : OutermostSizeIds) {
2453 int dim = isl_set_find_dim_by_id(Context, isl_dim_param, Id.get());
2454 Context = isl_set_lower_bound_si(Context, isl_dim_param, dim, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002455 }
2456
2457 return Context;
2458}
2459
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002460void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002461 if (PollyIgnoreParamBounds)
2462 return;
2463
Tobias Grosser6be480c2011-11-08 15:41:13 +00002464 // Add all parameters into a common model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002465 isl::space Space = getFullParamSpace();
Tobias Grosser6be480c2011-11-08 15:41:13 +00002466
2467 // Align the parameters of all data structures to the model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002468 Context = isl_set_align_params(Context, Space.copy());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002469
Tobias Grosserb5563c62017-08-03 13:51:15 +00002470 // Bound the size of the fortran array dimensions.
2471 Context = boundFortranArrayParams(Context, arrays());
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002472
Johannes Doerferta60ad842016-05-10 12:18:22 +00002473 // As all parameters are known add bounds to them.
2474 addParameterBounds();
2475
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002476 for (ScopStmt &Stmt : *this)
2477 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002478 // Simplify the schedule according to the context too.
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00002479 Schedule = isl_schedule_gist_domain_params(Schedule, getContext().release());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002480}
2481
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002482static __isl_give isl_set *
2483simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2484 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002485 // If we have modeled all blocks in the SCoP that have side effects we can
2486 // simplify the context with the constraints that are needed for anything to
2487 // be executed at all. However, if we have error blocks in the SCoP we already
2488 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002489 // domains, thus we cannot use the remaining domain to simplify the
2490 // assumptions.
2491 if (!S.hasErrorBlock()) {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002492 isl_set *DomainParameters = isl_union_set_params(S.getDomains().release());
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002493 AssumptionContext =
2494 isl_set_gist_params(AssumptionContext, DomainParameters);
2495 }
2496
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002497 AssumptionContext =
2498 isl_set_gist_params(AssumptionContext, S.getContext().release());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002499 return AssumptionContext;
2500}
2501
2502void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002503 // The parameter constraints of the iteration domains give us a set of
2504 // constraints that need to hold for all cases where at least a single
2505 // statement iteration is executed in the whole scop. We now simplify the
2506 // assumed context under the assumption that such constraints hold and at
2507 // least a single statement iteration is executed. For cases where no
2508 // statement instances are executed, the assumptions we have taken about
2509 // the executed code do not matter and can be changed.
2510 //
2511 // WARNING: This only holds if the assumptions we have taken do not reduce
2512 // the set of statement instances that are executed. Otherwise we
2513 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002514 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002515 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002516 // performed. In such a case, modifying the run-time conditions and
2517 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002518 // to not be executed.
2519 //
2520 // Example:
2521 //
2522 // When delinearizing the following code:
2523 //
2524 // for (long i = 0; i < 100; i++)
2525 // for (long j = 0; j < m; j++)
2526 // A[i+p][j] = 1.0;
2527 //
2528 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002529 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002530 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002531 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002532 InvalidContext =
2533 isl_set_align_params(InvalidContext, getParamSpace().release());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002534}
2535
Tobias Grosserc80d6972016-09-02 06:33:33 +00002536/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002537static isl::stat
2538buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2539 isl::pw_multi_aff MinPMA, MaxPMA;
2540 isl::pw_aff LastDimAff;
2541 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002542 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002543 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002544
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002545 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002546
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002547 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2548 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002549
Johannes Doerfert9143d672014-09-27 11:02:39 +00002550 // Restrict the number of parameters involved in the access as the lexmin/
2551 // lexmax computation will take too long if this number is high.
2552 //
2553 // Experiments with a simple test case using an i7 4800MQ:
2554 //
2555 // #Parameters involved | Time (in sec)
2556 // 6 | 0.01
2557 // 7 | 0.04
2558 // 8 | 0.12
2559 // 9 | 0.40
2560 // 10 | 1.54
2561 // 11 | 6.78
2562 // 12 | 30.38
2563 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002564 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002565 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002566 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2567 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002568 InvolvedParams++;
2569
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002570 if (InvolvedParams > RunTimeChecksMaxParameters)
2571 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002572 }
2573
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002574 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2575 return isl::stat::error;
2576
Tobias Grosser57a1d362017-06-23 08:05:27 +00002577 MinPMA = Set.lexmin_pw_multi_aff();
2578 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002579
Tobias Grosser57a1d362017-06-23 08:05:27 +00002580 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002581 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002582
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002583 MinPMA = MinPMA.coalesce();
2584 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002585
Johannes Doerfertb164c792014-09-18 11:17:17 +00002586 // Adjust the last dimension of the maximal access by one as we want to
2587 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2588 // we test during code generation might now point after the end of the
2589 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002590 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2591 Pos = MaxPMA.dim(isl::dim::out) - 1;
2592 LastDimAff = MaxPMA.get_pw_aff(Pos);
2593 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2594 OneAff = OneAff.add_constant_si(1);
2595 LastDimAff = LastDimAff.add(OneAff);
2596 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002597
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002598 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002599
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002600 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002601}
2602
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002603static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00002604 isl_set *Domain = MA->getStatement()->getDomain().release();
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002605 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2606 return isl_set_reset_tuple_id(Domain);
2607}
2608
Tobias Grosserc80d6972016-09-02 06:33:33 +00002609/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002610static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002611 Scop::MinMaxVectorTy &MinMaxAccesses) {
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002612 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002613
Tobias Grosser31df6f32017-08-06 21:42:25 +00002614 isl::union_set Domains = S.getDomains();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002615 isl::union_map Accesses = isl::union_map::empty(S.getParamSpace());
Tobias Grossere9522232017-01-16 15:49:04 +00002616
2617 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser1515f6b2017-07-23 04:08:38 +00002618 Accesses = Accesses.add_map(give(MA->getAccessRelation().release()));
Tobias Grossere9522232017-01-16 15:49:04 +00002619
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002620 Accesses = Accesses.intersect_domain(Domains);
2621 isl::union_set Locations = Accesses.range();
2622 Locations = Locations.coalesce();
2623 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002624
2625 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2626 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2627 };
2628 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002629}
2630
Tobias Grosserc80d6972016-09-02 06:33:33 +00002631/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002632///
2633///{
2634
Tobias Grosserc80d6972016-09-02 06:33:33 +00002635/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002636static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2637 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2638 : RN->getNodeAs<BasicBlock>();
2639}
2640
Tobias Grosserc80d6972016-09-02 06:33:33 +00002641/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002642static inline BasicBlock *
2643getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002644 if (RN->isSubRegion()) {
2645 assert(idx == 0);
2646 return RN->getNodeAs<Region>()->getExit();
2647 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002648 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002649}
2650
Tobias Grosserc80d6972016-09-02 06:33:33 +00002651/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002652static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002653 if (!RN->isSubRegion()) {
2654 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2655 Loop *L = LI.getLoopFor(BB);
2656
2657 // Unreachable statements are not considered to belong to a LLVM loop, as
2658 // they are not part of an actual loop in the control flow graph.
2659 // Nevertheless, we handle certain unreachable statements that are common
2660 // when modeling run-time bounds checks as being part of the loop to be
2661 // able to model them and to later eliminate the run-time bounds checks.
2662 //
2663 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002664 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002665 // basic blocks belong to the loop the predecessor belongs to. This
2666 // allows us to model the following code.
2667 //
2668 // for (i = 0; i < N; i++) {
2669 // if (i > 1024)
2670 // abort(); <- this abort might be translated to an
2671 // unreachable
2672 //
2673 // A[i] = ...
2674 // }
2675 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2676 L = LI.getLoopFor(BB->getPrevNode());
2677 return L;
2678 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002679
2680 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2681 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2682 while (L && NonAffineSubRegion->contains(L))
2683 L = L->getParentLoop();
2684 return L;
2685}
2686
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002687/// Get the number of blocks in @p L.
2688///
2689/// The number of blocks in a loop are the number of basic blocks actually
2690/// belonging to the loop, as well as all single basic blocks that the loop
2691/// exits to and which terminate in an unreachable instruction. We do not
2692/// allow such basic blocks in the exit of a scop, hence they belong to the
2693/// scop and represent run-time conditions which we want to model and
2694/// subsequently speculate away.
2695///
2696/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002697unsigned getNumBlocksInLoop(Loop *L) {
2698 unsigned NumBlocks = L->getNumBlocks();
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002699 SmallVector<BasicBlock *, 4> ExitBlocks;
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002700 L->getExitBlocks(ExitBlocks);
2701
2702 for (auto ExitBlock : ExitBlocks) {
2703 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2704 NumBlocks++;
2705 }
2706 return NumBlocks;
2707}
2708
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002709static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2710 if (!RN->isSubRegion())
2711 return 1;
2712
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002713 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002714 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002715}
2716
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002717static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2718 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002719 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002720 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002721 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002722 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002723 return true;
2724 return false;
2725}
2726
Johannes Doerfert96425c22015-08-30 21:13:53 +00002727///}
2728
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002729static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2730 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002731 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002732 isl_id *DimId =
2733 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2734 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2735}
2736
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002737isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002738 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002739}
2740
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002741isl::set Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002742 auto DIt = DomainMap.find(BB);
2743 if (DIt != DomainMap.end())
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002744 return DIt->getSecond();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002745
2746 auto &RI = *R.getRegionInfo();
2747 auto *BBR = RI.getRegionFor(BB);
2748 while (BBR->getEntry() == BB)
2749 BBR = BBR->getParent();
2750 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002751}
2752
Tobias Grosser13acbb92017-07-15 09:01:31 +00002753bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2754 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002755 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002756 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002757 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2758 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002759 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002760
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002761 while (LD-- >= 0) {
2762 S = addDomainDimId(S, LD + 1, L);
2763 L = L->getParentLoop();
2764 }
2765
Tobias Grosser13acbb92017-07-15 09:01:31 +00002766 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002767 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002768
Johannes Doerfert432658d2016-01-26 11:01:41 +00002769 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002770 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002771
Michael Kruse476f8552017-06-29 12:47:41 +00002772 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002773 return false;
2774
Michael Kruse476f8552017-06-29 12:47:41 +00002775 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002776 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002777
2778 // Error blocks and blocks dominated by them have been assumed to never be
2779 // executed. Representing them in the Scop does not add any value. In fact,
2780 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002781 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002782 // will cause problems when building up a ScopStmt for them.
2783 // Furthermore, basic blocks dominated by error blocks may reference
2784 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002785 // can themselves not be constructed properly. To this end we will replace
2786 // the domains of error blocks and those only reachable via error blocks
2787 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002788 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002789 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002790 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002791 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002792
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002793 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002794}
2795
Tobias Grosserc80d6972016-09-02 06:33:33 +00002796/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002797/// to be compatible to domains constructed for loop @p NewL.
2798///
2799/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2800/// edge from @p OldL to @p NewL.
2801static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2802 __isl_take isl_set *Dom,
2803 Loop *OldL, Loop *NewL) {
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002804 // If the loops are the same there is nothing to do.
2805 if (NewL == OldL)
2806 return Dom;
2807
2808 int OldDepth = S.getRelativeLoopDepth(OldL);
2809 int NewDepth = S.getRelativeLoopDepth(NewL);
2810 // If both loops are non-affine loops there is nothing to do.
2811 if (OldDepth == -1 && NewDepth == -1)
2812 return Dom;
2813
2814 // Distinguish three cases:
2815 // 1) The depth is the same but the loops are not.
2816 // => One loop was left one was entered.
2817 // 2) The depth increased from OldL to NewL.
2818 // => One loop was entered, none was left.
2819 // 3) The depth decreased from OldL to NewL.
2820 // => Loops were left were difference of the depths defines how many.
2821 if (OldDepth == NewDepth) {
2822 assert(OldL->getParentLoop() == NewL->getParentLoop());
2823 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2824 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2825 Dom = addDomainDimId(Dom, NewDepth, NewL);
2826 } else if (OldDepth < NewDepth) {
2827 assert(OldDepth + 1 == NewDepth);
2828 auto &R = S.getRegion();
2829 (void)R;
2830 assert(NewL->getParentLoop() == OldL ||
2831 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2832 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2833 Dom = addDomainDimId(Dom, NewDepth, NewL);
2834 } else {
2835 assert(OldDepth > NewDepth);
2836 int Diff = OldDepth - NewDepth;
2837 int NumDim = isl_set_n_dim(Dom);
2838 assert(NumDim >= Diff);
2839 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2840 }
2841
2842 return Dom;
2843}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002844
Michael Kruse476f8552017-06-29 12:47:41 +00002845bool Scop::propagateInvalidStmtDomains(
2846 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002847 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002848 ReversePostOrderTraversal<Region *> RTraversal(R);
2849 for (auto *RN : RTraversal) {
2850
2851 // Recurse for affine subregions but go on for basic blocks and non-affine
2852 // subregions.
2853 if (RN->isSubRegion()) {
2854 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002855 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002856 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002857 continue;
2858 }
2859 }
2860
2861 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2862 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002863 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002864 assert(Domain && "Cannot propagate a nullptr");
2865
Tobias Grosser325204a32017-07-15 12:41:32 +00002866 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002867
Tobias Grosser325204a32017-07-15 12:41:32 +00002868 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002869
Johannes Doerferta3519512016-04-23 13:02:23 +00002870 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002871 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002872 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002873 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002874 isl::set DomPar = Domain.params();
2875 recordAssumption(ERRORBLOCK, DomPar.release(),
2876 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002877 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002878 }
2879
Tobias Grosser325204a32017-07-15 12:41:32 +00002880 if (InvalidDomain.is_empty()) {
2881 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002882 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002883 }
2884
Johannes Doerferta3519512016-04-23 13:02:23 +00002885 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002886 auto *TI = BB->getTerminator();
2887 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2888 for (unsigned u = 0; u < NumSuccs; u++) {
2889 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002890
2891 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002892 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002893 continue;
2894
Johannes Doerferte4459a22016-04-25 13:34:50 +00002895 // Skip backedges.
2896 if (DT.dominates(SuccBB, BB))
2897 continue;
2898
Michael Kruse476f8552017-06-29 12:47:41 +00002899 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2900
Johannes Doerferta3519512016-04-23 13:02:23 +00002901 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002902 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002903
Tobias Grosser13acbb92017-07-15 09:01:31 +00002904 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002905 SuccInvalidDomain =
2906 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2907 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2908 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002909
Tobias Grosser13acbb92017-07-15 09:01:31 +00002910 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002911
Michael Krusebc150122016-05-02 12:25:18 +00002912 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002913 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002914 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002915 continue;
2916
Tobias Grosserf44f0052017-07-09 15:47:17 +00002917 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002918 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002919 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002920 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002921
Tobias Grosser325204a32017-07-15 12:41:32 +00002922 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002923 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002924
2925 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002926}
2927
Johannes Doerfert642594a2016-04-04 07:57:39 +00002928void Scop::propagateDomainConstraintsToRegionExit(
2929 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002930 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002931 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002932 // Check if the block @p BB is the entry of a region. If so we propagate it's
2933 // domain to the exit block of the region. Otherwise we are done.
2934 auto *RI = R.getRegionInfo();
2935 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2936 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002937 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002938 return;
2939
Johannes Doerfert642594a2016-04-04 07:57:39 +00002940 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002941 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002942 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002943 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002944 SmallVector<BasicBlock *, 4> LatchBBs;
2945 BBLoop->getLoopLatches(LatchBBs);
2946 for (auto *LatchBB : LatchBBs)
2947 if (BB != LatchBB && BBReg->contains(LatchBB))
2948 return;
2949 L = L->getParentLoop();
2950 }
2951
Tobias Grosser325204a32017-07-15 12:41:32 +00002952 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002953 assert(Domain && "Cannot propagate a nullptr");
2954
Michael Kruse476f8552017-06-29 12:47:41 +00002955 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002956
2957 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2958 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002959 isl::set AdjustedDomain = isl::manage(
2960 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2961 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002962
2963 // If the exit domain is not yet created we set it otherwise we "add" the
2964 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002965 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002966
Johannes Doerferta3519512016-04-23 13:02:23 +00002967 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002968 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002969
Johannes Doerfert642594a2016-04-04 07:57:39 +00002970 FinishedExitBlocks.insert(ExitBB);
2971}
2972
Michael Kruse476f8552017-06-29 12:47:41 +00002973bool Scop::buildDomainsWithBranchConstraints(
2974 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002975 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002976 // To create the domain for each block in R we iterate over all blocks and
2977 // subregions in R and propagate the conditions under which the current region
2978 // element is executed. To this end we iterate in reverse post order over R as
2979 // it ensures that we first visit all predecessors of a region node (either a
2980 // basic block or a subregion) before we visit the region node itself.
2981 // Initially, only the domain for the SCoP region entry block is set and from
2982 // there we propagate the current domain to all successors, however we add the
2983 // condition that the successor is actually executed next.
2984 // As we are only interested in non-loop carried constraints here we can
2985 // simply skip loop back edges.
2986
Johannes Doerfert642594a2016-04-04 07:57:39 +00002987 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002988 ReversePostOrderTraversal<Region *> RTraversal(R);
2989 for (auto *RN : RTraversal) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002990 // Recurse for affine subregions but go on for basic blocks and non-affine
2991 // subregions.
2992 if (RN->isSubRegion()) {
2993 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002994 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002995 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2996 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002997 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002998 continue;
2999 }
3000 }
3001
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00003002 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00003003 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00003004
Johannes Doerfert96425c22015-08-30 21:13:53 +00003005 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00003006 TerminatorInst *TI = BB->getTerminator();
3007
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00003008 if (isa<UnreachableInst>(TI))
3009 continue;
3010
Tobias Grosser325204a32017-07-15 12:41:32 +00003011 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00003012 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00003013 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00003014 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003015
Johannes Doerfert642594a2016-04-04 07:57:39 +00003016 auto *BBLoop = getRegionNodeLoop(RN, LI);
3017 // Propagate the domain from BB directly to blocks that have a superset
3018 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00003019 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
3020 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00003021
3022 // If all successors of BB have been set a domain through the propagation
3023 // above we do not need to build condition sets but can just skip this
3024 // block. However, it is important to note that this is a local property
3025 // with regards to the region @p R. To this end FinishedExitBlocks is a
3026 // local variable.
3027 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
3028 return FinishedExitBlocks.count(SuccBB);
3029 };
3030 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
3031 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003032
3033 // Build the condition sets for the successor nodes of the current region
3034 // node. If it is a non-affine subregion we will always execute the single
3035 // exit node, hence the single entry node domain is the condition set. For
3036 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003037 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003038 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00003039 ConditionSets.push_back(Domain.copy());
3040 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00003041 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003042 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003043
3044 // Now iterate over the successors and set their initial domain based on
3045 // their condition set. We skip back edges here and have to be careful when
3046 // we leave a loop not to keep constraints over a dimension that doesn't
3047 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003048 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00003049 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003050 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003051 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003052
Johannes Doerfert535de032016-04-19 14:49:05 +00003053 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00003054 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00003055 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00003056
Johannes Doerfert642594a2016-04-04 07:57:39 +00003057 // If we propagate the domain of some block to "SuccBB" we do not have to
3058 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003059 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00003060 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00003061
Johannes Doerfert96425c22015-08-30 21:13:53 +00003062 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00003063 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00003064 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003065
Michael Kruse476f8552017-06-29 12:47:41 +00003066 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
3067
Tobias Grosser325204a32017-07-15 12:41:32 +00003068 CondSet = isl::manage(
3069 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003070
3071 // Set the domain for the successor or merge it with an existing domain in
3072 // case there are multiple paths (without loop back edges) to the
3073 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003074 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00003075
Johannes Doerferta3519512016-04-23 13:02:23 +00003076 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003077 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00003078 } else {
3079 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003080 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00003081 SuccDomain = CondSet;
3082 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00003083
Tobias Grosser325204a32017-07-15 12:41:32 +00003084 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00003085
Michael Krusebc150122016-05-02 12:25:18 +00003086 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003087 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003088 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003089 continue;
3090
3091 invalidate(COMPLEXITY, DebugLoc());
3092 while (++u < ConditionSets.size())
3093 isl_set_free(ConditionSets[u]);
3094 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003095 }
3096 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003097
3098 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003099}
3100
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003101isl::set Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
3102 DominatorTree &DT,
3103 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003104 // If @p BB is the ScopEntry we are done
3105 if (R.getEntry() == BB)
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003106 return isl::set::universe(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003107
Johannes Doerfert642594a2016-04-04 07:57:39 +00003108 // The region info of this function.
3109 auto &RI = *R.getRegionInfo();
3110
Michael Kruse476f8552017-06-29 12:47:41 +00003111 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003112
3113 // A domain to collect all predecessor domains, thus all conditions under
3114 // which the block is executed. To this end we start with the empty domain.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003115 isl::set PredDom = isl::set::empty(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003116
3117 // Set of regions of which the entry block domain has been propagated to BB.
3118 // all predecessors inside any of the regions can be skipped.
3119 SmallSet<Region *, 8> PropagatedRegions;
3120
3121 for (auto *PredBB : predecessors(BB)) {
3122 // Skip backedges.
3123 if (DT.dominates(BB, PredBB))
3124 continue;
3125
3126 // If the predecessor is in a region we used for propagation we can skip it.
3127 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3128 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3129 PredBBInRegion)) {
3130 continue;
3131 }
3132
3133 // Check if there is a valid region we can use for propagation, thus look
3134 // for a region that contains the predecessor and has @p BB as exit block.
3135 auto *PredR = RI.getRegionFor(PredBB);
3136 while (PredR->getExit() != BB && !PredR->contains(BB))
3137 PredR->getParent();
3138
3139 // If a valid region for propagation was found use the entry of that region
3140 // for propagation, otherwise the PredBB directly.
3141 if (PredR->getExit() == BB) {
3142 PredBB = PredR->getEntry();
3143 PropagatedRegions.insert(PredR);
3144 }
3145
Tobias Grosser61bd3a42017-08-06 21:42:38 +00003146 auto *PredBBDom = getDomainConditions(PredBB).release();
Michael Kruse476f8552017-06-29 12:47:41 +00003147 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3148
Johannes Doerfert642594a2016-04-04 07:57:39 +00003149 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3150
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003151 PredDom = PredDom.unite(isl::manage(PredBBDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00003152 }
3153
3154 return PredDom;
3155}
3156
Michael Kruse476f8552017-06-29 12:47:41 +00003157bool Scop::propagateDomainConstraints(
3158 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003159 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003160 // Iterate over the region R and propagate the domain constrains from the
3161 // predecessors to the current node. In contrast to the
3162 // buildDomainsWithBranchConstraints function, this one will pull the domain
3163 // information from the predecessors instead of pushing it to the successors.
3164 // Additionally, we assume the domains to be already present in the domain
3165 // map here. However, we iterate again in reverse post order so we know all
3166 // predecessors have been visited before a block or non-affine subregion is
3167 // visited.
3168
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003169 ReversePostOrderTraversal<Region *> RTraversal(R);
3170 for (auto *RN : RTraversal) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003171 // Recurse for affine subregions but go on for basic blocks and non-affine
3172 // subregions.
3173 if (RN->isSubRegion()) {
3174 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003175 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003176 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003177 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003178 continue;
3179 }
3180 }
3181
3182 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003183 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003184 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003185
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003186 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003187 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser325204a32017-07-15 12:41:32 +00003188 Domain = Domain.intersect(PredDom).coalesce();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00003189 Domain = Domain.align_params(getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003190
Johannes Doerfert642594a2016-04-04 07:57:39 +00003191 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003192 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003193 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003194 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003195 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003196
3197 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003198}
3199
Tobias Grosserc80d6972016-09-02 06:33:33 +00003200/// Create a map to map from a given iteration to a subsequent iteration.
3201///
3202/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3203/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003204/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003205///
3206/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003207static __isl_give isl_map *
3208createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3209 auto *MapSpace = isl_space_map_from_set(SetSpace);
3210 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003211 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003212 if (u != Dim)
3213 NextIterationMap =
3214 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3215 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3216 C = isl_constraint_set_constant_si(C, 1);
3217 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3218 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3219 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3220 return NextIterationMap;
3221}
3222
Michael Kruse476f8552017-06-29 12:47:41 +00003223bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003224 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003225 int LoopDepth = getRelativeLoopDepth(L);
3226 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003227
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003228 BasicBlock *HeaderBB = L->getHeader();
3229 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003230 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003231
Tobias Grosser325204a32017-07-15 12:41:32 +00003232 isl::map NextIterationMap = isl::manage(
3233 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003234
Tobias Grosser325204a32017-07-15 12:41:32 +00003235 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003236
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003237 SmallVector<BasicBlock *, 4> LatchBlocks;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003238 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003239
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003240 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003241 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003242 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003243 if (!LatchBBDom)
3244 continue;
3245
Tobias Grosser325204a32017-07-15 12:41:32 +00003246 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003247
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003248 TerminatorInst *TI = LatchBB->getTerminator();
3249 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003250 assert(BI && "Only branch instructions allowed in loop latches");
3251
3252 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003253 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003254 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003255 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003256 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003257 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3258 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003259 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003260
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003261 // Free the non back edge condition set as we do not need it.
3262 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003263
Tobias Grosser325204a32017-07-15 12:41:32 +00003264 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003265 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003266
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003267 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3268 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003269 BackedgeCondition = BackedgeCondition.project_out(
3270 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3271 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003272 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003273
Tobias Grosser325204a32017-07-15 12:41:32 +00003274 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003275 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003276 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003277
Tobias Grosser325204a32017-07-15 12:41:32 +00003278 isl::set UnionBackedgeConditionComplement =
3279 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003280 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003281 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3282 0);
3283 UnionBackedgeConditionComplement =
3284 UnionBackedgeConditionComplement.apply(ForwardMap);
3285 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3286 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003287
Tobias Grosser325204a32017-07-15 12:41:32 +00003288 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3289 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003290
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003291 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3292 // the bounded assumptions to the context as they are already implied by the
3293 // <nsw> tag.
3294 if (Affinator.hasNSWAddRecForLoop(L)) {
3295 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003296 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003297 }
3298
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003299 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003300 recordAssumption(INFINITELOOP, UnboundedCtx,
3301 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003302 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003303}
3304
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003305MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003306 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003307
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003308 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003309 if (!PointerBaseInst)
3310 return nullptr;
3311
3312 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3313 if (!BasePtrStmt)
3314 return nullptr;
3315
3316 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3317}
3318
3319bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003320 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003321 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003322 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003323 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003324
Tobias Grosserbe372d52017-02-09 10:11:58 +00003325 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003326 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003327 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003328 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003329
3330 return false;
3331}
3332
Johannes Doerfert5210da52016-06-02 11:06:54 +00003333bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003334 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003335 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003336
Johannes Doerfertcd195322016-11-17 21:41:08 +00003337 if (buildAliasGroups(AA)) {
3338 // Aliasing assumptions do not go through addAssumption but we still want to
3339 // collect statistics so we do it here explicitly.
3340 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003341 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003342 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003343 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003344
3345 // If a problem occurs while building the alias groups we need to delete
3346 // this SCoP and pretend it wasn't valid in the first place. To this end
3347 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003348 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003349
3350 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3351 << " could not be created as the number of parameters involved "
3352 "is too high. The SCoP will be "
3353 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3354 "the maximal number of parameters but be advised that the "
3355 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003356 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003357}
3358
Tobias Grosser889830b2017-02-09 23:12:22 +00003359std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003360Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003361 AliasSetTracker AST(AA);
3362
3363 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003364 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003365 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003366
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003367 isl_set *StmtDomain = Stmt.getDomain().release();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003368 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3369 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003370
3371 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003372 if (StmtDomainEmpty)
3373 continue;
3374
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003375 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003376 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003377 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003378 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003379 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003380 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003381 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003382 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003383 else
3384 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003385 AST.add(Acc);
3386 }
3387 }
3388
Tobias Grosser9edcf072017-01-16 14:07:57 +00003389 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003390 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003391 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003392 continue;
3393 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003394 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003395 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003396 if (AG.size() < 2)
3397 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003398 AliasGroups.push_back(std::move(AG));
3399 }
3400
Tobias Grosser9edcf072017-01-16 14:07:57 +00003401 return std::make_tuple(AliasGroups, HasWriteAccess);
3402}
3403
Tobias Grossere39f9122017-01-16 14:08:00 +00003404void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003405 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3406 AliasGroupTy NewAG;
3407 AliasGroupTy &AG = AliasGroups[u];
3408 AliasGroupTy::iterator AGI = AG.begin();
3409 isl_set *AGDomain = getAccessDomain(*AGI);
3410 while (AGI != AG.end()) {
3411 MemoryAccess *MA = *AGI;
3412 isl_set *MADomain = getAccessDomain(MA);
3413 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3414 NewAG.push_back(MA);
3415 AGI = AG.erase(AGI);
3416 isl_set_free(MADomain);
3417 } else {
3418 AGDomain = isl_set_union(AGDomain, MADomain);
3419 AGI++;
3420 }
3421 }
3422 if (NewAG.size() > 1)
3423 AliasGroups.push_back(std::move(NewAG));
3424 isl_set_free(AGDomain);
3425 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003426}
3427
3428bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3429 // To create sound alias checks we perform the following steps:
3430 // o) We partition each group into read only and non read only accesses.
3431 // o) For each group with more than one base pointer we then compute minimal
3432 // and maximal accesses to each array of a group in read only and non
3433 // read only partitions separately.
3434 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003435 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003436
3437 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3438
3439 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003440
Johannes Doerfert13771732014-10-01 12:40:46 +00003441 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003442 if (!hasFeasibleRuntimeContext())
3443 return false;
3444
Tobias Grosser57a1d362017-06-23 08:05:27 +00003445 {
3446 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3447 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3448 if (!Valid)
3449 return false;
3450 }
3451 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3452 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003453 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003454 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003455 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003456
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003457 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003458}
3459
Tobias Grosser77f32572017-01-16 15:49:07 +00003460bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003461 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003462 AliasGroupTy ReadOnlyAccesses;
3463 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003464 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003465 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003466
Tobias Grosser77f32572017-01-16 15:49:07 +00003467 if (AliasGroup.size() < 2)
3468 return true;
3469
3470 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003471 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3472 Access->getAccessInstruction())
3473 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003474 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3475 if (HasWriteAccess.count(Array)) {
3476 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003477 ReadWriteAccesses.push_back(Access);
3478 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003479 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003480 ReadOnlyAccesses.push_back(Access);
3481 }
3482 }
3483
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003484 // If there are no read-only pointers, and less than two read-write pointers,
3485 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003486 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003487 return true;
3488
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003489 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003490 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003491 return true;
3492
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003493 // For non-affine accesses, no alias check can be generated as we cannot
3494 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003495 for (MemoryAccess *MA : AliasGroup) {
3496 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003497 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3498 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003499 return false;
3500 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003501 }
3502
3503 // Ensure that for all memory accesses for which we generate alias checks,
3504 // their base pointers are available.
3505 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003506 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3507 addRequiredInvariantLoad(
3508 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3509 }
3510
3511 MinMaxAliasGroups.emplace_back();
3512 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3513 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3514 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3515
3516 bool Valid;
3517
3518 Valid =
3519 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3520
3521 if (!Valid)
3522 return false;
3523
3524 // Bail out if the number of values we need to compare is too large.
3525 // This is important as the number of comparisons grows quadratically with
3526 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003527 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003528 RunTimeChecksMaxArraysPerGroup)
3529 return false;
3530
3531 Valid =
3532 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3533
3534 if (!Valid)
3535 return false;
3536
3537 return true;
3538}
3539
Tobias Grosserc80d6972016-09-02 06:33:33 +00003540/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003541static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003542 // Start with the smallest loop containing the entry and expand that
3543 // loop until it contains all blocks in the region. If there is a loop
3544 // containing all blocks in the region check if it is itself contained
3545 // and if so take the parent loop as it will be the smallest containing
3546 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003547 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003548 while (L) {
3549 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003550 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003551 AllContained &= L->contains(BB);
3552 if (AllContained)
3553 break;
3554 L = L->getParentLoop();
3555 }
3556
Johannes Doerfertef744432016-05-23 12:42:38 +00003557 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003558}
3559
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003560int Scop::NextScopID = 0;
3561
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003562std::string Scop::CurrentFunc;
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003563
3564int Scop::getNextID(std::string ParentFunc) {
3565 if (ParentFunc != CurrentFunc) {
3566 CurrentFunc = ParentFunc;
3567 NextScopID = 0;
3568 }
3569 return NextScopID++;
3570}
3571
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003572Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003573 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003574 : SE(&ScalarEvolution), R(R), name(R.getNameStr()),
3575 HasSingleExitEdge(R.getExitingBlock()), DC(DC), ORE(ORE),
3576 IslCtx(isl_ctx_alloc(), isl_ctx_free), Affinator(this, LI),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003577 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003578 if (IslOnErrorAbort)
3579 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003580 buildContext();
3581}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003582
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003583Scop::~Scop() {
3584 isl_set_free(Context);
3585 isl_set_free(AssumedContext);
3586 isl_set_free(InvalidContext);
3587 isl_schedule_free(Schedule);
3588
3589 ParameterIds.clear();
3590
3591 for (auto &AS : RecordedAssumptions)
3592 isl_set_free(AS.Set);
3593
3594 // Free the alias groups
3595 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
3596 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
3597 isl_pw_multi_aff_free(MMA.first);
3598 isl_pw_multi_aff_free(MMA.second);
3599 }
3600 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
3601 isl_pw_multi_aff_free(MMA.first);
3602 isl_pw_multi_aff_free(MMA.second);
3603 }
3604 }
3605
3606 for (const auto &IAClass : InvariantEquivClasses)
3607 isl_set_free(IAClass.ExecutionContext);
3608
3609 // Explicitly release all Scop objects and the underlying isl objects before
3610 // we release the isl context.
3611 Stmts.clear();
3612 ScopArrayInfoSet.clear();
3613 ScopArrayInfoMap.clear();
3614 ScopArrayNameMap.clear();
3615 AccessFunctions.clear();
3616}
3617
Tobias Grosserbedef002016-12-02 08:10:56 +00003618void Scop::foldSizeConstantsToRight() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003619 isl_union_set *Accessed = isl_union_map_range(getAccesses().release());
Tobias Grosserbedef002016-12-02 08:10:56 +00003620
3621 for (auto Array : arrays()) {
3622 if (Array->getNumberOfDimensions() <= 1)
3623 continue;
3624
Tobias Grosser77eef902017-07-21 23:07:56 +00003625 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003626
3627 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3628
3629 if (!isl_union_set_contains(Accessed, Space)) {
3630 isl_space_free(Space);
3631 continue;
3632 }
3633
3634 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3635
3636 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003637 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003638
3639 std::vector<int> Int;
3640
3641 int Dims = isl_set_dim(Elements, isl_dim_set);
3642 for (int i = 0; i < Dims; i++) {
3643 isl_set *DimOnly =
3644 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3645 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3646 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3647
3648 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3649
3650 if (i == Dims - 1) {
3651 Int.push_back(1);
3652 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3653 isl_basic_set_free(DimHull);
3654 continue;
3655 }
3656
3657 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3658 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3659 isl_val *Val = isl_aff_get_denominator_val(Diff);
3660 isl_aff_free(Diff);
3661
3662 int ValInt = 1;
3663
3664 if (isl_val_is_int(Val))
3665 ValInt = isl_val_get_num_si(Val);
3666 isl_val_free(Val);
3667
3668 Int.push_back(ValInt);
3669
3670 isl_constraint *C = isl_constraint_alloc_equality(
3671 isl_local_space_from_space(isl_map_get_space(Transform)));
3672 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3673 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3674 Transform = isl_map_add_constraint(Transform, C);
3675 isl_basic_set_free(DimHull);
3676 continue;
3677 }
3678
3679 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3680 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3681
3682 int ValInt = 1;
3683 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3684 ValInt = 0;
3685 }
3686
3687 Int.push_back(ValInt);
3688 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3689 isl_basic_set_free(DimHull);
3690 isl_basic_set_free(ZeroSet);
3691 }
3692
3693 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3694
3695 if (!isl_set_is_subset(Elements, MappedElements)) {
3696 isl_set_free(Elements);
3697 isl_set_free(MappedElements);
3698 isl_map_free(Transform);
3699 continue;
3700 }
3701
3702 isl_set_free(MappedElements);
3703
3704 bool CanFold = true;
3705
3706 if (Int[0] <= 1)
3707 CanFold = false;
3708
3709 unsigned NumDims = Array->getNumberOfDimensions();
3710 for (unsigned i = 1; i < NumDims - 1; i++)
3711 if (Int[0] != Int[i] && Int[i])
3712 CanFold = false;
3713
3714 if (!CanFold) {
3715 isl_set_free(Elements);
3716 isl_map_free(Transform);
3717 continue;
3718 }
3719
Tobias Grosserbedef002016-12-02 08:10:56 +00003720 for (auto &Access : AccessFunctions)
3721 if (Access->getScopArrayInfo() == Array)
Tobias Grosser6d588042017-08-02 19:27:16 +00003722 Access->setAccessRelation(Access->getAccessRelation().apply_range(
3723 isl::manage(isl_map_copy(Transform))));
Tobias Grosserbedef002016-12-02 08:10:56 +00003724
3725 isl_map_free(Transform);
3726
3727 std::vector<const SCEV *> Sizes;
3728 for (unsigned i = 0; i < NumDims; i++) {
3729 auto Size = Array->getDimensionSize(i);
3730
3731 if (i == NumDims - 1)
3732 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3733 Sizes.push_back(Size);
3734 }
3735
3736 Array->updateSizes(Sizes, false /* CheckConsistency */);
3737
3738 isl_set_free(Elements);
3739 }
3740 isl_union_set_free(Accessed);
Tobias Grosserbedef002016-12-02 08:10:56 +00003741}
3742
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003743void Scop::markFortranArrays() {
3744 for (ScopStmt &Stmt : Stmts) {
3745 for (MemoryAccess *MemAcc : Stmt) {
3746 Value *FAD = MemAcc->getFortranArrayDescriptor();
3747 if (!FAD)
3748 continue;
3749
3750 // TODO: const_cast-ing to edit
3751 ScopArrayInfo *SAI =
3752 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3753 assert(SAI && "memory access into a Fortran array does not "
3754 "have an associated ScopArrayInfo");
3755 SAI->applyAndSetFAD(FAD);
3756 }
3757 }
3758}
3759
Tobias Grosser491b7992016-12-02 05:21:22 +00003760void Scop::finalizeAccesses() {
3761 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003762 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003763 foldAccessRelations();
3764 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003765 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003766}
3767
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003768void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003769 // Check all array accesses for each base pointer and find a (virtual) element
3770 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003771 for (ScopStmt &Stmt : *this)
3772 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003773 if (!Access->isArrayKind())
3774 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003775 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003776 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3777
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003778 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003779 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003780 unsigned DivisibleSize = Array->getElemSizeInBytes();
3781 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003782 while (!isDivisible(Subscript, DivisibleSize, *SE))
3783 DivisibleSize /= 2;
3784 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003785 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003786 }
3787
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003788 for (auto &Stmt : *this)
3789 for (auto &Access : Stmt)
3790 Access->updateDimensionality();
3791}
3792
Tobias Grosser491b7992016-12-02 05:21:22 +00003793void Scop::foldAccessRelations() {
3794 for (auto &Stmt : *this)
3795 for (auto &Access : Stmt)
3796 Access->foldAccessRelation();
3797}
3798
3799void Scop::assumeNoOutOfBounds() {
3800 for (auto &Stmt : *this)
3801 for (auto &Access : Stmt)
3802 Access->assumeNoOutOfBound();
3803}
3804
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003805void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3806 if (Stmt.isRegionStmt())
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003807 for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003808 StmtMap.erase(BB);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003809 for (Instruction &Inst : *BB)
3810 InstStmtMap.erase(&Inst);
3811 }
3812 else {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003813 StmtMap.erase(Stmt.getBasicBlock());
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003814 for (Instruction *Inst : Stmt.getInstructions())
3815 InstStmtMap.erase(Inst);
3816 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003817}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003818
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003819void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3820 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3821 if (!ShouldDelete(*StmtIt)) {
3822 StmtIt++;
3823 continue;
3824 }
3825
3826 removeFromStmtMap(*StmtIt);
3827 StmtIt = Stmts.erase(StmtIt);
3828 }
3829}
3830
3831void Scop::removeStmtNotInDomainMap() {
3832 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003833 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003834 };
3835 removeStmts(ShouldDelete);
3836}
3837
3838void Scop::simplifySCoP(bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003839 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003840 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003841
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003842 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003843 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003844 bool OnlyRead = true;
3845 for (MemoryAccess *MA : Stmt) {
3846 if (MA->isRead())
3847 continue;
3848
3849 OnlyRead = false;
3850 break;
3851 }
3852
3853 RemoveStmt = OnlyRead;
3854 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003855 return RemoveStmt;
3856 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003857
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003858 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003859}
3860
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003861InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003862 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3863 if (!LInst)
3864 return nullptr;
3865
3866 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3867 LInst = cast<LoadInst>(Rep);
3868
Johannes Doerfert96e54712016-02-07 17:30:13 +00003869 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003870 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003871 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003872 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003873 continue;
3874
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003875 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003876 for (auto *MA : MAs)
3877 if (MA->getAccessInstruction() == Val)
3878 return &IAClass;
3879 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003880
3881 return nullptr;
3882}
3883
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003884bool isAParameter(llvm::Value *maybeParam, const Function &F) {
3885 for (const llvm::Argument &Arg : F.args())
3886 if (&Arg == maybeParam)
3887 return true;
3888
3889 return false;
Michael Kruse594386e2017-08-23 12:34:37 +00003890}
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003891
Tobias Grosser305d3162017-08-07 00:10:11 +00003892bool Scop::canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3893 bool MAInvalidCtxIsEmpty,
3894 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003895 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3896 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003897 if (PollyAllowDereferenceOfAllFunctionParams &&
3898 isAParameter(LInst->getPointerOperand(), getFunction()))
3899 return true;
3900
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003901 // TODO: We can provide more information for better but more expensive
3902 // results.
3903 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3904 LInst->getAlignment(), DL))
3905 return false;
3906
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003907 // If the location might be overwritten we do not hoist it unconditionally.
3908 //
Siddharth Bhat83fe6b52017-08-08 12:26:32 +00003909 // TODO: This is probably too conservative.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003910 if (!NonHoistableCtxIsEmpty)
3911 return false;
3912
Michael Krusea6d48f52017-06-08 12:06:15 +00003913 // If a dereferenceable load is in a statement that is modeled precisely we
3914 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003915 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003916 return true;
3917
3918 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003919 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003920 // statement domain.
3921 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3922 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3923 return false;
3924 return true;
3925}
3926
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003927void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003928 if (InvMAs.empty())
3929 return;
3930
Tobias Grosser2332fa32017-08-06 15:36:48 +00003931 isl::set StmtInvalidCtx = Stmt.getInvalidContext();
3932 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003933
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003934 // Get the context under which the statement is executed but remove the error
3935 // context under which this statement is reached.
Tobias Grossere69b2722017-08-06 23:50:25 +00003936 isl::set DomainCtx = Stmt.getDomain().params();
3937 DomainCtx = DomainCtx.subtract(StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003938
Tobias Grossere69b2722017-08-06 23:50:25 +00003939 if (isl_set_n_basic_set(DomainCtx.get()) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003940 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003941 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003942 return;
3943 }
3944
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003945 // Project out all parameters that relate to loads in the statement. Otherwise
3946 // we could have cyclic dependences on the constraints under which the
3947 // hoisted loads are executed and we could not determine an order in which to
3948 // pre-load them. This happens because not only lower bounds are part of the
3949 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003950 for (auto &InvMA : InvMAs) {
3951 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003952 Instruction *AccInst = MA->getAccessInstruction();
3953 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003954 SetVector<Value *> Values;
3955 for (const SCEV *Parameter : Parameters) {
3956 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003957 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003958 if (!Values.count(AccInst))
3959 continue;
3960
Tobias Grossere69b2722017-08-06 23:50:25 +00003961 if (isl::id ParamId = getIdForParam(Parameter)) {
3962 int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003963 if (Dim >= 0)
Tobias Grossere69b2722017-08-06 23:50:25 +00003964 DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003965 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003966 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003967 }
3968 }
3969
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003970 for (auto &InvMA : InvMAs) {
3971 auto *MA = InvMA.MA;
Tobias Grossere69b2722017-08-06 23:50:25 +00003972 isl::set NHCtx = InvMA.NonHoistableCtx;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003973
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003974 // Check for another invariant access that accesses the same location as
3975 // MA and if found consolidate them. Otherwise create a new equivalence
3976 // class at the end of InvariantEquivClasses.
3977 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003978 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003979 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3980
Tobias Grossere69b2722017-08-06 23:50:25 +00003981 isl::set MAInvalidCtx = MA->getInvalidContext();
3982 bool NonHoistableCtxIsEmpty = NHCtx.is_empty();
3983 bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty();
Johannes Doerfert85676e32016-04-23 14:32:34 +00003984
Tobias Grossere69b2722017-08-06 23:50:25 +00003985 isl::set MACtx;
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003986 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003987 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3988 NonHoistableCtxIsEmpty)) {
Tobias Grossere69b2722017-08-06 23:50:25 +00003989 MACtx = isl::set::universe(DomainCtx.get_space());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003990 } else {
Tobias Grossere69b2722017-08-06 23:50:25 +00003991 MACtx = DomainCtx;
3992 MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx));
3993 MACtx = MACtx.gist_params(getContext());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003994 }
3995
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003996 bool Consolidated = false;
3997 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003998 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003999 continue;
4000
Johannes Doerfertdf880232016-03-03 12:26:58 +00004001 // If the pointer and the type is equal check if the access function wrt.
4002 // to the domain is equal too. It can happen that the domain fixes
4003 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00004004 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00004005 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004006 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00004007 if (!MAs.empty()) {
4008 auto *LastMA = MAs.front();
4009
Tobias Grossere69b2722017-08-06 23:50:25 +00004010 isl::set AR = MA->getAccessRelation().range();
4011 isl::set LastAR = LastMA->getAccessRelation().range();
4012 bool SameAR = AR.is_equal(LastAR);
Johannes Doerfertdf880232016-03-03 12:26:58 +00004013
4014 if (!SameAR)
4015 continue;
4016 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004017
4018 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004019 MAs.push_front(MA);
4020
Johannes Doerfertdf880232016-03-03 12:26:58 +00004021 Consolidated = true;
4022
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004023 // Unify the execution context of the class and this statement.
Tobias Grossere69b2722017-08-06 23:50:25 +00004024 isl::set IAClassDomainCtx = isl::manage(IAClass.ExecutionContext);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004025 if (IAClassDomainCtx)
Tobias Grossere69b2722017-08-06 23:50:25 +00004026 IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce();
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004027 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004028 IAClassDomainCtx = MACtx;
Tobias Grossere69b2722017-08-06 23:50:25 +00004029 IAClass.ExecutionContext = IAClassDomainCtx.release();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004030 break;
4031 }
4032
4033 if (Consolidated)
4034 continue;
4035
4036 // If we did not consolidate MA, thus did not find an equivalence class
4037 // for it, we create a new one.
Tobias Grossere69b2722017-08-06 23:50:25 +00004038 InvariantEquivClasses.emplace_back(InvariantEquivClassTy{
4039 PointerSCEV, MemoryAccessList{MA}, MACtx.release(), Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004040 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004041}
4042
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004043/// Check if an access range is too complex.
4044///
4045/// An access range is too complex, if it contains either many disjuncts or
4046/// very complex expressions. As a simple heuristic, we assume if a set to
4047/// be too complex if the sum of existentially quantified dimensions and
4048/// set dimensions is larger than a threshold. This reliably detects both
4049/// sets with many disjuncts as well as sets with many divisions as they
4050/// arise in h264.
4051///
4052/// @param AccessRange The range to check for complexity.
4053///
4054/// @returns True if the access range is too complex.
4055static bool isAccessRangeTooComplex(isl::set AccessRange) {
4056 unsigned NumTotalDims = 0;
4057
4058 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
4059 NumTotalDims += BSet.dim(isl::dim::div);
4060 NumTotalDims += BSet.dim(isl::dim::set);
4061 return isl::stat::ok;
4062 };
4063
4064 AccessRange.foreach_basic_set(CountDimensions);
4065
4066 if (NumTotalDims > MaxDimensionsInAccessRange)
4067 return true;
4068
4069 return false;
4070}
4071
Tobias Grosser4071cb52017-06-06 23:13:02 +00004072isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004073 // TODO: Loads that are not loop carried, hence are in a statement with
4074 // zero iterators, are by construction invariant, though we
4075 // currently "hoist" them anyway. This is necessary because we allow
4076 // them to be treated as parameters (e.g., in conditions) and our code
4077 // generation would otherwise use the old value.
4078
4079 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00004080 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004081
Johannes Doerfertc9765462016-11-17 22:11:56 +00004082 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
4083 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004084 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004085
4086 // Skip accesses that have an invariant base pointer which is defined but
4087 // not loaded inside the SCoP. This can happened e.g., if a readnone call
4088 // returns a pointer that is used as a base address. However, as we want
4089 // to hoist indirect pointers, we allow the base pointer to be defined in
4090 // the region if it is also a memory access. Each ScopArrayInfo object
4091 // that has a base pointer origin has a base pointer that is loaded and
4092 // that it is invariant, thus it will be hoisted too. However, if there is
4093 // no base pointer origin we check that the base pointer is defined
4094 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004095 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00004096 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004097 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004098
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004099 isl::map AccessRelation = give(Access->getAccessRelation().release());
Tobias Grosser4071cb52017-06-06 23:13:02 +00004100 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004101
Tobias Grosser4071cb52017-06-06 23:13:02 +00004102 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004103 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004104
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004105 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
Tobias Grosser4071cb52017-06-06 23:13:02 +00004106 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004107
4108 auto &DL = getFunction().getParent()->getDataLayout();
4109 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
4110 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004111 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004112 } else if (BB != LI->getParent()) {
4113 // Skip accesses in non-affine subregions as they might not be executed
4114 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004115 return nullptr;
4116 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004117 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004118 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004119
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004120 if (isAccessRangeTooComplex(AccessRelation.range()))
4121 return nullptr;
4122
Tobias Grosser4071cb52017-06-06 23:13:02 +00004123 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4124 isl::set WrittenCtx = Written.params();
4125 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004126
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004127 if (!IsWritten)
4128 return WrittenCtx;
4129
Tobias Grosser4071cb52017-06-06 23:13:02 +00004130 WrittenCtx = WrittenCtx.remove_divs();
4131 bool TooComplex =
4132 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4133 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004134 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004135
Tobias Grosser4071cb52017-06-06 23:13:02 +00004136 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004137 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004138 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004139}
4140
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004141void Scop::verifyInvariantLoads() {
4142 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004143 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004144 assert(LI && contains(LI));
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004145 // If there exists a statement in the scop which has a memory access for
4146 // @p LI, then mark this scop as infeasible for optimization.
4147 for (ScopStmt &Stmt : Stmts)
4148 if (Stmt.getArrayAccessOrNULLFor(LI)) {
4149 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
4150 return;
4151 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004152 }
4153}
4154
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004155void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004156 if (!PollyInvariantLoadHoisting)
4157 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004158
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004159 isl::union_map Writes = getWrites();
Tobias Grosser0865e7752016-02-29 07:29:42 +00004160 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004161 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004162
Tobias Grosser0865e7752016-02-29 07:29:42 +00004163 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004164 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
Tobias Grosserd16f9272017-08-06 17:25:14 +00004165 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004166
4167 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004168 for (auto InvMA : InvariantAccesses)
4169 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004170 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004171 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004172}
4173
Tobias Grosserf3adab42017-05-10 10:59:58 +00004174/// Find the canonical scop array info object for a set of invariant load
4175/// hoisted loads. The canonical array is the one that corresponds to the
4176/// first load in the list of accesses which is used as base pointer of a
4177/// scop array.
4178static const ScopArrayInfo *findCanonicalArray(Scop *S,
4179 MemoryAccessList &Accesses) {
4180 for (MemoryAccess *Access : Accesses) {
4181 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4182 Access->getAccessInstruction(), MemoryKind::Array);
4183 if (CanonicalArray)
4184 return CanonicalArray;
4185 }
4186 return nullptr;
4187}
4188
4189/// Check if @p Array severs as base array in an invariant load.
4190static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4191 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4192 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4193 if (Access2->getScopArrayInfo() == Array)
4194 return true;
4195 return false;
4196}
4197
4198/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4199/// with a reference to @p New.
4200static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4201 const ScopArrayInfo *New) {
4202 for (ScopStmt &Stmt : *S)
4203 for (MemoryAccess *Access : Stmt) {
4204 if (Access->getLatestScopArrayInfo() != Old)
4205 continue;
4206
Tobias Grosser6d588042017-08-02 19:27:16 +00004207 isl::id Id = New->getBasePtrId();
4208 isl::map Map = Access->getAccessRelation();
4209 Map = Map.set_tuple_id(isl::dim::out, Id);
Tobias Grosserf3adab42017-05-10 10:59:58 +00004210 Access->setAccessRelation(Map);
4211 }
4212}
4213
4214void Scop::canonicalizeDynamicBasePtrs() {
4215 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4216 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4217
4218 const ScopArrayInfo *CanonicalBasePtrSAI =
4219 findCanonicalArray(this, BasePtrAccesses);
4220
4221 if (!CanonicalBasePtrSAI)
4222 continue;
4223
4224 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4225 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4226 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4227 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4228 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4229 continue;
4230
4231 // we currently do not canonicalize arrays where some accesses are
4232 // hoisted as invariant loads. If we would, we need to update the access
4233 // function of the invariant loads as well. However, as this is not a
4234 // very common situation, we leave this for now to avoid further
4235 // complexity increases.
4236 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4237 continue;
4238
4239 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4240 }
4241 }
4242}
4243
Michael Kruseb738ffa2017-06-28 13:02:43 +00004244ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4245 ArrayRef<const SCEV *> Sizes,
4246 MemoryKind Kind,
4247 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004248 assert((BasePtr || BaseName) &&
4249 "BasePtr and BaseName can not be nullptr at the same time.");
4250 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4251 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4252 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004253 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004254 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004255 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004256 DL, this, BaseName));
4257 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004258 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004259 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004260 // In case of mismatching array sizes, we bail out by setting the run-time
4261 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004262 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004263 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004264 }
Tobias Grosserab671442015-05-23 05:58:27 +00004265 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004266}
4267
Michael Kruseb738ffa2017-06-28 13:02:43 +00004268ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4269 const std::string &BaseName,
4270 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004271 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4272 std::vector<const SCEV *> SCEVSizes;
4273
4274 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004275 if (size)
4276 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4277 else
4278 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004279
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004280 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4281 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004282 return SAI;
4283}
4284
Tobias Grosserf3adab42017-05-10 10:59:58 +00004285const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4286 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004287 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004288 return SAI;
4289}
4290
4291const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4292 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004293 assert(SAI && "No ScopArrayInfo available for this base pointer");
4294 return SAI;
4295}
4296
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004297std::string Scop::getContextStr() const { return getContext().to_str(); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004298
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004299std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004300 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004301 return stringFromIslObj(AssumedContext);
4302}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004303
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004304std::string Scop::getInvalidContextStr() const {
4305 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004306}
Tobias Grosser75805372011-04-29 06:27:02 +00004307
4308std::string Scop::getNameStr() const {
4309 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004310 std::tie(EntryName, ExitName) = getEntryExitStr();
4311 return EntryName + "---" + ExitName;
4312}
4313
4314std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4315 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004316 raw_string_ostream ExitStr(ExitName);
4317 raw_string_ostream EntryStr(EntryName);
4318
Tobias Grosserf240b482014-01-09 10:42:15 +00004319 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004320 EntryStr.str();
4321
4322 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004323 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004324 ExitStr.str();
4325 } else
4326 ExitName = "FunctionExit";
4327
Siddharth Bhat07bee292017-06-02 08:01:22 +00004328 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004329}
4330
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004331isl::set Scop::getContext() const { return isl::manage(isl_set_copy(Context)); }
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004332isl::space Scop::getParamSpace() const { return getContext().get_space(); }
Tobias Grosser37487052011-10-06 00:03:42 +00004333
Tobias Grosserb5563c62017-08-03 13:51:15 +00004334isl::space Scop::getFullParamSpace() const {
4335 std::vector<isl::id> FortranIDs;
4336 FortranIDs = getFortranArrayIds(arrays());
4337
4338 isl::space Space = isl::space::params_alloc(
4339 getIslCtx(), ParameterIds.size() + FortranIDs.size());
4340
4341 unsigned PDim = 0;
4342 for (const SCEV *Parameter : Parameters) {
Tobias Grosser9a635702017-08-06 19:31:27 +00004343 isl::id Id = getIdForParam(Parameter);
Tobias Grosserb5563c62017-08-03 13:51:15 +00004344 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4345 }
4346
4347 for (isl::id Id : FortranIDs)
4348 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4349
4350 return Space;
4351}
4352
Tobias Grossere1270332017-08-06 21:42:09 +00004353isl::set Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004354 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere1270332017-08-06 21:42:09 +00004355 return isl::manage(isl_set_copy(AssumedContext));
Tobias Grossere86109f2013-10-29 21:05:49 +00004356}
4357
Michael Krusef3091bf2017-03-17 13:09:52 +00004358bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004359 if (PollyProcessUnprofitable)
4360 return true;
4361
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004362 if (isEmpty())
4363 return false;
4364
4365 unsigned OptimizableStmtsOrLoops = 0;
4366 for (auto &Stmt : *this) {
4367 if (Stmt.getNumIterators() == 0)
4368 continue;
4369
4370 bool ContainsArrayAccs = false;
4371 bool ContainsScalarAccs = false;
4372 for (auto *MA : Stmt) {
4373 if (MA->isRead())
4374 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004375 ContainsArrayAccs |= MA->isLatestArrayKind();
4376 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004377 }
4378
Michael Krusef3091bf2017-03-17 13:09:52 +00004379 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004380 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4381 }
4382
4383 return OptimizableStmtsOrLoops > 1;
4384}
4385
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004386bool Scop::hasFeasibleRuntimeContext() const {
Tobias Grossere1270332017-08-06 21:42:09 +00004387 auto *PositiveContext = getAssumedContext().release();
Tobias Grosser04ec2eb2017-08-06 21:42:16 +00004388 auto *NegativeContext = getInvalidContext().release();
Tobias Grosser232fdad2017-08-06 20:19:26 +00004389 PositiveContext =
4390 addNonEmptyDomainConstraints(isl::manage(PositiveContext)).release();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004391 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4392 isl_set_is_subset(PositiveContext, NegativeContext));
4393 isl_set_free(PositiveContext);
4394 if (!IsFeasible) {
4395 isl_set_free(NegativeContext);
4396 return false;
4397 }
4398
Tobias Grosser31df6f32017-08-06 21:42:25 +00004399 auto *DomainContext = isl_union_set_params(getDomains().release());
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004400 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004401 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004402 isl_set_free(NegativeContext);
4403 isl_set_free(DomainContext);
4404
Johannes Doerfert43788c52015-08-20 05:58:56 +00004405 return IsFeasible;
4406}
4407
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004408static std::string toString(AssumptionKind Kind) {
4409 switch (Kind) {
4410 case ALIASING:
4411 return "No-aliasing";
4412 case INBOUNDS:
4413 return "Inbounds";
4414 case WRAPPING:
4415 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004416 case UNSIGNED:
4417 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004418 case COMPLEXITY:
4419 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004420 case PROFITABLE:
4421 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004422 case ERRORBLOCK:
4423 return "No-error";
4424 case INFINITELOOP:
4425 return "Finite loop";
4426 case INVARIANTLOAD:
4427 return "Invariant load";
4428 case DELINEARIZATION:
4429 return "Delinearization";
4430 }
4431 llvm_unreachable("Unknown AssumptionKind!");
4432}
4433
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004434bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4435 if (Sign == AS_ASSUMPTION) {
4436 if (isl_set_is_subset(Context, Set))
4437 return false;
4438
4439 if (isl_set_is_subset(AssumedContext, Set))
4440 return false;
4441 } else {
4442 if (isl_set_is_disjoint(Set, Context))
4443 return false;
4444
4445 if (isl_set_is_subset(Set, InvalidContext))
4446 return false;
4447 }
4448 return true;
4449}
4450
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004451bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004452 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004453 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4454 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004455
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004456 // Do never emit trivial assumptions as they only clutter the output.
4457 if (!PollyRemarksMinimal) {
4458 isl_set *Univ = nullptr;
4459 if (Sign == AS_ASSUMPTION)
4460 Univ = isl_set_universe(isl_set_get_space(Set));
4461
4462 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4463 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4464 isl_set_free(Univ);
4465
4466 if (IsTrivial)
4467 return false;
4468 }
4469
Johannes Doerfertcd195322016-11-17 21:41:08 +00004470 switch (Kind) {
4471 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004472 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004473 break;
4474 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004475 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004476 break;
4477 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004478 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004479 break;
4480 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004481 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004482 break;
4483 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004484 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004485 break;
4486 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004487 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004488 break;
4489 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004490 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004491 break;
4492 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004493 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004494 break;
4495 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004496 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004497 break;
4498 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004499 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004500 break;
4501 }
4502
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004503 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4504 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004505 if (BB)
4506 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4507 << Msg);
4508 else
4509 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4510 R.getEntry())
4511 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004512 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004513}
4514
4515void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004516 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004517 // Simplify the assumptions/restrictions first.
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004518 Set = isl_set_gist_params(Set, getContext().release());
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004519
Eli Friedmane737fc12017-07-17 23:58:33 +00004520 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004521 isl_set_free(Set);
4522 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004523 }
4524
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004525 if (Sign == AS_ASSUMPTION) {
4526 AssumedContext = isl_set_intersect(AssumedContext, Set);
4527 AssumedContext = isl_set_coalesce(AssumedContext);
4528 } else {
4529 InvalidContext = isl_set_union(InvalidContext, Set);
4530 InvalidContext = isl_set_coalesce(InvalidContext);
4531 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004532}
4533
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004534void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004535 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004536 assert((isl_set_is_params(Set) || BB) &&
4537 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004538 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004539}
4540
4541void Scop::addRecordedAssumptions() {
4542 while (!RecordedAssumptions.empty()) {
4543 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004544
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004545 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004546 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004547 continue;
4548 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004549
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004550 // If the domain was deleted the assumptions are void.
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004551 isl_set *Dom = getDomainConditions(AS.BB).release();
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004552 if (!Dom) {
4553 isl_set_free(AS.Set);
4554 continue;
4555 }
4556
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004557 // If a basic block was given use its domain to simplify the assumption.
4558 // In case of restrictions we know they only have to hold on the domain,
4559 // thus we can intersect them with the domain of the block. However, for
4560 // assumptions the domain has to imply them, thus:
4561 // _ _____
4562 // Dom => S <==> A v B <==> A - B
4563 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004564 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004565 // assumption.
4566 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004567 if (AS.Sign == AS_RESTRICTION)
4568 S = isl_set_params(isl_set_intersect(S, Dom));
4569 else /* (AS.Sign == AS_ASSUMPTION) */
4570 S = isl_set_params(isl_set_subtract(Dom, S));
4571
Eli Friedmane737fc12017-07-17 23:58:33 +00004572 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004573 }
4574}
4575
Eli Friedmane737fc12017-07-17 23:58:33 +00004576void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004577 addAssumption(Kind, isl_set_empty(getParamSpace().release()), Loc,
4578 AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004579}
4580
Tobias Grosser04ec2eb2017-08-06 21:42:16 +00004581isl::set Scop::getInvalidContext() const {
4582 return isl::manage(isl_set_copy(InvalidContext));
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004583}
4584
Tobias Grosser75805372011-04-29 06:27:02 +00004585void Scop::printContext(raw_ostream &OS) const {
4586 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004587 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004588
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004589 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004590 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004591
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004592 OS.indent(4) << "Invalid Context:\n";
4593 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004594
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004595 unsigned Dim = 0;
4596 for (const SCEV *Parameter : Parameters)
4597 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004598}
4599
Johannes Doerfertb164c792014-09-18 11:17:17 +00004600void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004601 int noOfGroups = 0;
4602 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004603 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004604 noOfGroups += 1;
4605 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004606 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004607 }
4608
Tobias Grosserbb853c22015-07-25 12:31:03 +00004609 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004610 if (MinMaxAliasGroups.empty()) {
4611 OS.indent(8) << "n/a\n";
4612 return;
4613 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004614
Tobias Grosserbb853c22015-07-25 12:31:03 +00004615 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004616
4617 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004618 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004619 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004620 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004621 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4622 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004623 }
4624 OS << " ]]\n";
4625 }
4626
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004627 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004628 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004629 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004630 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004631 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4632 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004633 }
4634 OS << " ]]\n";
4635 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004636 }
4637}
4638
Michael Krusecd4c9772017-07-21 15:35:53 +00004639void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004640 OS << "Statements {\n";
4641
Michael Krusecd4c9772017-07-21 15:35:53 +00004642 for (const ScopStmt &Stmt : *this) {
4643 OS.indent(4);
4644 Stmt.print(OS, PrintInstructions);
4645 }
Tobias Grosser75805372011-04-29 06:27:02 +00004646
4647 OS.indent(4) << "}\n";
4648}
4649
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004650void Scop::printArrayInfo(raw_ostream &OS) const {
4651 OS << "Arrays {\n";
4652
Tobias Grosserab671442015-05-23 05:58:27 +00004653 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004654 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004655
4656 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004657
4658 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4659
4660 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004661 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004662
4663 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004664}
4665
Michael Krusecd4c9772017-07-21 15:35:53 +00004666void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004667 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004668 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004669 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004670 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004671 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004672 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004673 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004674 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004675 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004676 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004677 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4678 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004679 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004680 }
4681 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004682 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004683 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004684 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004685 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004686}
4687
Michael Kruse5d518462017-07-21 15:54:07 +00004688#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004689LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004690#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004691
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004692isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004693
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004694__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4695 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004696 // First try to use the SCEVAffinator to generate a piecewise defined
4697 // affine function from @p E in the context of @p BB. If that tasks becomes to
4698 // complex the affinator might return a nullptr. In such a case we invalidate
4699 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004700 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004701 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004702 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004703 // TODO: We could use a heuristic and either use:
4704 // SCEVAffinator::takeNonNegativeAssumption
4705 // or
4706 // SCEVAffinator::interpretAsUnsigned
4707 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004708 if (NonNegative)
4709 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004710 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004711 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004712
4713 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004714 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004715 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004716}
4717
Tobias Grosser31df6f32017-08-06 21:42:25 +00004718isl::union_set Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004719 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4720 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004721
Tobias Grosser808cd692015-07-14 09:33:13 +00004722 for (const ScopStmt &Stmt : *this)
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004723 Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004724
Tobias Grosser31df6f32017-08-06 21:42:25 +00004725 return isl::manage(Domain);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004726}
4727
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004728isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004729 PWACtx PWAC = getPwAff(E, BB);
4730 isl_set_free(PWAC.second);
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004731 return isl::manage(PWAC.first);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004732}
4733
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004734isl::union_map
Tobias Grossere5a35142015-11-12 14:07:09 +00004735Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004736 isl::union_map Accesses = isl::union_map::empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004737
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004738 for (ScopStmt &Stmt : *this) {
4739 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004740 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004741 continue;
4742
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004743 isl::set Domain = Stmt.getDomain();
4744 isl::map AccessDomain = MA->getAccessRelation();
4745 AccessDomain = AccessDomain.intersect_domain(Domain);
4746 Accesses = Accesses.add_map(AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004747 }
4748 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00004749
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004750 return Accesses.coalesce();
Tobias Grossere5a35142015-11-12 14:07:09 +00004751}
4752
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004753isl::union_map Scop::getMustWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004754 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004755}
4756
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004757isl::union_map Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004758 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004759}
4760
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004761isl::union_map Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004762 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004763}
4764
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004765isl::union_map Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004766 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004767}
4768
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004769isl::union_map Scop::getAccesses() {
Tobias Grosser2ac23382015-11-12 14:07:13 +00004770 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4771}
4772
Tobias Grosserfa03cb72017-08-17 22:04:53 +00004773isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
4774 return getAccessesOfType(
4775 [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
4776}
4777
Roman Gareevb3224ad2016-09-14 06:26:09 +00004778// Check whether @p Node is an extension node.
4779//
4780// @return true if @p Node is an extension node.
4781isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4782 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4783 return isl_bool_error;
4784 else
4785 return isl_bool_true;
4786}
4787
4788bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4789 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4790 nullptr) == isl_stat_error;
4791}
4792
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004793isl::union_map Scop::getSchedule() const {
4794 auto *Tree = getScheduleTree().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004795 if (containsExtensionNode(Tree)) {
4796 isl_schedule_free(Tree);
4797 return nullptr;
4798 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004799 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004800 isl_schedule_free(Tree);
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004801 return isl::manage(S);
Tobias Grosser808cd692015-07-14 09:33:13 +00004802}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004803
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004804isl::schedule Scop::getScheduleTree() const {
4805 return isl::manage(isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4806 getDomains().release()));
Tobias Grosser808cd692015-07-14 09:33:13 +00004807}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004808
Tobias Grosser808cd692015-07-14 09:33:13 +00004809void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
Tobias Grosser31df6f32017-08-06 21:42:25 +00004810 auto *S = isl_schedule_from_domain(getDomains().release());
Tobias Grosser808cd692015-07-14 09:33:13 +00004811 S = isl_schedule_insert_partial_schedule(
4812 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4813 isl_schedule_free(Schedule);
4814 Schedule = S;
4815}
4816
4817void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4818 isl_schedule_free(Schedule);
4819 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004820}
4821
Tobias Grosser990cbb42017-08-14 06:49:01 +00004822bool Scop::restrictDomains(isl::union_set Domain) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00004823 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004824 for (ScopStmt &Stmt : *this) {
Tobias Grosser990cbb42017-08-14 06:49:01 +00004825 isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
4826 isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
Tobias Grosser37eb4222014-02-20 21:43:54 +00004827
Tobias Grosser990cbb42017-08-14 06:49:01 +00004828 if (StmtDomain.is_subset(NewStmtDomain))
Tobias Grosser37eb4222014-02-20 21:43:54 +00004829 continue;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004830
4831 Changed = true;
4832
Tobias Grosser990cbb42017-08-14 06:49:01 +00004833 NewStmtDomain = NewStmtDomain.coalesce();
Tobias Grosser37eb4222014-02-20 21:43:54 +00004834
Tobias Grosser990cbb42017-08-14 06:49:01 +00004835 if (NewStmtDomain.is_empty())
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004836 Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
Tobias Grosser990cbb42017-08-14 06:49:01 +00004837 else
4838 Stmt.restrictDomain(isl::set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004839 }
Tobias Grosser37eb4222014-02-20 21:43:54 +00004840 return Changed;
4841}
4842
Tobias Grosser75805372011-04-29 06:27:02 +00004843ScalarEvolution *Scop::getSE() const { return SE; }
4844
Tobias Grosserc80d6972016-09-02 06:33:33 +00004845// Create an isl_multi_union_aff that defines an identity mapping from the
4846// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004847//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004848// # Example:
4849//
4850// Domain: { A[i,j]; B[i,j,k] }
4851// N: 1
4852//
4853// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4854//
4855// @param USet A union set describing the elements for which to generate a
4856// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004857// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004858// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004859static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004860 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004861 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004862 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004863
Tobias Grosser99320862017-05-26 17:22:03 +00004864 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004865
Tobias Grosser99320862017-05-26 17:22:03 +00004866 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4867 int Dim = S.dim(isl::dim::set);
4868 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4869 N, Dim - N);
4870 if (N > 1)
4871 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004872
Tobias Grosser99320862017-05-26 17:22:03 +00004873 Result = Result.add_pw_multi_aff(PMA);
4874 return isl::stat::ok;
4875 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004876
Tobias Grosser99320862017-05-26 17:22:03 +00004877 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004878 (void)Res;
4879
Tobias Grosser99320862017-05-26 17:22:03 +00004880 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004881
Tobias Grosser99320862017-05-26 17:22:03 +00004882 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004883}
4884
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004885void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
Michael Kruse59125512017-08-30 10:11:06 +00004886 std::vector<Instruction *> Instructions, int Count) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004887 assert(BB && "Unexpected nullptr!");
Michael Kruse59125512017-08-30 10:11:06 +00004888 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions, Count);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004889 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004890 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004891 for (Instruction *Inst : Instructions) {
4892 assert(!InstStmtMap.count(Inst) &&
4893 "Unexpected statement corresponding to the instruction.");
4894 InstStmtMap[Inst] = Stmt;
4895 }
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004896}
4897
Michael Kruse55454072017-03-15 22:16:43 +00004898void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004899 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004900 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004901 auto *Stmt = &Stmts.back();
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004902 for (BasicBlock *BB : R->blocks()) {
Michael Kruse4dfa7322017-07-18 15:41:49 +00004903 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004904 for (Instruction &Inst : *BB) {
4905 assert(!InstStmtMap.count(&Inst) &&
4906 "Unexpected statement corresponding to the instruction.");
4907 InstStmtMap[&Inst] = Stmt;
4908 }
4909 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004910}
4911
Tobias Grosser85048ef2017-08-06 17:24:59 +00004912ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
4913 isl::set Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004914#ifndef NDEBUG
Tobias Grosser85048ef2017-08-06 17:24:59 +00004915 isl::set SourceDomain = SourceRel.domain();
4916 isl::set TargetDomain = TargetRel.domain();
4917 assert(Domain.is_subset(TargetDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004918 "Target access not defined for complete statement domain");
Tobias Grosser85048ef2017-08-06 17:24:59 +00004919 assert(Domain.is_subset(SourceDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004920 "Source access not defined for complete statement domain");
Tobias Grossereba86a12016-11-09 04:24:49 +00004921#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004922 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4923 CopyStmtsNum++;
4924 return &(Stmts.back());
4925}
4926
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004927void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004928 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004929 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004930 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004931 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4932 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004933}
4934
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004935/// To generate a schedule for the elements in a Region we traverse the Region
4936/// in reverse-post-order and add the contained RegionNodes in traversal order
4937/// to the schedule of the loop that is currently at the top of the LoopStack.
4938/// For loop-free codes, this results in a correct sequential ordering.
4939///
4940/// Example:
4941/// bb1(0)
4942/// / \.
4943/// bb2(1) bb3(2)
4944/// \ / \.
4945/// bb4(3) bb5(4)
4946/// \ /
4947/// bb6(5)
4948///
4949/// Including loops requires additional processing. Whenever a loop header is
4950/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4951/// from an empty schedule, we first process all RegionNodes that are within
4952/// this loop and complete the sequential schedule at this loop-level before
4953/// processing about any other nodes. To implement this
4954/// loop-nodes-first-processing, the reverse post-order traversal is
4955/// insufficient. Hence, we additionally check if the traversal yields
4956/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4957/// These region-nodes are then queue and only traverse after the all nodes
4958/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004959void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004960 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004961
4962 ReversePostOrderTraversal<Region *> RTraversal(R);
4963 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4964 std::deque<RegionNode *> DelayList;
4965 bool LastRNWaiting = false;
4966
4967 // Iterate over the region @p R in reverse post-order but queue
4968 // sub-regions/blocks iff they are not part of the last encountered but not
4969 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4970 // that we queued the last sub-region/block from the reverse post-order
4971 // iterator. If it is set we have to explore the next sub-region/block from
4972 // the iterator (if any) to guarantee progress. If it is not set we first try
4973 // the next queued sub-region/blocks.
4974 while (!WorkList.empty() || !DelayList.empty()) {
4975 RegionNode *RN;
4976
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004977 if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004978 RN = WorkList.front();
4979 WorkList.pop_front();
4980 LastRNWaiting = false;
4981 } else {
4982 RN = DelayList.front();
4983 DelayList.pop_front();
4984 }
4985
4986 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004987 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004988 L = OuterScopLoop;
4989
Tobias Grosser151ae322016-04-03 19:36:52 +00004990 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004991 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004992 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004993 LastRNWaiting = true;
4994 DelayList.push_back(RN);
4995 continue;
4996 }
4997 LoopStack.push_back({L, nullptr, 0});
4998 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004999 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005000 }
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005001}
5002
Johannes Doerfertffd222f2016-05-19 12:34:57 +00005003void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Tobias Grosser8362c262016-01-06 15:30:06 +00005004 if (RN->isSubRegion()) {
5005 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00005006 if (!isNonAffineSubRegion(LocalRegion)) {
5007 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00005008 return;
5009 }
5010 }
Michael Kruse046dde42015-08-10 13:01:57 +00005011
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005012 auto &LoopData = LoopStack.back();
5013 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00005014
Michael Kruse1ce67912017-07-20 17:18:58 +00005015 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00005016 auto *UDomain = isl_union_set_from_set(Stmt->getDomain().release());
Tobias Grosser8362c262016-01-06 15:30:06 +00005017 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005018 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00005019 }
5020
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005021 // Check if we just processed the last node in this loop. If we did, finalize
5022 // the loop by:
5023 //
5024 // - adding new schedule dimensions
5025 // - folding the resulting schedule into the parent loop schedule
5026 // - dropping the loop schedule from the LoopStack.
5027 //
5028 // Then continue to check surrounding loops, which might also have been
5029 // completed by this node.
5030 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00005031 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00005032 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005033 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00005034
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005035 LoopStack.pop_back();
5036 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00005037
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005038 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00005039 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
5040 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
5041 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005042 NextLoopData.Schedule =
5043 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00005044 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00005045
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005046 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
5047 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00005048 }
Tobias Grosser75805372011-04-29 06:27:02 +00005049}
5050
Michael Kruse6eba4b12017-07-20 17:08:50 +00005051ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
5052 auto StmtMapIt = StmtMap.find(BB);
5053 if (StmtMapIt == StmtMap.end())
5054 return {};
Michael Kruse6eba4b12017-07-20 17:08:50 +00005055 return StmtMapIt->second;
5056}
5057
5058ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
5059 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00005060 if (!StmtList.empty())
Michael Kruse6eba4b12017-07-20 17:08:50 +00005061 return StmtList.back();
5062 return nullptr;
5063}
5064
Michael Kruse1ce67912017-07-20 17:18:58 +00005065ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00005066 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00005067 return getStmtListFor(RN->getNodeAs<Region>());
5068 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00005069}
5070
Michael Kruse1ce67912017-07-20 17:18:58 +00005071ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
5072 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00005073}
5074
Johannes Doerfert96425c22015-08-30 21:13:53 +00005075int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005076 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00005077 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005078 // outermostLoopInRegion always returns nullptr for top level regions
5079 if (R.isTopLevelRegion()) {
5080 // LoopInfo's depths start at 1, we start at 0
5081 return L->getLoopDepth() - 1;
5082 } else {
5083 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
5084 assert(OuterLoop);
5085 return L->getLoopDepth() - OuterLoop->getLoopDepth();
5086 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00005087}
5088
Roman Gareevd7754a12016-07-30 09:25:51 +00005089ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
5090 for (auto &SAI : arrays()) {
5091 if (SAI->getName() == BaseName)
5092 return SAI;
5093 }
5094 return nullptr;
5095}
5096
Michael Kruse8b805802017-07-19 17:11:25 +00005097void Scop::addAccessData(MemoryAccess *Access) {
5098 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
5099 assert(SAI && "can only use after access relations have been constructed");
5100
5101 if (Access->isOriginalValueKind() && Access->isRead())
5102 ValueUseAccs[SAI].push_back(Access);
5103 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
5104 PHIIncomingAccs[SAI].push_back(Access);
5105}
5106
5107void Scop::removeAccessData(MemoryAccess *Access) {
5108 if (Access->isOriginalValueKind() && Access->isRead()) {
5109 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
5110 std::remove(Uses.begin(), Uses.end(), Access);
5111 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
5112 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
5113 std::remove(Incomings.begin(), Incomings.end(), Access);
5114 }
5115}
5116
5117MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
5118 assert(SAI->isValueKind());
5119
5120 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
5121 if (!Val)
5122 return nullptr;
5123
5124 ScopStmt *Stmt = getStmtFor(Val);
5125 if (!Stmt)
5126 return nullptr;
5127
5128 return Stmt->lookupValueWriteOf(Val);
5129}
5130
5131ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
5132 assert(SAI->isValueKind());
5133 auto It = ValueUseAccs.find(SAI);
5134 if (It == ValueUseAccs.end())
5135 return {};
5136 return It->second;
5137}
5138
5139MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
5140 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5141
5142 if (SAI->isExitPHIKind())
5143 return nullptr;
5144
5145 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
5146 ScopStmt *Stmt = getStmtFor(PHI);
5147 assert(Stmt && "PHINode must be within the SCoP");
5148
5149 return Stmt->lookupPHIReadOf(PHI);
5150}
5151
5152ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
5153 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5154 auto It = PHIIncomingAccs.find(SAI);
5155 if (It == PHIIncomingAccs.end())
5156 return {};
5157 return It->second;
5158}
5159
Michael Krusea508a4e2017-07-27 14:39:52 +00005160bool Scop::isEscaping(Instruction *Inst) {
5161 assert(contains(Inst) && "The concept of escaping makes only sense for "
5162 "values defined inside the SCoP");
5163
5164 for (Use &Use : Inst->uses()) {
5165 BasicBlock *UserBB = getUseBlock(Use);
5166 if (!contains(UserBB))
5167 return true;
5168
5169 // When the SCoP region exit needs to be simplified, PHIs in the region exit
5170 // move to a new basic block such that its incoming blocks are not in the
5171 // SCoP anymore.
5172 if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
5173 isExit(cast<PHINode>(Use.getUser())->getParent()))
5174 return true;
5175 }
5176 return false;
5177}
5178
Michael Kruse06ed5292017-08-23 13:50:30 +00005179Scop::ScopStatistics Scop::getStatistics() const {
5180 ScopStatistics Result;
5181#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
5182 auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
5183
5184 int NumTotalLoops = LoopStat.NumLoops;
5185 Result.NumBoxedLoops = getBoxedLoops().size();
5186 Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
5187
5188 for (const ScopStmt &Stmt : *this) {
5189 isl::set Domain = Stmt.getDomain().intersect_params(getContext());
5190 bool IsInLoop = Stmt.getNumIterators() >= 1;
5191 for (MemoryAccess *MA : Stmt) {
5192 if (!MA->isWrite())
5193 continue;
5194
5195 if (MA->isLatestValueKind()) {
5196 Result.NumValueWrites += 1;
5197 if (IsInLoop)
5198 Result.NumValueWritesInLoops += 1;
5199 }
5200
5201 if (MA->isLatestAnyPHIKind()) {
5202 Result.NumPHIWrites += 1;
5203 if (IsInLoop)
5204 Result.NumPHIWritesInLoops += 1;
5205 }
5206
5207 isl::set AccSet =
5208 MA->getAccessRelation().intersect_domain(Domain).range();
5209 if (AccSet.is_singleton()) {
5210 Result.NumSingletonWrites += 1;
5211 if (IsInLoop)
5212 Result.NumSingletonWritesInLoops += 1;
5213 }
5214 }
5215 }
5216#endif
5217 return Result;
5218}
5219
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00005220raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
5221 scop.print(OS, PollyPrintInstructions);
5222 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00005223}
5224
Johannes Doerfert99191c72016-05-31 09:41:04 +00005225//===----------------------------------------------------------------------===//
5226void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5227 AU.addRequired<LoopInfoWrapperPass>();
5228 AU.addRequired<RegionInfoPass>();
5229 AU.addRequired<DominatorTreeWrapperPass>();
5230 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005231 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005232 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005233 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00005234 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005235 AU.setPreservesAll();
5236}
5237
Michael Kruse06ed5292017-08-23 13:50:30 +00005238void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
5239 Scop::ScopStatistics ScopStats) {
5240 assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
5241
5242 NumScops++;
Tobias Grossercd01a362017-02-17 08:12:36 +00005243 NumLoopsInScop += Stats.NumLoops;
5244 MaxNumLoopsInScop =
5245 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5246
Tobias Grossercd01a362017-02-17 08:12:36 +00005247 if (Stats.MaxDepth == 1)
5248 NumScopsDepthOne++;
5249 else if (Stats.MaxDepth == 2)
5250 NumScopsDepthTwo++;
5251 else if (Stats.MaxDepth == 3)
5252 NumScopsDepthThree++;
5253 else if (Stats.MaxDepth == 4)
5254 NumScopsDepthFour++;
5255 else if (Stats.MaxDepth == 5)
5256 NumScopsDepthFive++;
5257 else
5258 NumScopsDepthLarger++;
Michael Kruse06ed5292017-08-23 13:50:30 +00005259
5260 NumAffineLoops += ScopStats.NumAffineLoops;
5261 NumBoxedLoops += ScopStats.NumBoxedLoops;
5262
5263 NumValueWrites += ScopStats.NumValueWrites;
5264 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
5265 NumPHIWrites += ScopStats.NumPHIWrites;
5266 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
5267 NumSingletonWrites += ScopStats.NumSingletonWrites;
5268 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
Tobias Grossercd01a362017-02-17 08:12:36 +00005269}
5270
Johannes Doerfert99191c72016-05-31 09:41:04 +00005271bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005272 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005273
5274 if (!SD.isMaxRegionInScop(*R))
5275 return false;
5276
5277 Function *F = R->getEntry()->getParent();
5278 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5279 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5280 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5281 auto const &DL = F->getParent()->getDataLayout();
5282 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005283 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005284 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005285
Michael Krusea4f447c2017-08-28 14:07:33 +00005286 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005287 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005288
Michael Kruse06ed5292017-08-23 13:50:30 +00005289#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Tobias Grossercd01a362017-02-17 08:12:36 +00005290 if (S) {
5291 ScopDetection::LoopStats Stats =
5292 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005293 updateLoopCountStatistic(Stats, S->getStatistics());
Tobias Grossercd01a362017-02-17 08:12:36 +00005294 }
Michael Kruse06ed5292017-08-23 13:50:30 +00005295#endif
Tobias Grossercd01a362017-02-17 08:12:36 +00005296
Tobias Grosser75805372011-04-29 06:27:02 +00005297 return false;
5298}
5299
Johannes Doerfert99191c72016-05-31 09:41:04 +00005300void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005301 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005302 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005303 else
5304 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005305}
Tobias Grosser75805372011-04-29 06:27:02 +00005306
Johannes Doerfert99191c72016-05-31 09:41:04 +00005307char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005308
Johannes Doerfert99191c72016-05-31 09:41:04 +00005309Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5310
5311INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005312 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005313 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005314INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005315INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005316INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005317INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005318INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005319INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005320INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005321INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005322 "Polly - Create polyhedral description of Scops", false,
5323 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005324
5325//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005326ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5327 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
Michael Krusea4f447c2017-08-28 14:07:33 +00005328 AssumptionCache &AC, OptimizationRemarkEmitter &ORE)
5329 : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC), ORE(ORE) {
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005330 recompute();
5331}
5332
5333void ScopInfo::recompute() {
5334 RegionToScopMap.clear();
Michael Krusea6d48f52017-06-08 12:06:15 +00005335 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005336 /// function.
5337 for (auto &It : SD) {
5338 Region *R = const_cast<Region *>(It);
5339 if (!SD.isMaxRegionInScop(*R))
5340 continue;
5341
Michael Krusea4f447c2017-08-28 14:07:33 +00005342 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005343 std::unique_ptr<Scop> S = SB.getScop();
5344 if (!S)
5345 continue;
Michael Kruse06ed5292017-08-23 13:50:30 +00005346#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Philip Pfaffeead67db2017-08-02 11:14:41 +00005347 ScopDetection::LoopStats Stats =
5348 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005349 updateLoopCountStatistic(Stats, S->getStatistics());
5350#endif
Philip Pfaffe838e0882017-05-15 12:55:14 +00005351 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5352 assert(Inserted && "Building Scop for the same region twice!");
5353 (void)Inserted;
5354 }
5355}
5356
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005357bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
5358 FunctionAnalysisManager::Invalidator &Inv) {
5359 // Check whether the analysis, all analyses on functions have been preserved
5360 // or anything we're holding references to is being invalidated
5361 auto PAC = PA.getChecker<ScopInfoAnalysis>();
5362 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
5363 Inv.invalidate<ScopAnalysis>(F, PA) ||
5364 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
5365 Inv.invalidate<LoopAnalysis>(F, PA) ||
5366 Inv.invalidate<AAManager>(F, PA) ||
5367 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
5368 Inv.invalidate<AssumptionAnalysis>(F, PA);
5369}
5370
Philip Pfaffe838e0882017-05-15 12:55:14 +00005371AnalysisKey ScopInfoAnalysis::Key;
5372
5373ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5374 FunctionAnalysisManager &FAM) {
5375 auto &SD = FAM.getResult<ScopAnalysis>(F);
5376 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5377 auto &LI = FAM.getResult<LoopAnalysis>(F);
5378 auto &AA = FAM.getResult<AAManager>(F);
5379 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5380 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5381 auto &DL = F.getParent()->getDataLayout();
Michael Krusea4f447c2017-08-28 14:07:33 +00005382 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5383 return {DL, SD, SE, LI, AA, DT, AC, ORE};
Philip Pfaffe838e0882017-05-15 12:55:14 +00005384}
5385
5386PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5387 FunctionAnalysisManager &FAM) {
5388 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
Philip Pfaffe96d21432017-08-04 11:28:51 +00005389 // Since the legacy PM processes Scops in bottom up, we print them in reverse
5390 // order here to keep the output persistent
5391 for (auto &It : reverse(SI)) {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005392 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005393 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005394 else
5395 Stream << "Invalid Scop!\n";
5396 }
5397 return PreservedAnalyses::all();
5398}
5399
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005400void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5401 AU.addRequired<LoopInfoWrapperPass>();
5402 AU.addRequired<RegionInfoPass>();
5403 AU.addRequired<DominatorTreeWrapperPass>();
5404 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005405 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005406 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005407 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00005408 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005409 AU.setPreservesAll();
5410}
5411
5412bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005413 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005414 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5415 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5416 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5417 auto const &DL = F.getParent()->getDataLayout();
5418 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005419 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005420 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005421
Michael Krusea4f447c2017-08-28 14:07:33 +00005422 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC, ORE});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005423 return false;
5424}
5425
5426void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005427 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005428 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005429 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005430 else
5431 OS << "Invalid Scop!\n";
5432 }
5433}
5434
5435char ScopInfoWrapperPass::ID = 0;
5436
5437Pass *polly::createScopInfoWrapperPassPass() {
5438 return new ScopInfoWrapperPass();
5439}
5440
5441INITIALIZE_PASS_BEGIN(
5442 ScopInfoWrapperPass, "polly-function-scops",
5443 "Polly - Create polyhedral description of all Scops of a function", false,
5444 false);
5445INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005446INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005447INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5448INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5449INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005450INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005451INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5452INITIALIZE_PASS_END(
5453 ScopInfoWrapperPass, "polly-function-scops",
5454 "Polly - Create polyhedral description of all Scops of a function", false,
5455 false)