blob: 74e23141e4b40f2cf551fbff55eef7ac55618e5d [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"
Adam Nemete0f15412017-10-09 23:49:08 +000048#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000049#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 Grosserfcc3ad52018-04-18 20:03:36 +0000129STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
Tobias Grossercd01a362017-02-17 08:12:36 +0000130STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
131STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
132STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
133STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
134STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
135STATISTIC(NumScopsDepthLarger,
136 "Number of scops with maximal loop depth 6 and larger");
137STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
138
Michael Kruse06ed5292017-08-23 13:50:30 +0000139STATISTIC(NumValueWrites, "Number of scalar value writes after ScopInfo");
140STATISTIC(
141 NumValueWritesInLoops,
142 "Number of scalar value writes nested in affine loops after ScopInfo");
143STATISTIC(NumPHIWrites, "Number of scalar phi writes after ScopInfo");
144STATISTIC(NumPHIWritesInLoops,
145 "Number of scalar phi writes nested in affine loops after ScopInfo");
146STATISTIC(NumSingletonWrites, "Number of singleton writes after ScopInfo");
147STATISTIC(NumSingletonWritesInLoops,
148 "Number of singleton writes nested in affine loops after ScopInfo");
149
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000150// The maximal number of basic sets we allow during domain construction to
151// be created. More complex scops will result in very high compile time and
152// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +0000153static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000154
Tobias Grosserc8a82762017-02-16 19:11:25 +0000155// The number of disjunct in the context after which we stop to add more
156// disjuncts. This parameter is there to avoid exponential growth in the
157// number of disjunct when adding non-convex sets to the context.
158static int const MaxDisjunctsInContext = 4;
159
Tobias Grosser1eeedf42017-07-20 19:55:19 +0000160// The maximal number of dimensions we allow during invariant load construction.
161// More complex access ranges will result in very high compile time and are also
162// unlikely to result in good code. This value is very high and should only
163// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
164static int const MaxDimensionsInAccessRange = 9;
165
Tobias Grosser97715842017-05-19 04:01:52 +0000166static cl::opt<int>
167 OptComputeOut("polly-analysis-computeout",
168 cl::desc("Bound the scop analysis by a maximal amount of "
169 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000170 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000171 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000172
Johannes Doerfert2f705842016-04-12 16:09:44 +0000173static cl::opt<bool> PollyRemarksMinimal(
174 "polly-remarks-minimal",
175 cl::desc("Do not emit remarks about assumptions that are known"),
176 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
177
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000178static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
179 "polly-rtc-max-array-disjuncts",
180 cl::desc("The maximal number of disjunts allowed in memory accesses to "
181 "to build RTCs."),
182 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
183
Johannes Doerfert9143d672014-09-27 11:02:39 +0000184static cl::opt<unsigned> RunTimeChecksMaxParameters(
185 "polly-rtc-max-parameters",
186 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
187 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
188
Tobias Grosser71500722015-03-28 15:11:14 +0000189static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
190 "polly-rtc-max-arrays-per-group",
191 cl::desc("The maximal number of arrays to compare in each alias group."),
192 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000193
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000194static cl::opt<std::string> UserContextStr(
195 "polly-context", cl::value_desc("isl parameter set"),
196 cl::desc("Provide additional constraints on the context parameters"),
197 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000198
Tobias Grosser2937b592016-04-29 11:43:20 +0000199static cl::opt<bool>
200 IslOnErrorAbort("polly-on-isl-error-abort",
201 cl::desc("Abort if an isl error is encountered"),
202 cl::init(true), cl::cat(PollyCategory));
203
Tobias Grosserd7c49752017-02-28 09:45:54 +0000204static cl::opt<bool> PollyPreciseInbounds(
205 "polly-precise-inbounds",
206 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
207 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
208
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000209static cl::opt<bool>
210 PollyIgnoreInbounds("polly-ignore-inbounds",
211 cl::desc("Do not take inbounds assumptions at all"),
212 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
213
Tobias Grosser5842dee2017-03-17 13:00:53 +0000214static cl::opt<bool> PollyIgnoreParamBounds(
215 "polly-ignore-parameter-bounds",
216 cl::desc(
217 "Do not add parameter bounds and do no gist simplify sets accordingly"),
218 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
219
Siddharth Bhat7bc77e82017-08-21 11:57:04 +0000220static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams(
221 "polly-allow-dereference-of-all-function-parameters",
222 cl::desc(
223 "Treat all parameters to functions that are pointers as dereferencible."
224 " This is useful for invariant load hoisting, since we can generate"
225 " less runtime checks. This is only valid if all pointers to functions"
226 " are always initialized, so that Polly can choose to hoist"
227 " their loads. "),
228 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
229
Tobias Grosserc2f15102017-03-01 21:11:27 +0000230static cl::opt<bool> PollyPreciseFoldAccesses(
231 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000232 cl::desc("Fold memory accesses to model more possible delinearizations "
233 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000234 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000235
Michael Kruse5ae08c02017-05-06 14:03:58 +0000236bool polly::UseInstructionNames;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000237
Michael Kruse5ae08c02017-05-06 14:03:58 +0000238static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000239 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000240 cl::desc("Use LLVM-IR names when deriving statement names"),
241 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
242 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000243
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000244static cl::opt<bool> PollyPrintInstructions(
245 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
246 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
247
Michael Kruse7bf39442015-09-10 12:46:52 +0000248//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000249
Michael Kruse046dde42015-08-10 13:01:57 +0000250// Create a sequence of two schedules. Either argument may be null and is
251// interpreted as the empty schedule. Can also return null if both schedules are
252// empty.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000253static isl::schedule combineInSequence(isl::schedule Prev, isl::schedule Succ) {
Michael Kruse046dde42015-08-10 13:01:57 +0000254 if (!Prev)
255 return Succ;
256 if (!Succ)
257 return Prev;
258
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000259 return Prev.sequence(Succ);
Michael Kruse046dde42015-08-10 13:01:57 +0000260}
261
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000262static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
263 int dim, isl::dim type) {
264 isl::val V;
265 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000266
Tobias Grosser3281f602017-02-16 18:39:14 +0000267 // The upper and lower bound for a parameter value is derived either from
268 // the data type of the parameter or from the - possibly more restrictive -
269 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000270 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
271 S = S.lower_bound_val(type, dim, V);
272 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
273 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000274
Tobias Grosser3281f602017-02-16 18:39:14 +0000275 if (Range.isFullSet())
276 return S;
277
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000278 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000279 return S;
280
Tobias Grosser3281f602017-02-16 18:39:14 +0000281 // In case of signed wrapping, we can refine the set of valid values by
282 // excluding the part not covered by the wrapping range.
283 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000284 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
285 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000286
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000287 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
288 V = V.sub_ui(1);
289 isl::set SUB = S.upper_bound_val(type, dim, V);
290 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000291 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000292
Tobias Grosser3281f602017-02-16 18:39:14 +0000293 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000294}
295
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000296static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
297 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
298 if (!BasePtrLI)
299 return nullptr;
300
Johannes Doerfert952b5302016-05-23 12:40:48 +0000301 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000302 return nullptr;
303
304 ScalarEvolution &SE = *S->getSE();
305
306 auto *OriginBaseSCEV =
307 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
308 if (!OriginBaseSCEV)
309 return nullptr;
310
311 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
312 if (!OriginBaseSCEVUnknown)
313 return nullptr;
314
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000315 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000316 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000317}
318
Tobias Grosser27db02b2017-08-06 17:25:05 +0000319ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000320 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000321 const DataLayout &DL, Scop *S,
322 const char *BaseName)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000323 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000324 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000325 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000326 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
327 Kind == MemoryKind::PHI ? "__phi" : "",
328 UseInstructionNames);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000329 Id = isl::id::alloc(Ctx, BasePtrName, this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000330
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000331 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000332
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000333 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000334 BasePtrOriginSAI = nullptr;
335 return;
336 }
337
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000338 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
339 if (BasePtrOriginSAI)
340 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000341}
342
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000343ScopArrayInfo::~ScopArrayInfo() = default;
344
Tobias Grosser77eef902017-07-21 23:07:56 +0000345isl::space ScopArrayInfo::getSpace() const {
346 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
347 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000348 return Space;
349}
350
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000351bool ScopArrayInfo::isReadOnly() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +0000352 isl::union_set WriteSet = S.getWrites().range();
Tobias Grosser77eef902017-07-21 23:07:56 +0000353 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000354 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000355
Tobias Grosser2ade9862017-05-23 06:41:04 +0000356 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000357}
358
Tobias Grosserf3adab42017-05-10 10:59:58 +0000359bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
360 if (Array->getElementType() != getElementType())
361 return false;
362
363 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
364 return false;
365
366 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
367 if (Array->getDimensionSize(i) != getDimensionSize(i))
368 return false;
369
370 return true;
371}
372
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000373void ScopArrayInfo::updateElementType(Type *NewElementType) {
374 if (NewElementType == ElementType)
375 return;
376
Tobias Grosserd840fc72016-02-04 13:18:42 +0000377 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
378 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
379
Johannes Doerferta7920982016-02-25 14:08:48 +0000380 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000381 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000382
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000383 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
384 ElementType = NewElementType;
385 } else {
386 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
387 ElementType = IntegerType::get(ElementType->getContext(), GCD);
388 }
389}
390
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000391/// Make the ScopArrayInfo model a Fortran Array
392void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
393 assert(FAD && "got invalid Fortran array descriptor");
394 if (this->FAD) {
395 assert(this->FAD == FAD &&
396 "receiving different array descriptors for same array");
397 return;
398 }
399
400 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
401 assert(!this->FAD);
402 this->FAD = FAD;
403
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000404 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000405
406 std::string param_name = getName();
407 param_name += "_fortranarr_size";
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000408 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000409
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000410 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
411 isl::pw_aff PwAff =
412 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000413
Tobias Grosser77eef902017-07-21 23:07:56 +0000414 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000415}
416
Tobias Grosserbedef002016-12-02 08:10:56 +0000417bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
418 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000419 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
420 int ExtraDimsNew = NewSizes.size() - SharedDims;
421 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000422
Tobias Grosserbedef002016-12-02 08:10:56 +0000423 if (CheckConsistency) {
424 for (int i = 0; i < SharedDims; i++) {
425 auto *NewSize = NewSizes[i + ExtraDimsNew];
426 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
427 if (NewSize && KnownSize && NewSize != KnownSize)
428 return false;
429 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000430
Tobias Grosserbedef002016-12-02 08:10:56 +0000431 if (DimensionSizes.size() >= NewSizes.size())
432 return true;
433 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000434
435 DimensionSizes.clear();
436 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
437 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000438 DimensionSizesPw.clear();
439 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000440 if (!Expr) {
441 DimensionSizesPw.push_back(nullptr);
442 continue;
443 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000444 isl::pw_aff Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000445 DimensionSizesPw.push_back(Size);
446 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000447 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000448}
449
Tobias Grosser77eef902017-07-21 23:07:56 +0000450std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000451
452int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000453 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000454}
455
Tobias Grosser77eef902017-07-21 23:07:56 +0000456isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000457
Michael Kruse5d518462017-07-21 15:54:07 +0000458#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000459LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000460#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000461
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000462void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000463 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000464 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000465 // If this is a Fortran array, then we can print the outermost dimension
466 // as a isl_pw_aff even though there is no SCEV information.
467 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
468
469 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
470 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000471 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000472 u++;
473 }
474 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000475 OS << "[";
476
Tobias Grosser26253842015-11-10 14:24:21 +0000477 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000478 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000479 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000480 } else {
481 OS << *getDimensionSize(u);
482 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000483
484 OS << "]";
485 }
486
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000487 OS << ";";
488
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000489 if (BasePtrOriginSAI)
490 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
491
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000492 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000493}
494
495const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000496ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
497 isl::id Id = PMA.get_tuple_id(isl::dim::out);
498 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000499 return getFromId(Id);
500}
501
Tobias Grosser206e9e32017-07-24 16:22:27 +0000502const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
503 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000504 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000505 return SAI;
506}
507
Michael Kruse3b425ff2016-04-11 14:34:08 +0000508void MemoryAccess::wrapConstantDimensions() {
509 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000510 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000511 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000512 unsigned DimsArray = SAI->getNumberOfDimensions();
513
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000514 isl::multi_aff DivModAff = isl::multi_aff::identity(
515 ArraySpace.map_from_domain_and_range(ArraySpace));
516 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000517
518 // Begin with last dimension, to iteratively carry into higher dimensions.
519 for (int i = DimsArray - 1; i > 0; i--) {
520 auto *DimSize = SAI->getDimensionSize(i);
521 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
522
523 // This transformation is not applicable to dimensions with dynamic size.
524 if (!DimSizeCst)
525 continue;
526
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000527 // This transformation is not applicable to dimensions of size zero.
528 if (DimSize->isZero())
529 continue;
530
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000531 isl::val DimSizeVal =
532 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
533 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
534 isl::aff PrevVar =
535 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000536
537 // Compute: index % size
538 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grossercb0224a2017-08-06 15:56:45 +0000539 isl::aff Modulo = Var.mod(DimSizeVal);
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000540 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000541
542 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000543 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
544 Divide = Divide.floor();
545 Divide = Divide.add(PrevVar);
546 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000547
548 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000549 DivModAff = DivModAff.set_aff(i, Modulo);
550 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000551 }
552
553 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000554 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000555 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
556 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000557 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000558}
559
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000560void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000561 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000562 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000563 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000564 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000565
Tobias Grosser7be82452017-05-21 20:38:33 +0000566 auto DimsArray = ArraySpace.dim(isl::dim::set);
567 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000568 auto DimsMissing = DimsArray - DimsAccess;
569
Michael Kruse375cb5f2016-02-24 22:08:24 +0000570 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000571 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000572 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000573 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000574
Tobias Grosser7be82452017-05-21 20:38:33 +0000575 isl::map Map = isl::map::from_domain_and_range(
576 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000577
578 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000579 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000580
581 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000582 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000583
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000584 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000585
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000586 // For the non delinearized arrays, divide the access function of the last
587 // subscript by the size of the elements in the array.
588 //
589 // A stride one array access in C expressed as A[i] is expressed in
590 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
591 // two subsequent values of 'i' index two values that are stored next to
592 // each other in memory. By this division we make this characteristic
593 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000594 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000595 // that divides the offsets of all accesses to this base pointer.
596 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000597 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000598 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000599 }
600
Michael Kruse3b425ff2016-04-11 14:34:08 +0000601 // We currently do this only if we added at least one dimension, which means
602 // some dimension's indices have not been specified, an indicator that some
603 // index values have been added together.
604 // TODO: Investigate general usefulness; Effect on unit tests is to make index
605 // expressions more complicated.
606 if (DimsMissing)
607 wrapConstantDimensions();
608
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000609 if (!isAffine())
610 computeBoundsOnAccessRelation(ArrayElemSize);
611
Tobias Grosserd840fc72016-02-04 13:18:42 +0000612 // Introduce multi-element accesses in case the type loaded by this memory
613 // access is larger than the canonical element type of the array.
614 //
615 // An access ((float *)A)[i] to an array char *A is modeled as
616 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000617 if (ElemBytes > ArrayElemSize) {
618 assert(ElemBytes % ArrayElemSize == 0 &&
619 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000620 isl::map Map = isl::map::from_domain_and_range(
621 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000622 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000623 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000624
Tobias Grosser7be82452017-05-21 20:38:33 +0000625 isl::constraint C;
626 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000627
Tobias Grosser7be82452017-05-21 20:38:33 +0000628 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000629 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
630
Tobias Grosser7be82452017-05-21 20:38:33 +0000631 C = isl::constraint::alloc_inequality(LS);
632 C = C.set_constant_val(isl::val(Ctx, Num - 1));
633 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
634 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
635 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000636
Tobias Grosser7be82452017-05-21 20:38:33 +0000637 C = isl::constraint::alloc_inequality(LS);
638 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
639 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
640 C = C.set_constant_val(isl::val(Ctx, 0));
641 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000642 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000643 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000644}
645
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000646const std::string
647MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
648 switch (RT) {
649 case MemoryAccess::RT_NONE:
650 llvm_unreachable("Requested a reduction operator string for a memory "
651 "access which isn't a reduction");
652 case MemoryAccess::RT_ADD:
653 return "+";
654 case MemoryAccess::RT_MUL:
655 return "*";
656 case MemoryAccess::RT_BOR:
657 return "|";
658 case MemoryAccess::RT_BXOR:
659 return "^";
660 case MemoryAccess::RT_BAND:
661 return "&";
662 }
663 llvm_unreachable("Unknown reduction type");
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000664}
665
Michael Kruse2fa35192016-09-01 19:53:31 +0000666const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000667 isl::id ArrayId = getArrayId();
668 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000669 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000670 return SAI;
671}
672
Michael Kruse2fa35192016-09-01 19:53:31 +0000673const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000674 isl::id ArrayId = getLatestArrayId();
675 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000676 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000677 return SAI;
678}
679
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000680isl::id MemoryAccess::getOriginalArrayId() const {
681 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000682}
683
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000684isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000685 if (!hasNewAccessRelation())
686 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000687 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000688}
689
Tobias Grosser6a870362017-07-23 04:08:45 +0000690isl::map MemoryAccess::getAddressFunction() const {
691 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000692}
693
Tobias Grosser3b196132017-07-23 04:08:52 +0000694isl::pw_multi_aff
695MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
696 isl::map Schedule, ScheduledAccRel;
697 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000698
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000699 UDomain = getStatement()->getDomain();
Tobias Grosser3b196132017-07-23 04:08:52 +0000700 USchedule = USchedule.intersect_domain(UDomain);
701 Schedule = isl::map::from_union_map(USchedule);
702 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
703 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000704}
705
Tobias Grosser22da5f02017-07-23 04:08:27 +0000706isl::map MemoryAccess::getOriginalAccessRelation() const {
707 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000708}
709
Johannes Doerferta99130f2014-10-13 12:58:03 +0000710std::string MemoryAccess::getOriginalAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000711 return AccessRelation.to_str();
Tobias Grosser5d453812011-10-06 00:04:11 +0000712}
713
Tobias Grosser22da5f02017-07-23 04:08:27 +0000714isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
715 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000716}
717
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000718isl::map MemoryAccess::getNewAccessRelation() const {
719 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000720}
721
Tobias Grosser6f730082015-09-05 07:46:47 +0000722std::string MemoryAccess::getNewAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000723 return NewAccessRelation.to_str();
Tobias Grosser6f730082015-09-05 07:46:47 +0000724}
725
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000726std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser2b7479b2017-08-06 11:41:10 +0000727 return getAccessRelation().to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000728}
729
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000730isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
731 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000732 Space = Space.align_params(Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000733
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000734 return isl::basic_map::from_domain_and_range(
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000735 isl::basic_set::universe(Statement->getDomainSpace()),
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000736 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000737}
738
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000739// Formalize no out-of-bound access assumption
740//
741// When delinearizing array accesses we optimistically assume that the
742// delinearized accesses do not access out of bound locations (the subscript
743// expression of each array evaluates for each statement instance that is
744// executed to a value that is larger than zero and strictly smaller than the
745// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000746// dimension for which we do not need to assume any upper bound. At this point
747// we formalize this assumption to ensure that at code generation time the
748// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000749//
750// To find the set of constraints necessary to avoid out of bound accesses, we
751// first build the set of data locations that are not within array bounds. We
752// then apply the reverse access relation to obtain the set of iterations that
753// may contain invalid accesses and reduce this set of iterations to the ones
754// that are actually executed by intersecting them with the domain of the
755// statement. If we now project out all loop dimensions, we obtain a set of
756// parameters that may cause statement instances to be executed that may
757// possibly yield out of bound memory accesses. The complement of these
758// constraints is the set of constraints that needs to be assumed to ensure such
759// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000760void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000761 if (PollyIgnoreInbounds)
762 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000763 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000764 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000765 isl::set Outside = isl::set::empty(Space);
766 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
767 isl::local_space LS(Space);
768 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
769 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000770
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000771 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000772 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000773 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
774 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
775 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000776
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000777 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000778 }
779
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000780 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000781 Outside = Outside.intersect(Statement->getDomain());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000782 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000783
784 // Remove divs to avoid the construction of overly complicated assumptions.
785 // Doing so increases the set of parameter combinations that are assumed to
786 // not appear. This is always save, but may make the resulting run-time check
787 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000788 Outside = Outside.remove_divs();
789 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000790 const auto &Loc = getAccessInstruction()
791 ? getAccessInstruction()->getDebugLoc()
792 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000793 if (!PollyPreciseInbounds)
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000794 Outside = Outside.gist_params(Statement->getDomain().params());
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000795 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000796 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000797}
798
Johannes Doerfertcea61932016-02-21 19:13:19 +0000799void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000800 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000801 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000802
Tobias Grossercdf471b2017-07-24 16:36:34 +0000803 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000804 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000805
Tobias Grosser53fc3552017-05-23 07:07:09 +0000806 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000807 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000808 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000809 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000810 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000811 LengthMap = isl::map::from_pw_aff(LengthPWA);
812 isl::space RangeSpace = LengthMap.get_space().range();
813 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000814 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000815 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
816 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
817 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
818 LengthMap = LengthMap.sum(SubscriptMap);
819 AccessRelation =
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000820 LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000821}
822
Johannes Doerferte7044942015-02-24 11:58:30 +0000823void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
824 ScalarEvolution *SE = Statement->getParent()->getSE();
825
Johannes Doerfertcea61932016-02-21 19:13:19 +0000826 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000827 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000828 return;
829
830 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000831 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
832 return;
833
834 auto *PtrSCEV = SE->getSCEV(Ptr);
835 if (isa<SCEVCouldNotCompute>(PtrSCEV))
836 return;
837
838 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
839 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
840 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
841
842 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
843 if (Range.isFullSet())
844 return;
845
Michael Kruse960c0d02017-05-18 21:55:36 +0000846 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000847 return;
848
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000849 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000850
Johannes Doerferte7044942015-02-24 11:58:30 +0000851 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000852 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000853 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000854 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000855
856 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000857 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000858
Tobias Grosserb3a85882017-02-12 08:11:12 +0000859 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
860
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000861 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000862 isl::set AccessRange = Relation.range();
863 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
864 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000865 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000866}
867
Tobias Grosser491b7992016-12-02 05:21:22 +0000868void MemoryAccess::foldAccessRelation() {
869 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
870 return;
871
Michael Krusee2bccbb2015-09-18 19:59:43 +0000872 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000873
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000874 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000875
Tobias Grosser619190d2015-03-30 17:22:28 +0000876 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000877 isl::space Space;
878 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000879 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000880
Tobias Grossera32de132017-05-23 07:22:56 +0000881 isl::space SpaceSize = DimSize.get_space();
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000882 isl::id ParamId = SpaceSize.get_dim_id(isl::dim::param, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000883
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000884 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000885 Space = Space.range().map_from_set();
886 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000887
Tobias Grossera32de132017-05-23 07:22:56 +0000888 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000889
Tobias Grossera32de132017-05-23 07:22:56 +0000890 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000891 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000892 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
893 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000894
Tobias Grossera32de132017-05-23 07:22:56 +0000895 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000896 for (int j = 0; j < Size; ++j)
897 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000898 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000899
Tobias Grossera32de132017-05-23 07:22:56 +0000900 isl::local_space LS(Space);
901 isl::constraint C;
902 C = isl::constraint::alloc_equality(LS);
903 C = C.set_constant_si(-1);
904 C = C.set_coefficient_si(isl::dim::in, i, 1);
905 C = C.set_coefficient_si(isl::dim::out, i, -1);
906 MapTwo = MapTwo.add_constraint(C);
907 C = isl::constraint::alloc_equality(LS);
908 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
909 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
910 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
911 MapTwo = MapTwo.add_constraint(C);
912 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000913
Tobias Grossera32de132017-05-23 07:22:56 +0000914 MapOne = MapOne.unite(MapTwo);
915 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000916 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000917
Tobias Grosser77eef902017-07-21 23:07:56 +0000918 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000919 isl::space Space = Statement->getDomainSpace();
Tobias Grossera32de132017-05-23 07:22:56 +0000920 NewAccessRelation = NewAccessRelation.set_tuple_id(
921 isl::dim::in, Space.get_tuple_id(isl::dim::set));
922 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000923 NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000924
925 // Access dimension folding might in certain cases increase the number of
926 // disjuncts in the memory access, which can possibly complicate the generated
927 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000928 if (!PollyPreciseFoldAccesses &&
929 isl_map_n_basic_map(NewAccessRelation.get()) >
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000930 isl_map_n_basic_map(AccessRelation.get())) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000931 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000932 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000933 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000934}
935
Tobias Grosserc80d6972016-09-02 06:33:33 +0000936/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000937static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000938 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000939 if (Size == 1)
940 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000941
942 // Only one factor needs to be divisible.
943 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
944 for (auto *FactorExpr : MulExpr->operands())
945 if (isDivisible(FactorExpr, Size, SE))
946 return true;
947 return false;
948 }
949
950 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000951 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000952 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
953 for (auto *OpExpr : NAryExpr->operands())
954 if (!isDivisible(OpExpr, Size, SE))
955 return false;
956 return true;
957 }
958
959 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
960 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
961 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
962 return MulSCEV == Expr;
963}
964
Michael Krusee2bccbb2015-09-18 19:59:43 +0000965void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000966 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000967
Johannes Doerfert85676e32016-04-23 14:32:34 +0000968 // Initialize the invalid domain which describes all iterations for which the
969 // access relation is not modeled correctly.
Tobias Grosser2332fa32017-08-06 15:36:48 +0000970 isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
Tobias Grosserb739cb42017-07-24 20:30:34 +0000971 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +0000972
Tobias Grosserb739cb42017-07-24 20:30:34 +0000973 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000974 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000975
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000976 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
977 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000978 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000979 return;
980 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000981
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000982 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000983 // We overapproximate non-affine accesses with a possible access to the
984 // whole array. For read accesses it does not make a difference, if an
985 // access must or may happen. However, for write accesses it is important to
986 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000987 if (AccessRelation.is_null())
988 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000989
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000990 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000991 return;
992 }
993
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000994 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
995 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000996
Michael Krusee2bccbb2015-09-18 19:59:43 +0000997 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000998 isl::pw_aff Affine = getPwAff(Subscripts[i]);
999 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
1000 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001001 }
1002
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001003 Space = Statement->getDomainSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001004 AccessRelation = AccessRelation.set_tuple_id(
1005 isl::dim::in, Space.get_tuple_id(isl::dim::set));
1006 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001007
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001008 AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001009}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001010
Michael Krusecac948e2015-10-02 13:53:07 +00001011MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001012 AccessType AccType, Value *BaseAddress,
1013 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001014 ArrayRef<const SCEV *> Subscripts,
1015 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001016 MemoryKind Kind)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001017 : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(nullptr),
1018 BaseAddr(BaseAddress), ElementType(ElementType),
Tobias Grosser81331282017-05-03 07:57:35 +00001019 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1020 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001021 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001022 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001023 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001024 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001025
Tobias Grosser81331282017-05-03 07:57:35 +00001026 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001027 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001028}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001029
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001030MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001031 : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
1032 InvalidDomain(nullptr), AccessRelation(nullptr),
1033 NewAccessRelation(AccRel), FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +00001034 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001035 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1036 Sizes.push_back(nullptr);
1037 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1038 Sizes.push_back(SAI->getDimensionSize(i));
1039 ElementType = SAI->getElementType();
1040 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001041 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001042 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001043
Tobias Grosser81331282017-05-03 07:57:35 +00001044 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001045 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001046}
1047
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001048MemoryAccess::~MemoryAccess() = default;
1049
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001050void MemoryAccess::realignParams() {
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001051 isl::set Ctx = Statement->getParent()->getContext();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001052 InvalidDomain = InvalidDomain.gist_params(Ctx);
1053 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001054}
1055
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001056const std::string MemoryAccess::getReductionOperatorStr() const {
1057 return MemoryAccess::getReductionOperatorStr(getReductionType());
1058}
1059
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001060isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001061
Johannes Doerfertf6183392014-07-01 20:52:51 +00001062raw_ostream &polly::operator<<(raw_ostream &OS,
1063 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001064 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001065 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001066 else
1067 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001068 return OS;
1069}
1070
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001071void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001072
Tobias Grosser75805372011-04-29 06:27:02 +00001073void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001074 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001075 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001076 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001077 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001078 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001079 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001080 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001081 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001082 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001083 break;
1084 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001085
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001086 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001087
1088 if (FAD) {
1089 OS << "[Fortran array descriptor: " << FAD->getName();
1090 OS << "] ";
1091 };
1092
Tobias Grossera535dff2015-12-13 19:59:01 +00001093 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001094 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001095 if (hasNewAccessRelation())
1096 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001097}
1098
Michael Kruse5d518462017-07-21 15:54:07 +00001099#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001100LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001101#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001102
Tobias Grossercdf471b2017-07-24 16:36:34 +00001103isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001104 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001105 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001106 isl::set StmtDom = getStatement()->getDomain();
Tobias Grossercdf471b2017-07-24 16:36:34 +00001107 StmtDom = StmtDom.reset_tuple_id();
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001108 isl::set NewInvalidDom = StmtDom.intersect(PWAC.second);
Tobias Grosserb739cb42017-07-24 20:30:34 +00001109 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001110 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001111}
1112
Tobias Grosser75805372011-04-29 06:27:02 +00001113// Create a map in the size of the provided set domain, that maps from the
1114// one element of the provided set domain to another element of the provided
1115// set domain.
1116// The mapping is limited to all points that are equal in all but the last
1117// dimension and for which the last dimension of the input is strict smaller
1118// than the last dimension of the output.
1119//
1120// getEqualAndLarger(set[i0, i1, ..., iX]):
1121//
1122// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1123// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1124//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001125static isl::map getEqualAndLarger(isl::space SetDomain) {
1126 isl::space Space = SetDomain.map_from_set();
1127 isl::map Map = isl::map::universe(Space);
1128 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001129
1130 // Set all but the last dimension to be equal for the input and output
1131 //
1132 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1133 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001134 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001135 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001136
1137 // Set the last dimension of the input to be strict smaller than the
1138 // last dimension of the output.
1139 //
1140 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001141 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001142 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001143}
1144
Tobias Grosserd7065e52017-07-24 20:50:22 +00001145isl::set MemoryAccess::getStride(isl::map Schedule) const {
1146 isl::map AccessRelation = getAccessRelation();
1147 isl::space Space = Schedule.get_space().range();
1148 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001149
Tobias Grosserd7065e52017-07-24 20:50:22 +00001150 Schedule = Schedule.reverse();
1151 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001152
Tobias Grosserd7065e52017-07-24 20:50:22 +00001153 NextScatt = NextScatt.apply_range(Schedule);
1154 NextScatt = NextScatt.apply_range(AccessRelation);
1155 NextScatt = NextScatt.apply_domain(Schedule);
1156 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001157
Tobias Grosserd7065e52017-07-24 20:50:22 +00001158 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001159 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001160}
1161
Tobias Grosserd7065e52017-07-24 20:50:22 +00001162bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1163 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001164 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001165
Sebastian Popa00a0292012-12-18 07:46:06 +00001166 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001167 StrideX = isl::set::universe(Stride.get_space());
1168 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1169 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1170 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1171 StrideWidth);
1172 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001173
Tobias Grosser28dd4862012-01-24 16:42:16 +00001174 return IsStrideX;
1175}
1176
Tobias Grosserd7065e52017-07-24 20:50:22 +00001177bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001178 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001179}
1180
Tobias Grosserd7065e52017-07-24 20:50:22 +00001181bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001182 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001183}
1184
Tobias Grosser6d588042017-08-02 19:27:16 +00001185void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1186 AccessRelation = NewAccess;
Tobias Grosserbedef002016-12-02 08:10:56 +00001187}
1188
Tobias Grosser7b45af12017-08-02 19:27:25 +00001189void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001190 assert(NewAccess);
1191
1192#ifndef NDEBUG
1193 // Check domain space compatibility.
Tobias Grosser7b45af12017-08-02 19:27:25 +00001194 isl::space NewSpace = NewAccess.get_space();
1195 isl::space NewDomainSpace = NewSpace.domain();
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001196 isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001197 assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
Michael Kruse772ce722016-09-01 19:16:58 +00001198
Michael Kruse706f79a2017-05-21 22:46:57 +00001199 // Reads must be executed unconditionally. Writes might be executed in a
1200 // subdomain only.
1201 if (isRead()) {
1202 // Check whether there is an access for every statement instance.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001203 isl::set StmtDomain = getStatement()->getDomain();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001204 StmtDomain =
1205 StmtDomain.intersect_params(getStatement()->getParent()->getContext());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001206 isl::set NewDomain = NewAccess.domain();
1207 assert(StmtDomain.is_subset(NewDomain) &&
Michael Kruse706f79a2017-05-21 22:46:57 +00001208 "Partial READ accesses not supported");
Michael Kruse706f79a2017-05-21 22:46:57 +00001209 }
Michael Kruse772ce722016-09-01 19:16:58 +00001210
Tobias Grosser7b45af12017-08-02 19:27:25 +00001211 isl::space NewAccessSpace = NewAccess.get_space();
1212 assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
Michael Kruse772ce722016-09-01 19:16:58 +00001213 "Must specify the array that is accessed");
Tobias Grosser7b45af12017-08-02 19:27:25 +00001214 isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1215 auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
Michael Kruse772ce722016-09-01 19:16:58 +00001216 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001217
1218 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1219 InvariantEquivClassTy *EqClass =
1220 getStatement()->getParent()->lookupInvariantEquivClass(
1221 SAI->getBasePtr());
1222 assert(EqClass &&
1223 "Access functions to indirect arrays must have an invariant and "
1224 "hoisted base pointer");
1225 }
1226
1227 // Check whether access dimensions correspond to number of dimensions of the
1228 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001229 auto Dims = SAI->getNumberOfDimensions();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001230 assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
Michael Kruse772ce722016-09-01 19:16:58 +00001231 "Access dims must match array dims");
Michael Kruse772ce722016-09-01 19:16:58 +00001232#endif
1233
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001234 NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001235 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001236}
Tobias Grosser75805372011-04-29 06:27:02 +00001237
Michael Kruse706f79a2017-05-21 22:46:57 +00001238bool MemoryAccess::isLatestPartialAccess() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001239 isl::set StmtDom = getStatement()->getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001240 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001241
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00001242 return !StmtDom.is_subset(AccDom);
Michael Kruse706f79a2017-05-21 22:46:57 +00001243}
1244
Tobias Grosser75805372011-04-29 06:27:02 +00001245//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001246
Tobias Grosser6ad16402017-08-06 17:45:28 +00001247isl::map ScopStmt::getSchedule() const {
Tobias Grosser1e09c132017-08-14 06:49:06 +00001248 isl::set Domain = getDomain();
1249 if (Domain.is_empty())
1250 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1251 auto Schedule = getParent()->getSchedule();
1252 if (!Schedule)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001253 return nullptr;
Tobias Grosser1e09c132017-08-14 06:49:06 +00001254 Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1255 if (Schedule.is_empty())
1256 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1257 isl::map M = M.from_union_map(Schedule);
1258 M = M.coalesce();
1259 M = M.gist_domain(Domain);
1260 M = M.coalesce();
1261 return M;
Tobias Grosser808cd692015-07-14 09:33:13 +00001262}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001263
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001264void ScopStmt::restrictDomain(isl::set NewDomain) {
1265 assert(NewDomain.is_subset(Domain) &&
Tobias Grosser37eb4222014-02-20 21:43:54 +00001266 "New domain is not a subset of old domain!");
Tobias Grosser37eb4222014-02-20 21:43:54 +00001267 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001268}
1269
Michael Kruse70af4f52017-08-07 18:40:29 +00001270void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
Michael Krusecac948e2015-10-02 13:53:07 +00001271 Instruction *AccessInst = Access->getAccessInstruction();
1272
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001273 if (Access->isArrayKind()) {
1274 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1275 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001276 } else if (Access->isValueKind() && Access->isWrite()) {
1277 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse436db622016-01-26 13:33:10 +00001278 assert(!ValueWrites.lookup(AccessVal));
1279
1280 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001281 } else if (Access->isValueKind() && Access->isRead()) {
1282 Value *AccessVal = Access->getAccessValue();
1283 assert(!ValueReads.lookup(AccessVal));
1284
1285 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001286 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001287 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001288 assert(!PHIWrites.lookup(PHI));
1289
1290 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001291 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1292 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1293 assert(!PHIReads.lookup(PHI));
1294
1295 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001296 }
1297
Michael Kruse70af4f52017-08-07 18:40:29 +00001298 if (Prepend) {
1299 MemAccs.insert(MemAccs.begin(), Access);
1300 return;
1301 }
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001302 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001303}
1304
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001305void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001306 for (MemoryAccess *MA : *this)
1307 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001308
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001309 isl::set Ctx = Parent.getContext();
Tobias Grosser2332fa32017-08-06 15:36:48 +00001310 InvalidDomain = InvalidDomain.gist_params(Ctx);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001311 Domain = Domain.gist_params(Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001312}
1313
Tobias Grosserc80d6972016-09-02 06:33:33 +00001314/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001315static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1316 void *User) {
1317 isl_set **BoundedParts = static_cast<isl_set **>(User);
1318 if (isl_basic_set_is_bounded(BSet))
1319 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1320 else
1321 isl_basic_set_free(BSet);
1322 return isl_stat_ok;
1323}
1324
Tobias Grosserc80d6972016-09-02 06:33:33 +00001325/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001326static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1327 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1328 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1329 isl_set_free(S);
1330 return BoundedParts;
1331}
1332
Tobias Grosserc80d6972016-09-02 06:33:33 +00001333/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001334///
1335/// @returns A separation of @p S into first an unbounded then a bounded subset,
1336/// both with regards to the dimension @p Dim.
1337static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1338partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001339 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001340 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001341
1342 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001343 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001344
1345 // Remove dimensions that are greater than Dim as they are not interesting.
1346 assert(NumDimsS >= Dim + 1);
1347 OnlyDimS =
1348 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1349
1350 // Create artificial parametric upper bounds for dimensions smaller than Dim
1351 // as we are not interested in them.
1352 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1353 for (unsigned u = 0; u < Dim; u++) {
1354 isl_constraint *C = isl_inequality_alloc(
1355 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1356 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1357 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1358 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1359 }
1360
1361 // Collect all bounded parts of OnlyDimS.
1362 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1363
1364 // Create the dimensions greater than Dim again.
1365 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1366 NumDimsS - Dim - 1);
1367
1368 // Remove the artificial upper bound parameters again.
1369 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1370
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001371 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001372 return std::make_pair(UnboundedParts, BoundedParts);
1373}
1374
Tobias Grosserc80d6972016-09-02 06:33:33 +00001375/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001376static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001377 __isl_take isl_pw_aff *L,
1378 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001379 switch (Pred) {
1380 case ICmpInst::ICMP_EQ:
1381 return isl_pw_aff_eq_set(L, R);
1382 case ICmpInst::ICMP_NE:
1383 return isl_pw_aff_ne_set(L, R);
1384 case ICmpInst::ICMP_SLT:
1385 return isl_pw_aff_lt_set(L, R);
1386 case ICmpInst::ICMP_SLE:
1387 return isl_pw_aff_le_set(L, R);
1388 case ICmpInst::ICMP_SGT:
1389 return isl_pw_aff_gt_set(L, R);
1390 case ICmpInst::ICMP_SGE:
1391 return isl_pw_aff_ge_set(L, R);
1392 case ICmpInst::ICMP_ULT:
1393 return isl_pw_aff_lt_set(L, R);
1394 case ICmpInst::ICMP_UGT:
1395 return isl_pw_aff_gt_set(L, R);
1396 case ICmpInst::ICMP_ULE:
1397 return isl_pw_aff_le_set(L, R);
1398 case ICmpInst::ICMP_UGE:
1399 return isl_pw_aff_ge_set(L, R);
1400 default:
1401 llvm_unreachable("Non integer predicate not supported");
1402 }
1403}
1404
Michael Kruse476f8552017-06-29 12:47:41 +00001405/// Compute the isl representation for the SCEV @p E in this BB.
1406///
1407/// @param S The Scop in which @p BB resides in.
1408/// @param BB The BB for which isl representation is to be
1409/// computed.
1410/// @param InvalidDomainMap A map of BB to their invalid domains.
1411/// @param E The SCEV that should be translated.
1412/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1413///
1414/// Note that this function will also adjust the invalid context accordingly.
1415
1416__isl_give isl_pw_aff *
1417getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001418 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1419 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001420 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001421 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(PWAC.second);
Tobias Grosser8dae41a2018-04-29 00:57:38 +00001422 return PWAC.first.release();
Michael Kruse476f8552017-06-29 12:47:41 +00001423}
1424
Tobias Grosserc80d6972016-09-02 06:33:33 +00001425/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001426///
1427/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001428/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1429/// have as many elements as @p SI has successors.
Tobias Grosseree457592017-09-24 09:25:30 +00001430bool buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1431 __isl_keep isl_set *Domain,
1432 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1433 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001434 Value *Condition = getConditionFromTerminator(SI);
1435 assert(Condition && "No condition for switch");
1436
1437 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001438 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001439 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001440
1441 unsigned NumSuccessors = SI->getNumSuccessors();
1442 ConditionSets.resize(NumSuccessors);
1443 for (auto &Case : SI->cases()) {
1444 unsigned Idx = Case.getSuccessorIndex();
1445 ConstantInt *CaseValue = Case.getCaseValue();
1446
Michael Kruse476f8552017-06-29 12:47:41 +00001447 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001448 isl_set *CaseConditionSet =
Tobias Grosserb9486302018-03-03 19:27:54 +00001449 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001450 ConditionSets[Idx] = isl_set_coalesce(
1451 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1452 }
1453
1454 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1455 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1456 for (unsigned u = 2; u < NumSuccessors; u++)
1457 ConditionSetUnion =
1458 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
Tobias Grosserb9486302018-03-03 19:27:54 +00001459 ConditionSets[0] = isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001460
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001461 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001462
1463 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001464}
1465
Michael Kruse08655852017-07-20 12:37:02 +00001466/// Build condition sets for unsigned ICmpInst(s).
1467/// Special handling is required for unsigned operands to ensure that if
1468/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1469/// it should wrap around.
1470///
1471/// @param IsStrictUpperBound holds information on the predicate relation
1472/// between TestVal and UpperBound, i.e,
1473/// TestVal < UpperBound OR TestVal <= UpperBound
Tobias Grosseree457592017-09-24 09:25:30 +00001474__isl_give isl_set *
Michael Kruse08655852017-07-20 12:37:02 +00001475buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1476 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1477 const SCEV *SCEV_UpperBound,
1478 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1479 bool IsStrictUpperBound) {
Michael Kruse08655852017-07-20 12:37:02 +00001480 // Do not take NonNeg assumption on TestVal
1481 // as it might have MSB (Sign bit) set.
1482 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1483 // Take NonNeg assumption on UpperBound.
1484 isl_pw_aff *UpperBound =
1485 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1486
1487 // 0 <= TestVal
1488 isl_set *First =
1489 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1490 isl_pw_aff_get_domain_space(TestVal))),
1491 isl_pw_aff_copy(TestVal));
1492
1493 isl_set *Second;
1494 if (IsStrictUpperBound)
1495 // TestVal < UpperBound
1496 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1497 else
1498 // TestVal <= UpperBound
1499 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1500
1501 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
Michael Kruse08655852017-07-20 12:37:02 +00001502 return ConsequenceCondSet;
1503}
1504
Tobias Grosserc80d6972016-09-02 06:33:33 +00001505/// Build the conditions sets for the branch condition @p Condition in
1506/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001507///
1508/// This will fill @p ConditionSets with the conditions under which control
1509/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001510/// have as many elements as @p TI has successors. If @p TI is nullptr the
1511/// context under which @p Condition is true/false will be returned as the
1512/// new elements of @p ConditionSets.
Tobias Grosseree457592017-09-24 09:25:30 +00001513bool buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1514 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1515 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1516 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Tobias Grosser5e531df2017-09-25 20:27:15 +00001517 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001518 isl_set *ConsequenceCondSet = nullptr;
Tobias Grosser0a62b2d2017-09-25 16:37:15 +00001519
Tobias Grosser5e531df2017-09-25 20:27:15 +00001520 if (auto Load = dyn_cast<LoadInst>(Condition)) {
1521 const SCEV *LHSSCEV = SE.getSCEVAtScope(Load, L);
1522 const SCEV *RHSSCEV = SE.getZero(LHSSCEV->getType());
1523 bool NonNeg = false;
1524 isl_pw_aff *LHS = getPwAff(S, BB, InvalidDomainMap, LHSSCEV, NonNeg);
1525 isl_pw_aff *RHS = getPwAff(S, BB, InvalidDomainMap, RHSSCEV, NonNeg);
Tobias Grosserb9486302018-03-03 19:27:54 +00001526 ConsequenceCondSet = buildConditionSet(ICmpInst::ICMP_SLE, LHS, RHS);
Tobias Grosser5e531df2017-09-25 20:27:15 +00001527 } else if (auto *PHI = dyn_cast<PHINode>(Condition)) {
Tobias Grosser0a62b2d2017-09-25 16:37:15 +00001528 auto *Unique = dyn_cast<ConstantInt>(
1529 getUniqueNonErrorValue(PHI, &S.getRegion(), *S.getLI(), *S.getDT()));
1530
1531 if (Unique->isZero())
1532 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1533 else
1534 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1535 } else if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001536 if (CCond->isZero())
1537 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1538 else
1539 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1540 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1541 auto Opcode = BinOp->getOpcode();
1542 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1543
Michael Kruse476f8552017-06-29 12:47:41 +00001544 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1545 InvalidDomainMap, ConditionSets) &&
1546 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1547 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001548 if (!Valid) {
1549 while (!ConditionSets.empty())
1550 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001551 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001552 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001553
1554 isl_set_free(ConditionSets.pop_back_val());
1555 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1556 isl_set_free(ConditionSets.pop_back_val());
1557 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1558
1559 if (Opcode == Instruction::And)
1560 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1561 else
1562 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1563 } else {
1564 auto *ICond = dyn_cast<ICmpInst>(Condition);
1565 assert(ICond &&
1566 "Condition of exiting branch was neither constant nor ICmp!");
1567
Tobias Grosseree457592017-09-24 09:25:30 +00001568 LoopInfo &LI = *S.getLI();
1569 DominatorTree &DT = *S.getDT();
1570 Region &R = S.getRegion();
1571
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001572 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001573 // For unsigned comparisons we assumed the signed bit of neither operand
1574 // to be set. The comparison is equal to a signed comparison under this
1575 // assumption.
1576 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001577 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1578 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1579
Tobias Grosseree457592017-09-24 09:25:30 +00001580 LeftOperand = tryForwardThroughPHI(LeftOperand, R, SE, LI, DT);
1581 RightOperand = tryForwardThroughPHI(RightOperand, R, SE, LI, DT);
1582
Michael Kruse08655852017-07-20 12:37:02 +00001583 switch (ICond->getPredicate()) {
1584 case ICmpInst::ICMP_ULT:
1585 ConsequenceCondSet =
1586 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1587 RightOperand, InvalidDomainMap, true);
1588 break;
1589 case ICmpInst::ICMP_ULE:
1590 ConsequenceCondSet =
1591 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1592 RightOperand, InvalidDomainMap, false);
1593 break;
1594 case ICmpInst::ICMP_UGT:
1595 ConsequenceCondSet =
1596 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1597 LeftOperand, InvalidDomainMap, true);
1598 break;
1599 case ICmpInst::ICMP_UGE:
1600 ConsequenceCondSet =
1601 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1602 LeftOperand, InvalidDomainMap, false);
1603 break;
1604 default:
1605 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1606 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
Tobias Grosserb9486302018-03-03 19:27:54 +00001607 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
Michael Kruse08655852017-07-20 12:37:02 +00001608 break;
1609 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001610 }
1611
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001612 // If no terminator was given we are only looking for parameter constraints
1613 // under which @p Condition is true/false.
1614 if (!TI)
1615 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001616 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001617 ConsequenceCondSet = isl_set_coalesce(
1618 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001619
Johannes Doerfertb2885792016-04-26 09:20:41 +00001620 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001621 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001622 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001623
Michael Krusef7a4a942016-05-02 12:25:36 +00001624 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001625 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1626 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001627 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001628 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001629 }
1630
Michael Krusef7a4a942016-05-02 12:25:36 +00001631 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001632 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1633 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001634 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001635 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001636 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001637 }
1638
1639 ConditionSets.push_back(ConsequenceCondSet);
1640 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001641
1642 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001643}
1644
Tobias Grosserc80d6972016-09-02 06:33:33 +00001645/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001646///
1647/// This will fill @p ConditionSets with the conditions under which control
1648/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1649/// have as many elements as @p TI has successors.
Tobias Grosseree457592017-09-24 09:25:30 +00001650bool buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1651 __isl_keep isl_set *Domain,
1652 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1653 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001654 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001655 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1656 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001657
1658 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1659
1660 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001661 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001662 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001663 }
1664
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001665 Value *Condition = getConditionFromTerminator(TI);
1666 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001667
Michael Kruse476f8552017-06-29 12:47:41 +00001668 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1669 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001670}
1671
Michael Krused6e22082018-01-18 15:15:38 +00001672ScopStmt::ScopStmt(Scop &parent, Region &R, StringRef Name,
1673 Loop *SurroundingLoop,
Tobias Grosserbd15d132017-08-31 03:15:56 +00001674 std::vector<Instruction *> EntryBlockInstructions)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001675 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), R(&R),
Michael Krused6e22082018-01-18 15:15:38 +00001676 Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1677 Instructions(EntryBlockInstructions) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001678
Michael Krused6e22082018-01-18 15:15:38 +00001679ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, StringRef Name,
1680 Loop *SurroundingLoop,
1681 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001682 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Krused6e22082018-01-18 15:15:38 +00001683 Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1684 Instructions(Instructions) {}
Michael Krusecac948e2015-10-02 13:53:07 +00001685
Tobias Grosser85048ef2017-08-06 17:24:59 +00001686ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1687 isl::set NewDomain)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001688 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain),
1689 Build(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001690 BaseName = getIslCompatibleName("CopyStmt_", "",
1691 std::to_string(parent.getCopyStmtsNum()));
Tobias Grosser85048ef2017-08-06 17:24:59 +00001692 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1693 Domain = Domain.set_tuple_id(Id);
1694 TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1695 auto *Access =
1696 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001697 parent.addAccessFunction(Access);
1698 addAccess(Access);
Tobias Grosser85048ef2017-08-06 17:24:59 +00001699 SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1700 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001701 parent.addAccessFunction(Access);
1702 addAccess(Access);
1703}
1704
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001705ScopStmt::~ScopStmt() = default;
1706
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001707std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001708
Tobias Grosser54839312015-04-21 11:37:25 +00001709std::string ScopStmt::getScheduleStr() const {
Tobias Grosser6ad16402017-08-06 17:45:28 +00001710 auto *S = getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001711 if (!S)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001712 return {};
Tobias Grosser808cd692015-07-14 09:33:13 +00001713 auto Str = stringFromIslObj(S);
1714 isl_map_free(S);
1715 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001716}
1717
Tobias Grosser2332fa32017-08-06 15:36:48 +00001718void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
Johannes Doerfert7c013572016-04-12 09:57:34 +00001719
Michael Kruse375cb5f2016-02-24 22:08:24 +00001720BasicBlock *ScopStmt::getEntryBlock() const {
1721 if (isBlockStmt())
1722 return getBasicBlock();
1723 return getRegion()->getEntry();
1724}
1725
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001726unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001727
Tobias Grosser75805372011-04-29 06:27:02 +00001728const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1729
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001730Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001731 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001732}
1733
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001734isl::ctx ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001735
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001736isl::set ScopStmt::getDomain() const { return Domain; }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001737
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001738isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001739
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001740isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001741
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001742void ScopStmt::printInstructions(raw_ostream &OS) const {
1743 OS << "Instructions {\n";
1744
1745 for (Instruction *Inst : Instructions)
1746 OS.indent(16) << *Inst << "\n";
1747
Michael Krusee52ebd12017-07-22 16:44:39 +00001748 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001749}
1750
Michael Krusecd4c9772017-07-21 15:35:53 +00001751void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001752 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001753 OS.indent(12) << "Domain :=\n";
1754
1755 if (Domain) {
1756 OS.indent(16) << getDomainStr() << ";\n";
1757 } else
1758 OS.indent(16) << "n/a\n";
1759
Tobias Grosser54839312015-04-21 11:37:25 +00001760 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001761
1762 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001763 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001764 } else
1765 OS.indent(16) << "n/a\n";
1766
Tobias Grosser083d3d32014-06-28 08:59:45 +00001767 for (MemoryAccess *Access : MemAccs)
1768 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001769
Tobias Grosserbd15d132017-08-31 03:15:56 +00001770 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001771 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001772}
1773
Michael Kruse5d518462017-07-21 15:54:07 +00001774#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001775LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001776#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001777
Michael Krusee60eca72017-05-11 22:56:12 +00001778void ScopStmt::removeAccessData(MemoryAccess *MA) {
1779 if (MA->isRead() && MA->isOriginalValueKind()) {
1780 bool Found = ValueReads.erase(MA->getAccessValue());
1781 (void)Found;
1782 assert(Found && "Expected access data not found");
1783 }
1784 if (MA->isWrite() && MA->isOriginalValueKind()) {
1785 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1786 (void)Found;
1787 assert(Found && "Expected access data not found");
1788 }
1789 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1790 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1791 (void)Found;
1792 assert(Found && "Expected access data not found");
1793 }
Michael Kruse3562f272017-07-20 16:47:57 +00001794 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
1795 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1796 (void)Found;
1797 assert(Found && "Expected access data not found");
1798 }
Michael Krusee60eca72017-05-11 22:56:12 +00001799}
1800
Michael Kruse10071822016-05-23 14:45:58 +00001801void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001802 // Remove the memory accesses from this statement together with all scalar
1803 // accesses that were caused by it. MemoryKind::Value READs have no access
1804 // instruction, hence would not be removed by this function. However, it is
1805 // only used for invariant LoadInst accesses, its arguments are always affine,
1806 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1807 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001808 auto Predicate = [&](MemoryAccess *Acc) {
1809 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1810 };
Michael Krusee60eca72017-05-11 22:56:12 +00001811 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00001812 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00001813 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00001814 Parent.removeAccessData(MA);
1815 }
Michael Krusee60eca72017-05-11 22:56:12 +00001816 }
Michael Kruse10071822016-05-23 14:45:58 +00001817 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1818 MemAccs.end());
1819 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001820}
1821
Michael Kruse192e7f72018-04-09 23:13:05 +00001822void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA, bool AfterHoisting) {
1823 if (AfterHoisting) {
1824 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1825 assert(MAIt != MemAccs.end());
1826 MemAccs.erase(MAIt);
Michael Kruse0446d812017-03-10 16:05:24 +00001827
Michael Kruse192e7f72018-04-09 23:13:05 +00001828 removeAccessData(MA);
1829 Parent.removeAccessData(MA);
1830 }
Michael Krusee60eca72017-05-11 22:56:12 +00001831
Michael Kruse0446d812017-03-10 16:05:24 +00001832 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1833 if (It != InstructionToAccess.end()) {
1834 It->second.remove(MA);
1835 if (It->second.empty())
1836 InstructionToAccess.erase(MA->getAccessInstruction());
1837 }
1838}
1839
Michael Kruse07e8c362017-07-24 12:43:27 +00001840MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
1841 MemoryAccess *Access = lookupInputAccessOf(V);
1842 if (Access)
1843 return Access;
1844
1845 ScopArrayInfo *SAI =
1846 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
1847 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
1848 true, {}, {}, V, MemoryKind::Value);
1849 Parent.addAccessFunction(Access);
1850 Access->buildAccessRelation(SAI);
1851 addAccess(Access);
1852 Parent.addAccessData(Access);
1853 return Access;
1854}
1855
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001856raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
1857 S.print(OS, PollyPrintInstructions);
1858 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00001859}
1860
Tobias Grosser75805372011-04-29 06:27:02 +00001861//===----------------------------------------------------------------------===//
1862/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001863
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001864void Scop::setContext(isl::set NewContext) {
1865 Context = NewContext.align_params(Context.get_space());
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001866}
1867
Eli Friedman5e589ea2017-06-20 22:53:02 +00001868namespace {
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001869
Tobias Grosserc80d6972016-09-02 06:33:33 +00001870/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001871struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001872 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001873 const ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001874
1875public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001876 SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
1877 ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001878 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001879
1880 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001881 const ValueToValueMap &VMap) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001882 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1883 return SSPR.visit(E);
1884 }
1885
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001886 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1887 auto *Start = visit(E->getStart());
1888 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1889 visit(E->getStepRecurrence(SE)),
1890 E->getLoop(), SCEV::FlagAnyWrap);
1891 return SE.getAddExpr(Start, AddRec);
1892 }
1893
1894 const SCEV *visitUnknown(const SCEVUnknown *E) {
1895 if (auto *NewValue = VMap.lookup(E->getValue()))
1896 return SE.getUnknown(NewValue);
1897 return E;
1898 }
1899};
1900
Eli Friedman5e589ea2017-06-20 22:53:02 +00001901/// Check whether we should remap a SCEV expression.
1902struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001903 const ValueToValueMap &VMap;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001904 bool FoundInside = false;
Tobias Grosserb5563c62017-08-03 13:51:15 +00001905 const Scop *S;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001906
1907public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001908 SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
1909 const Scop *S)
Eli Friedman5e589ea2017-06-20 22:53:02 +00001910 : SCEVTraversal(*this), VMap(VMap), S(S) {}
1911
1912 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001913 const ValueToValueMap &VMap, const Scop *S) {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001914 SCEVFindInsideScop SFIS(VMap, SE, S);
1915 SFIS.visitAll(E);
1916 return SFIS.FoundInside;
1917 }
1918
1919 bool follow(const SCEV *E) {
1920 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
1921 FoundInside |= S->getRegion().contains(AddRec->getLoop());
1922 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
1923 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
1924 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
1925 }
1926 return !FoundInside;
1927 }
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001928
Eli Friedman5e589ea2017-06-20 22:53:02 +00001929 bool isDone() { return FoundInside; }
1930};
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001931} // end anonymous namespace
Eli Friedman5e589ea2017-06-20 22:53:02 +00001932
Tobias Grosserb5563c62017-08-03 13:51:15 +00001933const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001934 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
1935 // doesn't like addition between an AddRec and an expression that
1936 // doesn't have a dominance relationship with it.)
1937 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
1938 return E;
1939
1940 // Rewrite SCEV.
1941 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001942}
1943
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001944// This table of function names is used to translate parameter names in more
1945// human-readable names. This makes it easier to interpret Polly analysis
1946// results.
1947StringMap<std::string> KnownNames = {
1948 {"_Z13get_global_idj", "global_id"},
1949 {"_Z12get_local_idj", "local_id"},
1950 {"_Z15get_global_sizej", "global_size"},
1951 {"_Z14get_local_sizej", "local_size"},
1952 {"_Z12get_work_dimv", "work_dim"},
1953 {"_Z17get_global_offsetj", "global_offset"},
1954 {"_Z12get_group_idj", "group_id"},
1955 {"_Z14get_num_groupsj", "num_groups"},
1956};
1957
1958static std::string getCallParamName(CallInst *Call) {
1959 std::string Result;
1960 raw_string_ostream OS(Result);
1961 std::string Name = Call->getCalledFunction()->getName();
1962
1963 auto Iterator = KnownNames.find(Name);
1964 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00001965 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001966 OS << Name;
1967 for (auto &Operand : Call->arg_operands()) {
1968 ConstantInt *Op = cast<ConstantInt>(&Operand);
1969 OS << "_" << Op->getValue();
1970 }
1971 OS.flush();
1972 return Result;
1973}
1974
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001975void Scop::createParameterId(const SCEV *Parameter) {
1976 assert(Parameters.count(Parameter));
1977 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001978
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001979 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001980
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001981 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1982 Value *Val = ValueParameter->getValue();
1983 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001984
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001985 if (Call && isConstCall(Call)) {
1986 ParameterName = getCallParamName(Call);
1987 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001988 // If this parameter references a specific Value and this value has a name
1989 // we use this name as it is likely to be unique and more useful than just
1990 // a number.
1991 if (Val->hasName())
1992 ParameterName = Val->getName();
1993 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1994 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1995 if (LoadOrigin->hasName()) {
1996 ParameterName += "_loaded_from_";
1997 ParameterName +=
1998 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1999 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002000 }
2001 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002002
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002003 ParameterName = getIslCompatibleName("", ParameterName, "");
2004 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002005
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002006 isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002007 const_cast<void *>((const void *)Parameter));
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002008 ParameterIds[Parameter] = Id;
2009}
2010
2011void Scop::addParams(const ParameterSetTy &NewParameters) {
2012 for (const SCEV *Parameter : NewParameters) {
2013 // Normalize the SCEV to get the representing element for an invariant load.
2014 Parameter = extractConstantFactor(Parameter, *SE).second;
2015 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2016
2017 if (Parameters.insert(Parameter))
2018 createParameterId(Parameter);
2019 }
2020}
2021
Tobias Grosser9a635702017-08-06 19:31:27 +00002022isl::id Scop::getIdForParam(const SCEV *Parameter) const {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002023 // Normalize the SCEV to get the representing element for an invariant load.
2024 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002025 return ParameterIds.lookup(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00002026}
Tobias Grosser75805372011-04-29 06:27:02 +00002027
Tobias Grosser232fdad2017-08-06 20:19:26 +00002028isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002029 isl_set *DomainContext = isl_union_set_params(getDomains().release());
Tobias Grosser232fdad2017-08-06 20:19:26 +00002030 return isl::manage(isl_set_intersect_params(C.release(), DomainContext));
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002031}
2032
Johannes Doerferte0b08072016-05-23 12:43:44 +00002033bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2034 return DT.dominates(BB, getEntry());
2035}
2036
Michael Kruse476f8552017-06-29 12:47:41 +00002037void Scop::addUserAssumptions(
2038 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002039 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002040 for (auto &Assumption : AC.assumptions()) {
2041 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2042 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002043 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002044
Michael Kruse89b1f942017-03-17 13:56:53 +00002045 bool InScop = contains(CI);
2046 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2047 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002048
Michael Kruse89b1f942017-03-17 13:56:53 +00002049 auto *L = LI.getLoopFor(CI->getParent());
2050 auto *Val = CI->getArgOperand(0);
2051 ParameterSetTy DetectedParams;
2052 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002053 ORE.emit(
2054 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2055 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002056 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002057 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002058
2059 // Collect all newly introduced parameters.
2060 ParameterSetTy NewParams;
2061 for (auto *Param : DetectedParams) {
2062 Param = extractConstantFactor(Param, *SE).second;
2063 Param = getRepresentingInvariantLoadSCEV(Param);
2064 if (Parameters.count(Param))
2065 continue;
2066 NewParams.insert(Param);
2067 }
2068
2069 SmallVector<isl_set *, 2> ConditionSets;
2070 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
Michael Kruse1df1aac2017-07-26 13:25:28 +00002071 BasicBlock *BB = InScop ? CI->getParent() : getRegion().getEntry();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002072 auto *Dom = InScop ? DomainMap[BB].copy() : Context.copy();
Michael Kruse1df1aac2017-07-26 13:25:28 +00002073 assert(Dom && "Cannot propagate a nullptr.");
2074 bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2075 InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002076 isl_set_free(Dom);
2077
2078 if (!Valid)
2079 continue;
2080
2081 isl_set *AssumptionCtx = nullptr;
2082 if (InScop) {
2083 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2084 isl_set_free(ConditionSets[0]);
2085 } else {
2086 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2087 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2088 }
2089
2090 // Project out newly introduced parameters as they are not otherwise useful.
2091 if (!NewParams.empty()) {
2092 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2093 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2094 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2095 isl_id_free(Id);
2096
2097 if (!NewParams.count(Param))
2098 continue;
2099
2100 AssumptionCtx =
2101 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2102 }
2103 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002104 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2105 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002106 Context = Context.intersect(isl::manage(AssumptionCtx));
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002107 }
2108}
2109
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002110void Scop::addUserContext() {
2111 if (UserContextStr.empty())
2112 return;
2113
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002114 isl_set *UserContext =
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002115 isl_set_read_from_str(getIslCtx().get(), UserContextStr.c_str());
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002116 isl_space *Space = getParamSpace().release();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002117 if (isl_space_dim(Space, isl_dim_param) !=
2118 isl_set_dim(UserContext, isl_dim_param)) {
2119 auto SpaceStr = isl_space_to_str(Space);
2120 errs() << "Error: the context provided in -polly-context has not the same "
2121 << "number of dimensions than the computed context. Due to this "
2122 << "mismatch, the -polly-context option is ignored. Please provide "
2123 << "the context in the parameter space: " << SpaceStr << ".\n";
2124 free(SpaceStr);
2125 isl_set_free(UserContext);
2126 isl_space_free(Space);
2127 return;
2128 }
2129
2130 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002131 std::string NameContext = Context.get_dim_name(isl::dim::param, i);
2132 std::string NameUserContext =
2133 isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002134
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002135 if (NameContext != NameUserContext) {
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002136 auto SpaceStr = isl_space_to_str(Space);
2137 errs() << "Error: the name of dimension " << i
2138 << " provided in -polly-context "
2139 << "is '" << NameUserContext << "', but the name in the computed "
2140 << "context is '" << NameContext
2141 << "'. Due to this name mismatch, "
2142 << "the -polly-context option is ignored. Please provide "
2143 << "the context in the parameter space: " << SpaceStr << ".\n";
2144 free(SpaceStr);
2145 isl_set_free(UserContext);
2146 isl_space_free(Space);
2147 return;
2148 }
2149
2150 UserContext =
2151 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2152 isl_space_get_dim_id(Space, isl_dim_param, i));
2153 }
2154
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002155 Context = Context.intersect(isl::manage(UserContext));
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002156 isl_space_free(Space);
2157}
2158
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002159void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002160 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002161
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002162 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002163 for (LoadInst *LInst : RIL) {
2164 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2165
Johannes Doerfert96e54712016-02-07 17:30:13 +00002166 Type *Ty = LInst->getType();
2167 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002168 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002169 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002170 continue;
2171 }
2172
2173 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002174 InvariantEquivClasses.emplace_back(
2175 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002176 }
2177}
2178
Tobias Grosser6be480c2011-11-08 15:41:13 +00002179void Scop::buildContext() {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002180 isl::space Space = isl::space::params_alloc(getIslCtx(), 0);
2181 Context = isl::set::universe(Space);
2182 InvalidContext = isl::set::empty(Space);
2183 AssumedContext = isl::set::universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002184}
2185
Tobias Grosser18daaca2012-05-22 10:47:27 +00002186void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002187 unsigned PDim = 0;
2188 for (auto *Parameter : Parameters) {
2189 ConstantRange SRange = SE->getSignedRange(Parameter);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002190 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl::dim::param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002191 }
2192}
2193
Tobias Grosserb5563c62017-08-03 13:51:15 +00002194static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
2195 std::vector<isl::id> OutermostSizeIds;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002196 for (auto Array : Arrays) {
2197 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2198 // for its outermost dimension. Fortran arrays will have this since the
2199 // outermost dimension size can be picked up from their runtime description.
2200 // TODO: actually need to check if it has a FAD, but for now this works.
2201 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002202 isl::pw_aff PwAff = Array->getDimensionSizePw(0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002203 if (!PwAff)
2204 continue;
2205
Tobias Grosserb5563c62017-08-03 13:51:15 +00002206 isl::id Id =
2207 isl::manage(isl_pw_aff_get_dim_id(PwAff.get(), isl_dim_param, 0));
2208 assert(!Id.is_null() &&
2209 "Invalid Id for PwAff expression in Fortran array");
2210 Id.dump();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002211 OutermostSizeIds.push_back(Id);
2212 }
2213 }
Tobias Grosserb5563c62017-08-03 13:51:15 +00002214 return OutermostSizeIds;
2215}
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002216
Tobias Grosserb5563c62017-08-03 13:51:15 +00002217// The FORTRAN array size parameters are known to be non-negative.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002218static isl::set boundFortranArrayParams(isl::set Context,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002219 Scop::array_range Arrays) {
2220 std::vector<isl::id> OutermostSizeIds;
2221 OutermostSizeIds = getFortranArrayIds(Arrays);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002222
Tobias Grosserb5563c62017-08-03 13:51:15 +00002223 for (isl::id Id : OutermostSizeIds) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002224 int dim = Context.find_dim_by_id(isl::dim::param, Id);
2225 Context = Context.lower_bound_si(isl::dim::param, dim, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002226 }
2227
2228 return Context;
2229}
2230
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002231void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002232 if (PollyIgnoreParamBounds)
2233 return;
2234
Tobias Grosser6be480c2011-11-08 15:41:13 +00002235 // Add all parameters into a common model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002236 isl::space Space = getFullParamSpace();
Tobias Grosser6be480c2011-11-08 15:41:13 +00002237
2238 // Align the parameters of all data structures to the model.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002239 Context = Context.align_params(Space);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002240
Tobias Grosserb5563c62017-08-03 13:51:15 +00002241 // Bound the size of the fortran array dimensions.
2242 Context = boundFortranArrayParams(Context, arrays());
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002243
Johannes Doerferta60ad842016-05-10 12:18:22 +00002244 // As all parameters are known add bounds to them.
2245 addParameterBounds();
2246
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002247 for (ScopStmt &Stmt : *this)
2248 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002249 // Simplify the schedule according to the context too.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002250 Schedule = Schedule.gist_domain_params(getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002251}
2252
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002253static isl::set simplifyAssumptionContext(isl::set AssumptionContext,
2254 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002255 // If we have modeled all blocks in the SCoP that have side effects we can
2256 // simplify the context with the constraints that are needed for anything to
2257 // be executed at all. However, if we have error blocks in the SCoP we already
2258 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002259 // domains, thus we cannot use the remaining domain to simplify the
2260 // assumptions.
2261 if (!S.hasErrorBlock()) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002262 auto DomainParameters = S.getDomains().params();
2263 AssumptionContext = AssumptionContext.gist_params(DomainParameters);
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002264 }
2265
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002266 AssumptionContext = AssumptionContext.gist_params(S.getContext());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002267 return AssumptionContext;
2268}
2269
2270void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002271 // The parameter constraints of the iteration domains give us a set of
2272 // constraints that need to hold for all cases where at least a single
2273 // statement iteration is executed in the whole scop. We now simplify the
2274 // assumed context under the assumption that such constraints hold and at
2275 // least a single statement iteration is executed. For cases where no
2276 // statement instances are executed, the assumptions we have taken about
2277 // the executed code do not matter and can be changed.
2278 //
2279 // WARNING: This only holds if the assumptions we have taken do not reduce
2280 // the set of statement instances that are executed. Otherwise we
2281 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002282 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002283 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002284 // performed. In such a case, modifying the run-time conditions and
2285 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002286 // to not be executed.
2287 //
2288 // Example:
2289 //
2290 // When delinearizing the following code:
2291 //
2292 // for (long i = 0; i < 100; i++)
2293 // for (long j = 0; j < m; j++)
2294 // A[i+p][j] = 1.0;
2295 //
2296 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002297 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002298 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002299 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002300 InvalidContext = InvalidContext.align_params(getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002301}
2302
Tobias Grosserc80d6972016-09-02 06:33:33 +00002303/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002304static isl::stat
2305buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2306 isl::pw_multi_aff MinPMA, MaxPMA;
2307 isl::pw_aff LastDimAff;
2308 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002309 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002310 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002311
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002312 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002313
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002314 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2315 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002316
Johannes Doerfert9143d672014-09-27 11:02:39 +00002317 // Restrict the number of parameters involved in the access as the lexmin/
2318 // lexmax computation will take too long if this number is high.
2319 //
2320 // Experiments with a simple test case using an i7 4800MQ:
2321 //
2322 // #Parameters involved | Time (in sec)
2323 // 6 | 0.01
2324 // 7 | 0.04
2325 // 8 | 0.12
2326 // 9 | 0.40
2327 // 10 | 1.54
2328 // 11 | 6.78
2329 // 12 | 30.38
2330 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002331 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002332 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002333 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2334 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002335 InvolvedParams++;
2336
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002337 if (InvolvedParams > RunTimeChecksMaxParameters)
2338 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002339 }
2340
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002341 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2342 return isl::stat::error;
2343
Tobias Grosser57a1d362017-06-23 08:05:27 +00002344 MinPMA = Set.lexmin_pw_multi_aff();
2345 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002346
Tobias Grosser57a1d362017-06-23 08:05:27 +00002347 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002348 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002349
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002350 MinPMA = MinPMA.coalesce();
2351 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002352
Johannes Doerfertb164c792014-09-18 11:17:17 +00002353 // Adjust the last dimension of the maximal access by one as we want to
2354 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2355 // we test during code generation might now point after the end of the
2356 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002357 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2358 Pos = MaxPMA.dim(isl::dim::out) - 1;
2359 LastDimAff = MaxPMA.get_pw_aff(Pos);
2360 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2361 OneAff = OneAff.add_constant_si(1);
2362 LastDimAff = LastDimAff.add(OneAff);
2363 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002364
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002365 MinMaxAccesses.push_back(std::make_pair(MinPMA, MaxPMA));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002366
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002367 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002368}
2369
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002370static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00002371 isl_set *Domain = MA->getStatement()->getDomain().release();
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002372 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2373 return isl_set_reset_tuple_id(Domain);
2374}
2375
Tobias Grosserc80d6972016-09-02 06:33:33 +00002376/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002377static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002378 Scop::MinMaxVectorTy &MinMaxAccesses) {
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002379 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002380
Tobias Grosser31df6f32017-08-06 21:42:25 +00002381 isl::union_set Domains = S.getDomains();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002382 isl::union_map Accesses = isl::union_map::empty(S.getParamSpace());
Tobias Grossere9522232017-01-16 15:49:04 +00002383
2384 for (MemoryAccess *MA : AliasGroup)
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00002385 Accesses = Accesses.add_map(MA->getAccessRelation());
Tobias Grossere9522232017-01-16 15:49:04 +00002386
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002387 Accesses = Accesses.intersect_domain(Domains);
2388 isl::union_set Locations = Accesses.range();
2389 Locations = Locations.coalesce();
2390 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002391
2392 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2393 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2394 };
2395 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002396}
2397
Tobias Grosserc80d6972016-09-02 06:33:33 +00002398/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002399///
2400///{
2401
Tobias Grosserc80d6972016-09-02 06:33:33 +00002402/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002403static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2404 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2405 : RN->getNodeAs<BasicBlock>();
2406}
2407
Tobias Grosserc80d6972016-09-02 06:33:33 +00002408/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002409static inline BasicBlock *
2410getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002411 if (RN->isSubRegion()) {
2412 assert(idx == 0);
2413 return RN->getNodeAs<Region>()->getExit();
2414 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002415 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002416}
2417
Tobias Grosserc80d6972016-09-02 06:33:33 +00002418/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002419static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002420 if (!RN->isSubRegion()) {
2421 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2422 Loop *L = LI.getLoopFor(BB);
2423
2424 // Unreachable statements are not considered to belong to a LLVM loop, as
2425 // they are not part of an actual loop in the control flow graph.
2426 // Nevertheless, we handle certain unreachable statements that are common
2427 // when modeling run-time bounds checks as being part of the loop to be
2428 // able to model them and to later eliminate the run-time bounds checks.
2429 //
2430 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002431 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002432 // basic blocks belong to the loop the predecessor belongs to. This
2433 // allows us to model the following code.
2434 //
2435 // for (i = 0; i < N; i++) {
2436 // if (i > 1024)
2437 // abort(); <- this abort might be translated to an
2438 // unreachable
2439 //
2440 // A[i] = ...
2441 // }
2442 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2443 L = LI.getLoopFor(BB->getPrevNode());
2444 return L;
2445 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002446
2447 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2448 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2449 while (L && NonAffineSubRegion->contains(L))
2450 L = L->getParentLoop();
2451 return L;
2452}
2453
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002454/// Get the number of blocks in @p L.
2455///
2456/// The number of blocks in a loop are the number of basic blocks actually
2457/// belonging to the loop, as well as all single basic blocks that the loop
2458/// exits to and which terminate in an unreachable instruction. We do not
2459/// allow such basic blocks in the exit of a scop, hence they belong to the
2460/// scop and represent run-time conditions which we want to model and
2461/// subsequently speculate away.
2462///
2463/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002464unsigned getNumBlocksInLoop(Loop *L) {
2465 unsigned NumBlocks = L->getNumBlocks();
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002466 SmallVector<BasicBlock *, 4> ExitBlocks;
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002467 L->getExitBlocks(ExitBlocks);
2468
2469 for (auto ExitBlock : ExitBlocks) {
2470 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2471 NumBlocks++;
2472 }
2473 return NumBlocks;
2474}
2475
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002476static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2477 if (!RN->isSubRegion())
2478 return 1;
2479
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002480 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002481 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002482}
2483
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002484static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2485 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002486 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002487 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002488 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002489 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002490 return true;
2491 return false;
2492}
2493
Johannes Doerfert96425c22015-08-30 21:13:53 +00002494///}
2495
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002496isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002497 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002498}
2499
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002500isl::set Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002501 auto DIt = DomainMap.find(BB);
2502 if (DIt != DomainMap.end())
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002503 return DIt->getSecond();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002504
2505 auto &RI = *R.getRegionInfo();
2506 auto *BBR = RI.getRegionFor(BB);
2507 while (BBR->getEntry() == BB)
2508 BBR = BBR->getParent();
2509 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002510}
2511
Tobias Grosser13acbb92017-07-15 09:01:31 +00002512bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2513 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002514 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002515 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002516 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2517 int LD = getRelativeLoopDepth(L);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002518 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx().get(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002519
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002520 while (LD-- >= 0) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002521 L = L->getParentLoop();
2522 }
2523
Tobias Grosser13acbb92017-07-15 09:01:31 +00002524 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002525 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002526
Johannes Doerfert432658d2016-01-26 11:01:41 +00002527 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002528 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002529
Michael Kruse476f8552017-06-29 12:47:41 +00002530 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002531 return false;
2532
Michael Kruse476f8552017-06-29 12:47:41 +00002533 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002534 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002535
2536 // Error blocks and blocks dominated by them have been assumed to never be
2537 // executed. Representing them in the Scop does not add any value. In fact,
2538 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002539 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002540 // will cause problems when building up a ScopStmt for them.
2541 // Furthermore, basic blocks dominated by error blocks may reference
2542 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002543 // can themselves not be constructed properly. To this end we will replace
2544 // the domains of error blocks and those only reachable via error blocks
2545 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002546 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002547 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002548 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002549 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002550
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002551 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002552}
2553
Tobias Grosserc80d6972016-09-02 06:33:33 +00002554/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002555/// to be compatible to domains constructed for loop @p NewL.
2556///
2557/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2558/// edge from @p OldL to @p NewL.
2559static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2560 __isl_take isl_set *Dom,
2561 Loop *OldL, Loop *NewL) {
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002562 // If the loops are the same there is nothing to do.
2563 if (NewL == OldL)
2564 return Dom;
2565
2566 int OldDepth = S.getRelativeLoopDepth(OldL);
2567 int NewDepth = S.getRelativeLoopDepth(NewL);
2568 // If both loops are non-affine loops there is nothing to do.
2569 if (OldDepth == -1 && NewDepth == -1)
2570 return Dom;
2571
2572 // Distinguish three cases:
2573 // 1) The depth is the same but the loops are not.
2574 // => One loop was left one was entered.
2575 // 2) The depth increased from OldL to NewL.
2576 // => One loop was entered, none was left.
2577 // 3) The depth decreased from OldL to NewL.
2578 // => Loops were left were difference of the depths defines how many.
2579 if (OldDepth == NewDepth) {
2580 assert(OldL->getParentLoop() == NewL->getParentLoop());
2581 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2582 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002583 } else if (OldDepth < NewDepth) {
2584 assert(OldDepth + 1 == NewDepth);
2585 auto &R = S.getRegion();
2586 (void)R;
2587 assert(NewL->getParentLoop() == OldL ||
2588 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2589 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002590 } else {
2591 assert(OldDepth > NewDepth);
2592 int Diff = OldDepth - NewDepth;
2593 int NumDim = isl_set_n_dim(Dom);
2594 assert(NumDim >= Diff);
2595 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2596 }
2597
2598 return Dom;
2599}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002600
Michael Kruse476f8552017-06-29 12:47:41 +00002601bool Scop::propagateInvalidStmtDomains(
2602 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002603 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002604 ReversePostOrderTraversal<Region *> RTraversal(R);
2605 for (auto *RN : RTraversal) {
2606
2607 // Recurse for affine subregions but go on for basic blocks and non-affine
2608 // subregions.
2609 if (RN->isSubRegion()) {
2610 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002611 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002612 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002613 continue;
2614 }
2615 }
2616
2617 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2618 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002619 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002620 assert(Domain && "Cannot propagate a nullptr");
2621
Tobias Grosser325204a32017-07-15 12:41:32 +00002622 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002623
Tobias Grosser325204a32017-07-15 12:41:32 +00002624 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002625
Johannes Doerferta3519512016-04-23 13:02:23 +00002626 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002627 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002628 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002629 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002630 isl::set DomPar = Domain.params();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002631 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2632 AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002633 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002634 }
2635
Tobias Grosser325204a32017-07-15 12:41:32 +00002636 if (InvalidDomain.is_empty()) {
2637 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002638 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002639 }
2640
Johannes Doerferta3519512016-04-23 13:02:23 +00002641 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002642 auto *TI = BB->getTerminator();
2643 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2644 for (unsigned u = 0; u < NumSuccs; u++) {
2645 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002646
2647 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002648 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002649 continue;
2650
Johannes Doerferte4459a22016-04-25 13:34:50 +00002651 // Skip backedges.
2652 if (DT.dominates(SuccBB, BB))
2653 continue;
2654
Michael Kruse476f8552017-06-29 12:47:41 +00002655 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2656
Johannes Doerferta3519512016-04-23 13:02:23 +00002657 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002658 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002659
Tobias Grosser13acbb92017-07-15 09:01:31 +00002660 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002661 SuccInvalidDomain =
2662 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2663 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2664 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002665
Tobias Grosser13acbb92017-07-15 09:01:31 +00002666 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002667
Michael Krusebc150122016-05-02 12:25:18 +00002668 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002669 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002670 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002671 continue;
2672
Tobias Grosserf44f0052017-07-09 15:47:17 +00002673 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002674 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002675 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002676 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002677
Tobias Grosser325204a32017-07-15 12:41:32 +00002678 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002679 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002680
2681 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002682}
2683
Johannes Doerfert642594a2016-04-04 07:57:39 +00002684void Scop::propagateDomainConstraintsToRegionExit(
2685 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002686 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002687 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002688 // Check if the block @p BB is the entry of a region. If so we propagate it's
2689 // domain to the exit block of the region. Otherwise we are done.
2690 auto *RI = R.getRegionInfo();
2691 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2692 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002693 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002694 return;
2695
Johannes Doerfert642594a2016-04-04 07:57:39 +00002696 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002697 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002698 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002699 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002700 SmallVector<BasicBlock *, 4> LatchBBs;
2701 BBLoop->getLoopLatches(LatchBBs);
2702 for (auto *LatchBB : LatchBBs)
2703 if (BB != LatchBB && BBReg->contains(LatchBB))
2704 return;
2705 L = L->getParentLoop();
2706 }
2707
Tobias Grosser325204a32017-07-15 12:41:32 +00002708 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002709 assert(Domain && "Cannot propagate a nullptr");
2710
Michael Kruse476f8552017-06-29 12:47:41 +00002711 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002712
2713 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2714 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002715 isl::set AdjustedDomain = isl::manage(
2716 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2717 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002718
2719 // If the exit domain is not yet created we set it otherwise we "add" the
2720 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002721 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002722
Johannes Doerferta3519512016-04-23 13:02:23 +00002723 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002724 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002725
Johannes Doerfert642594a2016-04-04 07:57:39 +00002726 FinishedExitBlocks.insert(ExitBB);
2727}
2728
Michael Kruse476f8552017-06-29 12:47:41 +00002729bool Scop::buildDomainsWithBranchConstraints(
2730 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002731 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002732 // To create the domain for each block in R we iterate over all blocks and
2733 // subregions in R and propagate the conditions under which the current region
2734 // element is executed. To this end we iterate in reverse post order over R as
2735 // it ensures that we first visit all predecessors of a region node (either a
2736 // basic block or a subregion) before we visit the region node itself.
2737 // Initially, only the domain for the SCoP region entry block is set and from
2738 // there we propagate the current domain to all successors, however we add the
2739 // condition that the successor is actually executed next.
2740 // As we are only interested in non-loop carried constraints here we can
2741 // simply skip loop back edges.
2742
Johannes Doerfert642594a2016-04-04 07:57:39 +00002743 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002744 ReversePostOrderTraversal<Region *> RTraversal(R);
2745 for (auto *RN : RTraversal) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002746 // Recurse for affine subregions but go on for basic blocks and non-affine
2747 // subregions.
2748 if (RN->isSubRegion()) {
2749 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002750 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002751 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2752 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002753 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002754 continue;
2755 }
2756 }
2757
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002758 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002759 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002760
Johannes Doerfert96425c22015-08-30 21:13:53 +00002761 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002762 TerminatorInst *TI = BB->getTerminator();
2763
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002764 if (isa<UnreachableInst>(TI))
2765 continue;
2766
Tobias Grosser325204a32017-07-15 12:41:32 +00002767 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002768 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002769 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002770 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002771
Johannes Doerfert642594a2016-04-04 07:57:39 +00002772 auto *BBLoop = getRegionNodeLoop(RN, LI);
2773 // Propagate the domain from BB directly to blocks that have a superset
2774 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00002775 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2776 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002777
2778 // If all successors of BB have been set a domain through the propagation
2779 // above we do not need to build condition sets but can just skip this
2780 // block. However, it is important to note that this is a local property
2781 // with regards to the region @p R. To this end FinishedExitBlocks is a
2782 // local variable.
2783 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2784 return FinishedExitBlocks.count(SuccBB);
2785 };
2786 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2787 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002788
2789 // Build the condition sets for the successor nodes of the current region
2790 // node. If it is a non-affine subregion we will always execute the single
2791 // exit node, hence the single entry node domain is the condition set. For
2792 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002793 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002794 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00002795 ConditionSets.push_back(Domain.copy());
2796 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00002797 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002798 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002799
2800 // Now iterate over the successors and set their initial domain based on
2801 // their condition set. We skip back edges here and have to be careful when
2802 // we leave a loop not to keep constraints over a dimension that doesn't
2803 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002804 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002805 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002806 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002807 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002808
Johannes Doerfert535de032016-04-19 14:49:05 +00002809 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00002810 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00002811 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00002812
Johannes Doerfert642594a2016-04-04 07:57:39 +00002813 // If we propagate the domain of some block to "SuccBB" we do not have to
2814 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002815 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002816 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002817
Johannes Doerfert96425c22015-08-30 21:13:53 +00002818 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00002819 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00002820 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002821
Michael Kruse476f8552017-06-29 12:47:41 +00002822 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2823
Tobias Grosser325204a32017-07-15 12:41:32 +00002824 CondSet = isl::manage(
2825 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002826
2827 // Set the domain for the successor or merge it with an existing domain in
2828 // case there are multiple paths (without loop back edges) to the
2829 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00002830 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002831
Johannes Doerferta3519512016-04-23 13:02:23 +00002832 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002833 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00002834 } else {
2835 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002836 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002837 SuccDomain = CondSet;
2838 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002839
Tobias Grosser325204a32017-07-15 12:41:32 +00002840 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00002841
Michael Krusebc150122016-05-02 12:25:18 +00002842 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002843 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00002844 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002845 continue;
2846
2847 invalidate(COMPLEXITY, DebugLoc());
2848 while (++u < ConditionSets.size())
2849 isl_set_free(ConditionSets[u]);
2850 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002851 }
2852 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002853
2854 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002855}
2856
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002857isl::set Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
2858 DominatorTree &DT,
2859 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002860 // If @p BB is the ScopEntry we are done
2861 if (R.getEntry() == BB)
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002862 return isl::set::universe(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002863
Johannes Doerfert642594a2016-04-04 07:57:39 +00002864 // The region info of this function.
2865 auto &RI = *R.getRegionInfo();
2866
Michael Kruse476f8552017-06-29 12:47:41 +00002867 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002868
2869 // A domain to collect all predecessor domains, thus all conditions under
2870 // which the block is executed. To this end we start with the empty domain.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002871 isl::set PredDom = isl::set::empty(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002872
2873 // Set of regions of which the entry block domain has been propagated to BB.
2874 // all predecessors inside any of the regions can be skipped.
2875 SmallSet<Region *, 8> PropagatedRegions;
2876
2877 for (auto *PredBB : predecessors(BB)) {
2878 // Skip backedges.
2879 if (DT.dominates(BB, PredBB))
2880 continue;
2881
2882 // If the predecessor is in a region we used for propagation we can skip it.
2883 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2884 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2885 PredBBInRegion)) {
2886 continue;
2887 }
2888
2889 // Check if there is a valid region we can use for propagation, thus look
2890 // for a region that contains the predecessor and has @p BB as exit block.
2891 auto *PredR = RI.getRegionFor(PredBB);
2892 while (PredR->getExit() != BB && !PredR->contains(BB))
2893 PredR->getParent();
2894
2895 // If a valid region for propagation was found use the entry of that region
2896 // for propagation, otherwise the PredBB directly.
2897 if (PredR->getExit() == BB) {
2898 PredBB = PredR->getEntry();
2899 PropagatedRegions.insert(PredR);
2900 }
2901
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002902 auto *PredBBDom = getDomainConditions(PredBB).release();
Michael Kruse476f8552017-06-29 12:47:41 +00002903 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
2904
Johannes Doerfert642594a2016-04-04 07:57:39 +00002905 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2906
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002907 PredDom = PredDom.unite(isl::manage(PredBBDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002908 }
2909
2910 return PredDom;
2911}
2912
Michael Kruse476f8552017-06-29 12:47:41 +00002913bool Scop::propagateDomainConstraints(
2914 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002915 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002916 // Iterate over the region R and propagate the domain constrains from the
2917 // predecessors to the current node. In contrast to the
2918 // buildDomainsWithBranchConstraints function, this one will pull the domain
2919 // information from the predecessors instead of pushing it to the successors.
2920 // Additionally, we assume the domains to be already present in the domain
2921 // map here. However, we iterate again in reverse post order so we know all
2922 // predecessors have been visited before a block or non-affine subregion is
2923 // visited.
2924
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002925 ReversePostOrderTraversal<Region *> RTraversal(R);
2926 for (auto *RN : RTraversal) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002927 // Recurse for affine subregions but go on for basic blocks and non-affine
2928 // subregions.
2929 if (RN->isSubRegion()) {
2930 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002931 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002932 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002933 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002934 continue;
2935 }
2936 }
2937
2938 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002939 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002940 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002941
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002942 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002943 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser325204a32017-07-15 12:41:32 +00002944 Domain = Domain.intersect(PredDom).coalesce();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002945 Domain = Domain.align_params(getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002946
Johannes Doerfert642594a2016-04-04 07:57:39 +00002947 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002948 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00002949 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002950 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002951 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002952
2953 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002954}
2955
Tobias Grosserc80d6972016-09-02 06:33:33 +00002956/// Create a map to map from a given iteration to a subsequent iteration.
2957///
2958/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2959/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002960/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002961///
2962/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002963static __isl_give isl_map *
2964createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2965 auto *MapSpace = isl_space_map_from_set(SetSpace);
2966 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00002967 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002968 if (u != Dim)
2969 NextIterationMap =
2970 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2971 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2972 C = isl_constraint_set_constant_si(C, 1);
2973 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2974 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2975 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2976 return NextIterationMap;
2977}
2978
Michael Kruse476f8552017-06-29 12:47:41 +00002979bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00002980 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002981 int LoopDepth = getRelativeLoopDepth(L);
2982 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002983
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002984 BasicBlock *HeaderBB = L->getHeader();
2985 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00002986 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002987
Tobias Grosser325204a32017-07-15 12:41:32 +00002988 isl::map NextIterationMap = isl::manage(
2989 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002990
Tobias Grosser325204a32017-07-15 12:41:32 +00002991 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002992
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002993 SmallVector<BasicBlock *, 4> LatchBlocks;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002994 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002995
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002996 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002997 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002998 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002999 if (!LatchBBDom)
3000 continue;
3001
Tobias Grosser325204a32017-07-15 12:41:32 +00003002 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003003
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003004 TerminatorInst *TI = LatchBB->getTerminator();
3005 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003006 assert(BI && "Only branch instructions allowed in loop latches");
3007
3008 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003009 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003010 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003011 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003012 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003013 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3014 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003015 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003016
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003017 // Free the non back edge condition set as we do not need it.
3018 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003019
Tobias Grosser325204a32017-07-15 12:41:32 +00003020 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003021 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003022
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003023 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3024 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003025 BackedgeCondition = BackedgeCondition.project_out(
3026 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3027 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003028 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003029
Tobias Grosser325204a32017-07-15 12:41:32 +00003030 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003031 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003032 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003033
Tobias Grosser325204a32017-07-15 12:41:32 +00003034 isl::set UnionBackedgeConditionComplement =
3035 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003036 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003037 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3038 0);
3039 UnionBackedgeConditionComplement =
3040 UnionBackedgeConditionComplement.apply(ForwardMap);
3041 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3042 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003043
Tobias Grosser325204a32017-07-15 12:41:32 +00003044 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3045 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003046
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003047 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3048 // the bounded assumptions to the context as they are already implied by the
3049 // <nsw> tag.
3050 if (Affinator.hasNSWAddRecForLoop(L)) {
3051 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003052 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003053 }
3054
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003055 isl::set UnboundedCtx = isl::manage(Parts.first).params();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003056 recordAssumption(INFINITELOOP, UnboundedCtx,
3057 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003058 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003059}
3060
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003061MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003062 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003063
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003064 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003065 if (!PointerBaseInst)
3066 return nullptr;
3067
3068 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3069 if (!BasePtrStmt)
3070 return nullptr;
3071
3072 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3073}
3074
3075bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003076 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003077 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003078 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003079 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003080
Tobias Grosserbe372d52017-02-09 10:11:58 +00003081 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003082 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003083 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003084 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003085
3086 return false;
3087}
3088
Johannes Doerfert5210da52016-06-02 11:06:54 +00003089bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003090 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003091 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003092
Johannes Doerfertcd195322016-11-17 21:41:08 +00003093 if (buildAliasGroups(AA)) {
3094 // Aliasing assumptions do not go through addAssumption but we still want to
3095 // collect statistics so we do it here explicitly.
3096 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003097 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003098 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003099 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003100
3101 // If a problem occurs while building the alias groups we need to delete
3102 // this SCoP and pretend it wasn't valid in the first place. To this end
3103 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003104 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003105
3106 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3107 << " could not be created as the number of parameters involved "
3108 "is too high. The SCoP will be "
3109 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3110 "the maximal number of parameters but be advised that the "
3111 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003112 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003113}
3114
Tobias Grosser889830b2017-02-09 23:12:22 +00003115std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003116Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003117 AliasSetTracker AST(AA);
3118
3119 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003120 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003121 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003122
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003123 isl_set *StmtDomain = Stmt.getDomain().release();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003124 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3125 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003126
3127 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003128 if (StmtDomainEmpty)
3129 continue;
3130
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003131 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003132 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003133 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003134 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003135 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003136 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003137 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003138 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003139 else
3140 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003141 AST.add(Acc);
3142 }
3143 }
3144
Tobias Grosser9edcf072017-01-16 14:07:57 +00003145 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003146 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003147 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003148 continue;
3149 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003150 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003151 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003152 if (AG.size() < 2)
3153 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003154 AliasGroups.push_back(std::move(AG));
3155 }
3156
Tobias Grosser9edcf072017-01-16 14:07:57 +00003157 return std::make_tuple(AliasGroups, HasWriteAccess);
3158}
3159
Tobias Grossere39f9122017-01-16 14:08:00 +00003160void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003161 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3162 AliasGroupTy NewAG;
3163 AliasGroupTy &AG = AliasGroups[u];
3164 AliasGroupTy::iterator AGI = AG.begin();
3165 isl_set *AGDomain = getAccessDomain(*AGI);
3166 while (AGI != AG.end()) {
3167 MemoryAccess *MA = *AGI;
3168 isl_set *MADomain = getAccessDomain(MA);
3169 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3170 NewAG.push_back(MA);
3171 AGI = AG.erase(AGI);
3172 isl_set_free(MADomain);
3173 } else {
3174 AGDomain = isl_set_union(AGDomain, MADomain);
3175 AGI++;
3176 }
3177 }
3178 if (NewAG.size() > 1)
3179 AliasGroups.push_back(std::move(NewAG));
3180 isl_set_free(AGDomain);
3181 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003182}
3183
3184bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3185 // To create sound alias checks we perform the following steps:
3186 // o) We partition each group into read only and non read only accesses.
3187 // o) For each group with more than one base pointer we then compute minimal
3188 // and maximal accesses to each array of a group in read only and non
3189 // read only partitions separately.
3190 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003191 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003192
3193 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3194
3195 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003196
Johannes Doerfert13771732014-10-01 12:40:46 +00003197 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003198 if (!hasFeasibleRuntimeContext())
3199 return false;
3200
Tobias Grosser57a1d362017-06-23 08:05:27 +00003201 {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003202 IslMaxOperationsGuard MaxOpGuard(getIslCtx().get(), OptComputeOut);
Tobias Grosser57a1d362017-06-23 08:05:27 +00003203 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3204 if (!Valid)
3205 return false;
3206 }
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003207 if (isl_ctx_last_error(getIslCtx().get()) == isl_error_quota) {
Tobias Grosser57a1d362017-06-23 08:05:27 +00003208 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003209 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003210 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003211 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003212
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003213 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003214}
3215
Tobias Grosser77f32572017-01-16 15:49:07 +00003216bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003217 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003218 AliasGroupTy ReadOnlyAccesses;
3219 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003220 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003221 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003222
Tobias Grosser77f32572017-01-16 15:49:07 +00003223 if (AliasGroup.size() < 2)
3224 return true;
3225
3226 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003227 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3228 Access->getAccessInstruction())
3229 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003230 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3231 if (HasWriteAccess.count(Array)) {
3232 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003233 ReadWriteAccesses.push_back(Access);
3234 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003235 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003236 ReadOnlyAccesses.push_back(Access);
3237 }
3238 }
3239
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003240 // If there are no read-only pointers, and less than two read-write pointers,
3241 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003242 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003243 return true;
3244
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003245 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003246 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003247 return true;
3248
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003249 // For non-affine accesses, no alias check can be generated as we cannot
3250 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003251 for (MemoryAccess *MA : AliasGroup) {
3252 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003253 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3254 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003255 return false;
3256 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003257 }
3258
3259 // Ensure that for all memory accesses for which we generate alias checks,
3260 // their base pointers are available.
3261 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003262 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3263 addRequiredInvariantLoad(
3264 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3265 }
3266
3267 MinMaxAliasGroups.emplace_back();
3268 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3269 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3270 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3271
3272 bool Valid;
3273
3274 Valid =
3275 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3276
3277 if (!Valid)
3278 return false;
3279
3280 // Bail out if the number of values we need to compare is too large.
3281 // This is important as the number of comparisons grows quadratically with
3282 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003283 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003284 RunTimeChecksMaxArraysPerGroup)
3285 return false;
3286
3287 Valid =
3288 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3289
3290 if (!Valid)
3291 return false;
3292
3293 return true;
3294}
3295
Tobias Grosserc80d6972016-09-02 06:33:33 +00003296/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003297static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003298 // Start with the smallest loop containing the entry and expand that
3299 // loop until it contains all blocks in the region. If there is a loop
3300 // containing all blocks in the region check if it is itself contained
3301 // and if so take the parent loop as it will be the smallest containing
3302 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003303 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003304 while (L) {
3305 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003306 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003307 AllContained &= L->contains(BB);
3308 if (AllContained)
3309 break;
3310 L = L->getParentLoop();
3311 }
3312
Johannes Doerfertef744432016-05-23 12:42:38 +00003313 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003314}
3315
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003316int Scop::NextScopID = 0;
3317
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003318std::string Scop::CurrentFunc;
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003319
3320int Scop::getNextID(std::string ParentFunc) {
3321 if (ParentFunc != CurrentFunc) {
3322 CurrentFunc = ParentFunc;
3323 NextScopID = 0;
3324 }
3325 return NextScopID++;
3326}
3327
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003328Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Tobias Grosseree457592017-09-24 09:25:30 +00003329 DominatorTree &DT, ScopDetection::DetectionContext &DC,
3330 OptimizationRemarkEmitter &ORE)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003331 : IslCtx(isl_ctx_alloc(), isl_ctx_free), SE(&ScalarEvolution), DT(&DT),
Eli Friedmanac4ad452018-03-27 20:51:49 +00003332 R(R), HasSingleExitEdge(R.getExitingBlock()), DC(DC), ORE(ORE),
3333 Affinator(this, LI),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003334 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003335 if (IslOnErrorAbort)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003336 isl_options_set_on_error(getIslCtx().get(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003337 buildContext();
3338}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003339
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003340Scop::~Scop() = default;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003341
Tobias Grosserbedef002016-12-02 08:10:56 +00003342void Scop::foldSizeConstantsToRight() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003343 isl_union_set *Accessed = isl_union_map_range(getAccesses().release());
Tobias Grosserbedef002016-12-02 08:10:56 +00003344
3345 for (auto Array : arrays()) {
3346 if (Array->getNumberOfDimensions() <= 1)
3347 continue;
3348
Tobias Grosser77eef902017-07-21 23:07:56 +00003349 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003350
3351 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3352
3353 if (!isl_union_set_contains(Accessed, Space)) {
3354 isl_space_free(Space);
3355 continue;
3356 }
3357
3358 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3359
3360 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003361 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003362
3363 std::vector<int> Int;
3364
3365 int Dims = isl_set_dim(Elements, isl_dim_set);
3366 for (int i = 0; i < Dims; i++) {
3367 isl_set *DimOnly =
3368 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3369 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3370 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3371
3372 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3373
3374 if (i == Dims - 1) {
3375 Int.push_back(1);
3376 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3377 isl_basic_set_free(DimHull);
3378 continue;
3379 }
3380
3381 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3382 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3383 isl_val *Val = isl_aff_get_denominator_val(Diff);
3384 isl_aff_free(Diff);
3385
3386 int ValInt = 1;
3387
Eli Friedmana75d53c2018-01-17 21:59:02 +00003388 if (isl_val_is_int(Val)) {
3389 auto ValAPInt = APIntFromVal(Val);
3390 if (ValAPInt.isSignedIntN(32))
3391 ValInt = ValAPInt.getSExtValue();
3392 } else {
3393 isl_val_free(Val);
3394 }
Tobias Grosserbedef002016-12-02 08:10:56 +00003395
3396 Int.push_back(ValInt);
3397
3398 isl_constraint *C = isl_constraint_alloc_equality(
3399 isl_local_space_from_space(isl_map_get_space(Transform)));
3400 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3401 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3402 Transform = isl_map_add_constraint(Transform, C);
3403 isl_basic_set_free(DimHull);
3404 continue;
3405 }
3406
3407 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3408 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3409
3410 int ValInt = 1;
3411 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3412 ValInt = 0;
3413 }
3414
3415 Int.push_back(ValInt);
3416 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3417 isl_basic_set_free(DimHull);
3418 isl_basic_set_free(ZeroSet);
3419 }
3420
3421 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3422
3423 if (!isl_set_is_subset(Elements, MappedElements)) {
3424 isl_set_free(Elements);
3425 isl_set_free(MappedElements);
3426 isl_map_free(Transform);
3427 continue;
3428 }
3429
3430 isl_set_free(MappedElements);
3431
3432 bool CanFold = true;
3433
3434 if (Int[0] <= 1)
3435 CanFold = false;
3436
3437 unsigned NumDims = Array->getNumberOfDimensions();
3438 for (unsigned i = 1; i < NumDims - 1; i++)
3439 if (Int[0] != Int[i] && Int[i])
3440 CanFold = false;
3441
3442 if (!CanFold) {
3443 isl_set_free(Elements);
3444 isl_map_free(Transform);
3445 continue;
3446 }
3447
Tobias Grosserbedef002016-12-02 08:10:56 +00003448 for (auto &Access : AccessFunctions)
3449 if (Access->getScopArrayInfo() == Array)
Tobias Grosser6d588042017-08-02 19:27:16 +00003450 Access->setAccessRelation(Access->getAccessRelation().apply_range(
Tobias Grosser718d04c2018-02-20 07:26:58 +00003451 isl::manage_copy(Transform)));
Tobias Grosserbedef002016-12-02 08:10:56 +00003452
3453 isl_map_free(Transform);
3454
3455 std::vector<const SCEV *> Sizes;
3456 for (unsigned i = 0; i < NumDims; i++) {
3457 auto Size = Array->getDimensionSize(i);
3458
3459 if (i == NumDims - 1)
3460 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3461 Sizes.push_back(Size);
3462 }
3463
3464 Array->updateSizes(Sizes, false /* CheckConsistency */);
3465
3466 isl_set_free(Elements);
3467 }
3468 isl_union_set_free(Accessed);
Tobias Grosserbedef002016-12-02 08:10:56 +00003469}
3470
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003471void Scop::markFortranArrays() {
3472 for (ScopStmt &Stmt : Stmts) {
3473 for (MemoryAccess *MemAcc : Stmt) {
3474 Value *FAD = MemAcc->getFortranArrayDescriptor();
3475 if (!FAD)
3476 continue;
3477
3478 // TODO: const_cast-ing to edit
3479 ScopArrayInfo *SAI =
3480 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3481 assert(SAI && "memory access into a Fortran array does not "
3482 "have an associated ScopArrayInfo");
3483 SAI->applyAndSetFAD(FAD);
3484 }
3485 }
3486}
3487
Tobias Grosser491b7992016-12-02 05:21:22 +00003488void Scop::finalizeAccesses() {
3489 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003490 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003491 foldAccessRelations();
3492 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003493 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003494}
3495
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003496void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003497 // Check all array accesses for each base pointer and find a (virtual) element
3498 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003499 for (ScopStmt &Stmt : *this)
3500 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003501 if (!Access->isArrayKind())
3502 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003503 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003504 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3505
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003506 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003507 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003508 unsigned DivisibleSize = Array->getElemSizeInBytes();
3509 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003510 while (!isDivisible(Subscript, DivisibleSize, *SE))
3511 DivisibleSize /= 2;
3512 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003513 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003514 }
3515
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003516 for (auto &Stmt : *this)
3517 for (auto &Access : Stmt)
3518 Access->updateDimensionality();
3519}
3520
Tobias Grosser491b7992016-12-02 05:21:22 +00003521void Scop::foldAccessRelations() {
3522 for (auto &Stmt : *this)
3523 for (auto &Access : Stmt)
3524 Access->foldAccessRelation();
3525}
3526
3527void Scop::assumeNoOutOfBounds() {
3528 for (auto &Stmt : *this)
3529 for (auto &Access : Stmt)
3530 Access->assumeNoOutOfBound();
3531}
3532
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003533void Scop::removeFromStmtMap(ScopStmt &Stmt) {
Tobias Grosserbd15d132017-08-31 03:15:56 +00003534 for (Instruction *Inst : Stmt.getInstructions())
3535 InstStmtMap.erase(Inst);
3536
3537 if (Stmt.isRegionStmt()) {
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003538 for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003539 StmtMap.erase(BB);
Tobias Grosserbd15d132017-08-31 03:15:56 +00003540 // Skip entry basic block, as its instructions are already deleted as
3541 // part of the statement's instruction list.
3542 if (BB == Stmt.getEntryBlock())
3543 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003544 for (Instruction &Inst : *BB)
3545 InstStmtMap.erase(&Inst);
3546 }
Tobias Grosserbd15d132017-08-31 03:15:56 +00003547 } else {
Michael Kruse0c6c5552017-09-01 11:36:52 +00003548 auto StmtMapIt = StmtMap.find(Stmt.getBasicBlock());
3549 if (StmtMapIt != StmtMap.end())
3550 StmtMapIt->second.erase(std::remove(StmtMapIt->second.begin(),
3551 StmtMapIt->second.end(), &Stmt),
3552 StmtMapIt->second.end());
3553 for (Instruction *Inst : Stmt.getInstructions())
3554 InstStmtMap.erase(Inst);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003555 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003556}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003557
Michael Kruse192e7f72018-04-09 23:13:05 +00003558void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete,
3559 bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003560 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3561 if (!ShouldDelete(*StmtIt)) {
3562 StmtIt++;
3563 continue;
3564 }
3565
Michael Kruse192e7f72018-04-09 23:13:05 +00003566 // Start with removing all of the statement's accesses including erasing it
3567 // from all maps that are pointing to them.
Michael Krusedb6f71e2018-04-10 01:20:41 +00003568 // Make a temporary copy because removing MAs invalidates the iterator.
3569 SmallVector<MemoryAccess *, 16> MAList(StmtIt->begin(), StmtIt->end());
3570 for (MemoryAccess *MA : MAList)
Michael Kruse192e7f72018-04-09 23:13:05 +00003571 StmtIt->removeSingleMemoryAccess(MA, AfterHoisting);
3572
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003573 removeFromStmtMap(*StmtIt);
3574 StmtIt = Stmts.erase(StmtIt);
3575 }
3576}
3577
3578void Scop::removeStmtNotInDomainMap() {
3579 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003580 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003581 };
Michael Kruse192e7f72018-04-09 23:13:05 +00003582 removeStmts(ShouldDelete, false);
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003583}
3584
3585void Scop::simplifySCoP(bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003586 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Michael Kruse5369ea52018-04-20 18:55:44 +00003587 // Never delete statements that contain calls to debug functions.
3588 if (hasDebugCall(&Stmt))
3589 return false;
3590
Johannes Doerfert26404542016-05-10 12:19:47 +00003591 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003592
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003593 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003594 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003595 bool OnlyRead = true;
3596 for (MemoryAccess *MA : Stmt) {
3597 if (MA->isRead())
3598 continue;
3599
3600 OnlyRead = false;
3601 break;
3602 }
3603
3604 RemoveStmt = OnlyRead;
3605 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003606 return RemoveStmt;
3607 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003608
Michael Kruse192e7f72018-04-09 23:13:05 +00003609 removeStmts(ShouldDelete, AfterHoisting);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003610}
3611
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003612InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003613 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3614 if (!LInst)
3615 return nullptr;
3616
3617 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3618 LInst = cast<LoadInst>(Rep);
3619
Johannes Doerfert96e54712016-02-07 17:30:13 +00003620 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003621 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003622 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003623 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003624 continue;
3625
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003626 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003627 for (auto *MA : MAs)
3628 if (MA->getAccessInstruction() == Val)
3629 return &IAClass;
3630 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003631
3632 return nullptr;
3633}
3634
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003635bool isAParameter(llvm::Value *maybeParam, const Function &F) {
3636 for (const llvm::Argument &Arg : F.args())
3637 if (&Arg == maybeParam)
3638 return true;
3639
3640 return false;
Michael Kruse594386e2017-08-23 12:34:37 +00003641}
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003642
Tobias Grosser305d3162017-08-07 00:10:11 +00003643bool Scop::canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3644 bool MAInvalidCtxIsEmpty,
3645 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003646 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3647 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003648 if (PollyAllowDereferenceOfAllFunctionParams &&
3649 isAParameter(LInst->getPointerOperand(), getFunction()))
3650 return true;
3651
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003652 // TODO: We can provide more information for better but more expensive
3653 // results.
3654 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3655 LInst->getAlignment(), DL))
3656 return false;
3657
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003658 // If the location might be overwritten we do not hoist it unconditionally.
3659 //
Siddharth Bhat83fe6b52017-08-08 12:26:32 +00003660 // TODO: This is probably too conservative.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003661 if (!NonHoistableCtxIsEmpty)
3662 return false;
3663
Michael Krusea6d48f52017-06-08 12:06:15 +00003664 // If a dereferenceable load is in a statement that is modeled precisely we
3665 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003666 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003667 return true;
3668
3669 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003670 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003671 // statement domain.
3672 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3673 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3674 return false;
3675 return true;
3676}
3677
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003678void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003679 if (InvMAs.empty())
3680 return;
3681
Tobias Grosser2332fa32017-08-06 15:36:48 +00003682 isl::set StmtInvalidCtx = Stmt.getInvalidContext();
3683 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003684
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003685 // Get the context under which the statement is executed but remove the error
3686 // context under which this statement is reached.
Tobias Grossere69b2722017-08-06 23:50:25 +00003687 isl::set DomainCtx = Stmt.getDomain().params();
3688 DomainCtx = DomainCtx.subtract(StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003689
Tobias Grossere69b2722017-08-06 23:50:25 +00003690 if (isl_set_n_basic_set(DomainCtx.get()) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003691 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003692 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003693 return;
3694 }
3695
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003696 // Project out all parameters that relate to loads in the statement. Otherwise
3697 // we could have cyclic dependences on the constraints under which the
3698 // hoisted loads are executed and we could not determine an order in which to
3699 // pre-load them. This happens because not only lower bounds are part of the
3700 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003701 for (auto &InvMA : InvMAs) {
3702 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003703 Instruction *AccInst = MA->getAccessInstruction();
3704 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003705 SetVector<Value *> Values;
3706 for (const SCEV *Parameter : Parameters) {
3707 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003708 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003709 if (!Values.count(AccInst))
3710 continue;
3711
Tobias Grossere69b2722017-08-06 23:50:25 +00003712 if (isl::id ParamId = getIdForParam(Parameter)) {
3713 int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003714 if (Dim >= 0)
Tobias Grossere69b2722017-08-06 23:50:25 +00003715 DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003716 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003717 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003718 }
3719 }
3720
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003721 for (auto &InvMA : InvMAs) {
3722 auto *MA = InvMA.MA;
Tobias Grossere69b2722017-08-06 23:50:25 +00003723 isl::set NHCtx = InvMA.NonHoistableCtx;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003724
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003725 // Check for another invariant access that accesses the same location as
3726 // MA and if found consolidate them. Otherwise create a new equivalence
3727 // class at the end of InvariantEquivClasses.
3728 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003729 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003730 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3731
Tobias Grossere69b2722017-08-06 23:50:25 +00003732 isl::set MAInvalidCtx = MA->getInvalidContext();
3733 bool NonHoistableCtxIsEmpty = NHCtx.is_empty();
3734 bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty();
Johannes Doerfert85676e32016-04-23 14:32:34 +00003735
Tobias Grossere69b2722017-08-06 23:50:25 +00003736 isl::set MACtx;
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003737 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003738 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3739 NonHoistableCtxIsEmpty)) {
Tobias Grossere69b2722017-08-06 23:50:25 +00003740 MACtx = isl::set::universe(DomainCtx.get_space());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003741 } else {
Tobias Grossere69b2722017-08-06 23:50:25 +00003742 MACtx = DomainCtx;
3743 MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx));
3744 MACtx = MACtx.gist_params(getContext());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003745 }
3746
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003747 bool Consolidated = false;
3748 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003749 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003750 continue;
3751
Johannes Doerfertdf880232016-03-03 12:26:58 +00003752 // If the pointer and the type is equal check if the access function wrt.
3753 // to the domain is equal too. It can happen that the domain fixes
3754 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003755 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003756 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003757 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003758 if (!MAs.empty()) {
3759 auto *LastMA = MAs.front();
3760
Tobias Grossere69b2722017-08-06 23:50:25 +00003761 isl::set AR = MA->getAccessRelation().range();
3762 isl::set LastAR = LastMA->getAccessRelation().range();
3763 bool SameAR = AR.is_equal(LastAR);
Johannes Doerfertdf880232016-03-03 12:26:58 +00003764
3765 if (!SameAR)
3766 continue;
3767 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003768
3769 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003770 MAs.push_front(MA);
3771
Johannes Doerfertdf880232016-03-03 12:26:58 +00003772 Consolidated = true;
3773
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003774 // Unify the execution context of the class and this statement.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003775 isl::set IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003776 if (IAClassDomainCtx)
Tobias Grossere69b2722017-08-06 23:50:25 +00003777 IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce();
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003778 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003779 IAClassDomainCtx = MACtx;
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003780 IAClass.ExecutionContext = IAClassDomainCtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003781 break;
3782 }
3783
3784 if (Consolidated)
3785 continue;
3786
3787 // If we did not consolidate MA, thus did not find an equivalence class
3788 // for it, we create a new one.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003789 InvariantEquivClasses.emplace_back(
3790 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003791 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003792}
3793
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003794/// Check if an access range is too complex.
3795///
3796/// An access range is too complex, if it contains either many disjuncts or
3797/// very complex expressions. As a simple heuristic, we assume if a set to
3798/// be too complex if the sum of existentially quantified dimensions and
3799/// set dimensions is larger than a threshold. This reliably detects both
3800/// sets with many disjuncts as well as sets with many divisions as they
3801/// arise in h264.
3802///
3803/// @param AccessRange The range to check for complexity.
3804///
3805/// @returns True if the access range is too complex.
3806static bool isAccessRangeTooComplex(isl::set AccessRange) {
3807 unsigned NumTotalDims = 0;
3808
3809 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
3810 NumTotalDims += BSet.dim(isl::dim::div);
3811 NumTotalDims += BSet.dim(isl::dim::set);
3812 return isl::stat::ok;
3813 };
3814
3815 AccessRange.foreach_basic_set(CountDimensions);
3816
3817 if (NumTotalDims > MaxDimensionsInAccessRange)
3818 return true;
3819
3820 return false;
3821}
3822
Tobias Grosser4071cb52017-06-06 23:13:02 +00003823isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003824 // TODO: Loads that are not loop carried, hence are in a statement with
3825 // zero iterators, are by construction invariant, though we
3826 // currently "hoist" them anyway. This is necessary because we allow
3827 // them to be treated as parameters (e.g., in conditions) and our code
3828 // generation would otherwise use the old value.
3829
3830 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003831 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003832
Johannes Doerfertc9765462016-11-17 22:11:56 +00003833 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3834 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003835 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003836
3837 // Skip accesses that have an invariant base pointer which is defined but
3838 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3839 // returns a pointer that is used as a base address. However, as we want
3840 // to hoist indirect pointers, we allow the base pointer to be defined in
3841 // the region if it is also a memory access. Each ScopArrayInfo object
3842 // that has a base pointer origin has a base pointer that is loaded and
3843 // that it is invariant, thus it will be hoisted too. However, if there is
3844 // no base pointer origin we check that the base pointer is defined
3845 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003846 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003847 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003848 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003849
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00003850 isl::map AccessRelation = Access->getAccessRelation();
Tobias Grosser4071cb52017-06-06 23:13:02 +00003851 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003852
Tobias Grosser4071cb52017-06-06 23:13:02 +00003853 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003854 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003855
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003856 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
Tobias Grosser4071cb52017-06-06 23:13:02 +00003857 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003858
3859 auto &DL = getFunction().getParent()->getDataLayout();
3860 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3861 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003862 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003863 } else if (BB != LI->getParent()) {
3864 // Skip accesses in non-affine subregions as they might not be executed
3865 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003866 return nullptr;
3867 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003868 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003869 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003870
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003871 if (isAccessRangeTooComplex(AccessRelation.range()))
3872 return nullptr;
3873
Tobias Grosser4071cb52017-06-06 23:13:02 +00003874 isl::union_map Written = Writes.intersect_range(SafeToLoad);
3875 isl::set WrittenCtx = Written.params();
3876 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003877
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003878 if (!IsWritten)
3879 return WrittenCtx;
3880
Tobias Grosser4071cb52017-06-06 23:13:02 +00003881 WrittenCtx = WrittenCtx.remove_divs();
3882 bool TooComplex =
3883 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
3884 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003885 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003886
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003887 addAssumption(INVARIANTLOAD, WrittenCtx, LI->getDebugLoc(), AS_RESTRICTION,
3888 LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003889 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003890}
3891
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003892void Scop::verifyInvariantLoads() {
3893 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003894 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003895 assert(LI && contains(LI));
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003896 // If there exists a statement in the scop which has a memory access for
3897 // @p LI, then mark this scop as infeasible for optimization.
3898 for (ScopStmt &Stmt : Stmts)
3899 if (Stmt.getArrayAccessOrNULLFor(LI)) {
3900 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
3901 return;
3902 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003903 }
3904}
3905
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003906void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003907 if (!PollyInvariantLoadHoisting)
3908 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003909
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003910 isl::union_map Writes = getWrites();
Tobias Grosser0865e7752016-02-29 07:29:42 +00003911 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003912 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003913
Tobias Grosser0865e7752016-02-29 07:29:42 +00003914 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00003915 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
Tobias Grosserd16f9272017-08-06 17:25:14 +00003916 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003917
3918 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003919 for (auto InvMA : InvariantAccesses)
3920 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003921 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003922 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003923}
3924
Tobias Grosserf3adab42017-05-10 10:59:58 +00003925/// Find the canonical scop array info object for a set of invariant load
3926/// hoisted loads. The canonical array is the one that corresponds to the
3927/// first load in the list of accesses which is used as base pointer of a
3928/// scop array.
3929static const ScopArrayInfo *findCanonicalArray(Scop *S,
3930 MemoryAccessList &Accesses) {
3931 for (MemoryAccess *Access : Accesses) {
3932 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3933 Access->getAccessInstruction(), MemoryKind::Array);
3934 if (CanonicalArray)
3935 return CanonicalArray;
3936 }
3937 return nullptr;
3938}
3939
3940/// Check if @p Array severs as base array in an invariant load.
3941static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3942 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3943 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3944 if (Access2->getScopArrayInfo() == Array)
3945 return true;
3946 return false;
3947}
3948
3949/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3950/// with a reference to @p New.
3951static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3952 const ScopArrayInfo *New) {
3953 for (ScopStmt &Stmt : *S)
3954 for (MemoryAccess *Access : Stmt) {
3955 if (Access->getLatestScopArrayInfo() != Old)
3956 continue;
3957
Tobias Grosser6d588042017-08-02 19:27:16 +00003958 isl::id Id = New->getBasePtrId();
3959 isl::map Map = Access->getAccessRelation();
3960 Map = Map.set_tuple_id(isl::dim::out, Id);
Tobias Grosserf3adab42017-05-10 10:59:58 +00003961 Access->setAccessRelation(Map);
3962 }
3963}
3964
3965void Scop::canonicalizeDynamicBasePtrs() {
3966 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3967 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3968
3969 const ScopArrayInfo *CanonicalBasePtrSAI =
3970 findCanonicalArray(this, BasePtrAccesses);
3971
3972 if (!CanonicalBasePtrSAI)
3973 continue;
3974
3975 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3976 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3977 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3978 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3979 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3980 continue;
3981
3982 // we currently do not canonicalize arrays where some accesses are
3983 // hoisted as invariant loads. If we would, we need to update the access
3984 // function of the invariant loads as well. However, as this is not a
3985 // very common situation, we leave this for now to avoid further
3986 // complexity increases.
3987 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
3988 continue;
3989
3990 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
3991 }
3992 }
3993}
3994
Michael Kruseb738ffa2017-06-28 13:02:43 +00003995ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3996 ArrayRef<const SCEV *> Sizes,
3997 MemoryKind Kind,
3998 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003999 assert((BasePtr || BaseName) &&
4000 "BasePtr and BaseName can not be nullptr at the same time.");
4001 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4002 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4003 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004004 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004005 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004006 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004007 DL, this, BaseName));
4008 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004009 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004010 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004011 // In case of mismatching array sizes, we bail out by setting the run-time
4012 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004013 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004014 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004015 }
Tobias Grosserab671442015-05-23 05:58:27 +00004016 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004017}
4018
Michael Kruseb738ffa2017-06-28 13:02:43 +00004019ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4020 const std::string &BaseName,
4021 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004022 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4023 std::vector<const SCEV *> SCEVSizes;
4024
4025 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004026 if (size)
4027 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4028 else
4029 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004030
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004031 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4032 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004033 return SAI;
4034}
4035
Tobias Grosserf3adab42017-05-10 10:59:58 +00004036const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4037 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004038 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004039 return SAI;
4040}
4041
4042const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4043 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004044 assert(SAI && "No ScopArrayInfo available for this base pointer");
4045 return SAI;
4046}
4047
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004048std::string Scop::getContextStr() const { return getContext().to_str(); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004049
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004050std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004051 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004052 return AssumedContext.to_str();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004053}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004054
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004055std::string Scop::getInvalidContextStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004056 return InvalidContext.to_str();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004057}
Tobias Grosser75805372011-04-29 06:27:02 +00004058
4059std::string Scop::getNameStr() const {
4060 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004061 std::tie(EntryName, ExitName) = getEntryExitStr();
4062 return EntryName + "---" + ExitName;
4063}
4064
4065std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4066 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004067 raw_string_ostream ExitStr(ExitName);
4068 raw_string_ostream EntryStr(EntryName);
4069
Tobias Grosserf240b482014-01-09 10:42:15 +00004070 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004071 EntryStr.str();
4072
4073 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004074 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004075 ExitStr.str();
4076 } else
4077 ExitName = "FunctionExit";
4078
Siddharth Bhat07bee292017-06-02 08:01:22 +00004079 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004080}
4081
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004082isl::set Scop::getContext() const { return Context; }
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004083isl::space Scop::getParamSpace() const { return getContext().get_space(); }
Tobias Grosser37487052011-10-06 00:03:42 +00004084
Tobias Grosserb5563c62017-08-03 13:51:15 +00004085isl::space Scop::getFullParamSpace() const {
4086 std::vector<isl::id> FortranIDs;
4087 FortranIDs = getFortranArrayIds(arrays());
4088
4089 isl::space Space = isl::space::params_alloc(
4090 getIslCtx(), ParameterIds.size() + FortranIDs.size());
4091
4092 unsigned PDim = 0;
4093 for (const SCEV *Parameter : Parameters) {
Tobias Grosser9a635702017-08-06 19:31:27 +00004094 isl::id Id = getIdForParam(Parameter);
Tobias Grosserb5563c62017-08-03 13:51:15 +00004095 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4096 }
4097
4098 for (isl::id Id : FortranIDs)
4099 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4100
4101 return Space;
4102}
4103
Tobias Grossere1270332017-08-06 21:42:09 +00004104isl::set Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004105 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004106 return AssumedContext;
Tobias Grossere86109f2013-10-29 21:05:49 +00004107}
4108
Michael Krusef3091bf2017-03-17 13:09:52 +00004109bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004110 if (PollyProcessUnprofitable)
4111 return true;
4112
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004113 if (isEmpty())
4114 return false;
4115
4116 unsigned OptimizableStmtsOrLoops = 0;
4117 for (auto &Stmt : *this) {
4118 if (Stmt.getNumIterators() == 0)
4119 continue;
4120
4121 bool ContainsArrayAccs = false;
4122 bool ContainsScalarAccs = false;
4123 for (auto *MA : Stmt) {
4124 if (MA->isRead())
4125 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004126 ContainsArrayAccs |= MA->isLatestArrayKind();
4127 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004128 }
4129
Michael Krusef3091bf2017-03-17 13:09:52 +00004130 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004131 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4132 }
4133
4134 return OptimizableStmtsOrLoops > 1;
4135}
4136
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004137bool Scop::hasFeasibleRuntimeContext() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004138 auto PositiveContext = getAssumedContext();
4139 auto NegativeContext = getInvalidContext();
4140 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4141 // addNonEmptyDomainConstraints returns null if ScopStmts have a null domain
4142 if (!PositiveContext)
Johannes Doerfert94341c92016-04-23 13:00:27 +00004143 return false;
Johannes Doerfert94341c92016-04-23 13:00:27 +00004144
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004145 bool IsFeasible = !(PositiveContext.is_empty() ||
4146 PositiveContext.is_subset(NegativeContext));
4147 if (!IsFeasible)
4148 return false;
4149
4150 auto DomainContext = getDomains().params();
4151 IsFeasible = !DomainContext.is_subset(NegativeContext);
4152 IsFeasible &= !Context.is_subset(NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004153
Johannes Doerfert43788c52015-08-20 05:58:56 +00004154 return IsFeasible;
4155}
4156
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004157static std::string toString(AssumptionKind Kind) {
4158 switch (Kind) {
4159 case ALIASING:
4160 return "No-aliasing";
4161 case INBOUNDS:
4162 return "Inbounds";
4163 case WRAPPING:
4164 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004165 case UNSIGNED:
4166 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004167 case COMPLEXITY:
4168 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004169 case PROFITABLE:
4170 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004171 case ERRORBLOCK:
4172 return "No-error";
4173 case INFINITELOOP:
4174 return "Finite loop";
4175 case INVARIANTLOAD:
4176 return "Invariant load";
4177 case DELINEARIZATION:
4178 return "Delinearization";
4179 }
4180 llvm_unreachable("Unknown AssumptionKind!");
4181}
4182
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004183bool Scop::isEffectiveAssumption(isl::set Set, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004184 if (Sign == AS_ASSUMPTION) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004185 if (Context.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004186 return false;
4187
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004188 if (AssumedContext.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004189 return false;
4190 } else {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004191 if (Set.is_disjoint(Context))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004192 return false;
4193
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004194 if (Set.is_subset(InvalidContext))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004195 return false;
4196 }
4197 return true;
4198}
4199
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004200bool Scop::trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4201 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004202 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4203 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004204
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004205 // Do never emit trivial assumptions as they only clutter the output.
4206 if (!PollyRemarksMinimal) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004207 isl::set Univ;
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004208 if (Sign == AS_ASSUMPTION)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004209 Univ = isl::set::universe(Set.get_space());
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004210
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004211 bool IsTrivial = (Sign == AS_RESTRICTION && Set.is_empty()) ||
4212 (Sign == AS_ASSUMPTION && Univ.is_equal(Set));
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004213
4214 if (IsTrivial)
4215 return false;
4216 }
4217
Johannes Doerfertcd195322016-11-17 21:41:08 +00004218 switch (Kind) {
4219 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004220 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004221 break;
4222 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004223 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004224 break;
4225 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004226 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004227 break;
4228 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004229 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004230 break;
4231 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004232 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004233 break;
4234 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004235 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004236 break;
4237 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004238 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004239 break;
4240 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004241 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004242 break;
4243 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004244 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004245 break;
4246 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004247 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004248 break;
4249 }
4250
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004251 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004252 std::string Msg = toString(Kind) + Suffix + Set.to_str();
Eli Friedmane737fc12017-07-17 23:58:33 +00004253 if (BB)
4254 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4255 << Msg);
4256 else
4257 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4258 R.getEntry())
4259 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004260 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004261}
4262
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004263void Scop::addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4264 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004265 // Simplify the assumptions/restrictions first.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004266 Set = Set.gist_params(getContext());
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004267
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004268 if (!trackAssumption(Kind, Set, Loc, Sign, BB))
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004269 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004270
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004271 if (Sign == AS_ASSUMPTION)
4272 AssumedContext = AssumedContext.intersect(Set).coalesce();
4273 else
4274 InvalidContext = InvalidContext.unite(Set).coalesce();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004275}
4276
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004277void Scop::recordAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4278 AssumptionSign Sign, BasicBlock *BB) {
4279 assert((Set.is_params() || BB) &&
Tobias Grosserf67433a2016-11-10 11:44:10 +00004280 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004281 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004282}
4283
4284void Scop::addRecordedAssumptions() {
4285 while (!RecordedAssumptions.empty()) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004286 Assumption AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004287
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004288 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004289 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004290 continue;
4291 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004292
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004293 // If the domain was deleted the assumptions are void.
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004294 isl_set *Dom = getDomainConditions(AS.BB).release();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004295 if (!Dom)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004296 continue;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004297
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004298 // If a basic block was given use its domain to simplify the assumption.
4299 // In case of restrictions we know they only have to hold on the domain,
4300 // thus we can intersect them with the domain of the block. However, for
4301 // assumptions the domain has to imply them, thus:
4302 // _ _____
4303 // Dom => S <==> A v B <==> A - B
4304 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004305 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004306 // assumption.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004307 isl_set *S = AS.Set.copy();
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004308 if (AS.Sign == AS_RESTRICTION)
4309 S = isl_set_params(isl_set_intersect(S, Dom));
4310 else /* (AS.Sign == AS_ASSUMPTION) */
4311 S = isl_set_params(isl_set_subtract(Dom, S));
4312
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004313 addAssumption(AS.Kind, isl::manage(S), AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004314 }
4315}
4316
Eli Friedmane737fc12017-07-17 23:58:33 +00004317void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
Michael Kruse860870b2017-08-30 11:52:03 +00004318 DEBUG(dbgs() << "Invalidate SCoP because of reason " << Kind << "\n");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004319 addAssumption(Kind, isl::set::empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004320}
4321
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004322isl::set Scop::getInvalidContext() const { return InvalidContext; }
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004323
Tobias Grosser75805372011-04-29 06:27:02 +00004324void Scop::printContext(raw_ostream &OS) const {
4325 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004326 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004327
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004328 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004329 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004330
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004331 OS.indent(4) << "Invalid Context:\n";
4332 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004333
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004334 unsigned Dim = 0;
4335 for (const SCEV *Parameter : Parameters)
4336 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004337}
4338
Johannes Doerfertb164c792014-09-18 11:17:17 +00004339void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004340 int noOfGroups = 0;
4341 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004342 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004343 noOfGroups += 1;
4344 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004345 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004346 }
4347
Tobias Grosserbb853c22015-07-25 12:31:03 +00004348 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004349 if (MinMaxAliasGroups.empty()) {
4350 OS.indent(8) << "n/a\n";
4351 return;
4352 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004353
Tobias Grosserbb853c22015-07-25 12:31:03 +00004354 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004355
4356 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004357 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004358 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004359 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004360 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4361 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004362 }
4363 OS << " ]]\n";
4364 }
4365
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004366 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004367 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004368 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004369 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004370 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4371 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004372 }
4373 OS << " ]]\n";
4374 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004375 }
4376}
4377
Michael Krusecd4c9772017-07-21 15:35:53 +00004378void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004379 OS << "Statements {\n";
4380
Michael Krusecd4c9772017-07-21 15:35:53 +00004381 for (const ScopStmt &Stmt : *this) {
4382 OS.indent(4);
4383 Stmt.print(OS, PrintInstructions);
4384 }
Tobias Grosser75805372011-04-29 06:27:02 +00004385
4386 OS.indent(4) << "}\n";
4387}
4388
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004389void Scop::printArrayInfo(raw_ostream &OS) const {
4390 OS << "Arrays {\n";
4391
Tobias Grosserab671442015-05-23 05:58:27 +00004392 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004393 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004394
4395 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004396
4397 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4398
4399 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004400 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004401
4402 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004403}
4404
Michael Krusecd4c9772017-07-21 15:35:53 +00004405void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004406 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004407 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004408 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004409 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004410 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004411 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004412 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004413 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004414 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004415 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004416 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4417 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004418 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004419 }
4420 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004421 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004422 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004423 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004424 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004425}
4426
Michael Kruse5d518462017-07-21 15:54:07 +00004427#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004428LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004429#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004430
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004431isl::ctx Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004432
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004433__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4434 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004435 // First try to use the SCEVAffinator to generate a piecewise defined
4436 // affine function from @p E in the context of @p BB. If that tasks becomes to
4437 // complex the affinator might return a nullptr. In such a case we invalidate
4438 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004439 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004440 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004441 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004442 // TODO: We could use a heuristic and either use:
4443 // SCEVAffinator::takeNonNegativeAssumption
4444 // or
4445 // SCEVAffinator::interpretAsUnsigned
4446 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004447 if (NonNegative)
4448 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004449 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004450 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004451
4452 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004453 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004454 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004455}
4456
Tobias Grosser31df6f32017-08-06 21:42:25 +00004457isl::union_set Scop::getDomains() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004458 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx().get(), 0);
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004459 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004460
Tobias Grosser808cd692015-07-14 09:33:13 +00004461 for (const ScopStmt &Stmt : *this)
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004462 Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004463
Tobias Grosser31df6f32017-08-06 21:42:25 +00004464 return isl::manage(Domain);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004465}
4466
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004467isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004468 PWACtx PWAC = getPwAff(E, BB);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00004469 return PWAC.first;
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004470}
4471
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004472isl::union_map
Tobias Grossere5a35142015-11-12 14:07:09 +00004473Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004474 isl::union_map Accesses = isl::union_map::empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004475
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004476 for (ScopStmt &Stmt : *this) {
4477 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004478 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004479 continue;
4480
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004481 isl::set Domain = Stmt.getDomain();
4482 isl::map AccessDomain = MA->getAccessRelation();
4483 AccessDomain = AccessDomain.intersect_domain(Domain);
4484 Accesses = Accesses.add_map(AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004485 }
4486 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00004487
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004488 return Accesses.coalesce();
Tobias Grossere5a35142015-11-12 14:07:09 +00004489}
4490
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004491isl::union_map Scop::getMustWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004492 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004493}
4494
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004495isl::union_map Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004496 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004497}
4498
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004499isl::union_map Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004500 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004501}
4502
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004503isl::union_map Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004504 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004505}
4506
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004507isl::union_map Scop::getAccesses() {
Tobias Grosser2ac23382015-11-12 14:07:13 +00004508 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4509}
4510
Tobias Grosserfa03cb72017-08-17 22:04:53 +00004511isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
4512 return getAccessesOfType(
4513 [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
4514}
4515
Roman Gareevb3224ad2016-09-14 06:26:09 +00004516// Check whether @p Node is an extension node.
4517//
4518// @return true if @p Node is an extension node.
4519isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4520 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4521 return isl_bool_error;
4522 else
4523 return isl_bool_true;
4524}
4525
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004526bool Scop::containsExtensionNode(isl::schedule Schedule) {
4527 return isl_schedule_foreach_schedule_node_top_down(
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00004528 Schedule.get(), isNotExtNode, nullptr) == isl_stat_error;
Roman Gareevb3224ad2016-09-14 06:26:09 +00004529}
4530
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004531isl::union_map Scop::getSchedule() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004532 auto Tree = getScheduleTree();
4533 if (containsExtensionNode(Tree))
Roman Gareevb3224ad2016-09-14 06:26:09 +00004534 return nullptr;
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004535
4536 return Tree.get_map();
Tobias Grosser808cd692015-07-14 09:33:13 +00004537}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004538
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004539isl::schedule Scop::getScheduleTree() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004540 return Schedule.intersect_domain(getDomains());
Tobias Grosser808cd692015-07-14 09:33:13 +00004541}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004542
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004543void Scop::setSchedule(isl::union_map NewSchedule) {
4544 auto S = isl::schedule::from_domain(getDomains());
4545 Schedule = S.insert_partial_schedule(
4546 isl::multi_union_pw_aff::from_union_map(NewSchedule));
Tobias Grosser808cd692015-07-14 09:33:13 +00004547}
4548
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004549void Scop::setScheduleTree(isl::schedule NewSchedule) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004550 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004551}
4552
Tobias Grosser990cbb42017-08-14 06:49:01 +00004553bool Scop::restrictDomains(isl::union_set Domain) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00004554 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004555 for (ScopStmt &Stmt : *this) {
Tobias Grosser990cbb42017-08-14 06:49:01 +00004556 isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
4557 isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
Tobias Grosser37eb4222014-02-20 21:43:54 +00004558
Tobias Grosser990cbb42017-08-14 06:49:01 +00004559 if (StmtDomain.is_subset(NewStmtDomain))
Tobias Grosser37eb4222014-02-20 21:43:54 +00004560 continue;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004561
4562 Changed = true;
4563
Tobias Grosser990cbb42017-08-14 06:49:01 +00004564 NewStmtDomain = NewStmtDomain.coalesce();
Tobias Grosser37eb4222014-02-20 21:43:54 +00004565
Tobias Grosser990cbb42017-08-14 06:49:01 +00004566 if (NewStmtDomain.is_empty())
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004567 Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
Tobias Grosser990cbb42017-08-14 06:49:01 +00004568 else
4569 Stmt.restrictDomain(isl::set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004570 }
Tobias Grosser37eb4222014-02-20 21:43:54 +00004571 return Changed;
4572}
4573
Tobias Grosser75805372011-04-29 06:27:02 +00004574ScalarEvolution *Scop::getSE() const { return SE; }
4575
Tobias Grosserc80d6972016-09-02 06:33:33 +00004576// Create an isl_multi_union_aff that defines an identity mapping from the
4577// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004578//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004579// # Example:
4580//
4581// Domain: { A[i,j]; B[i,j,k] }
4582// N: 1
4583//
4584// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4585//
4586// @param USet A union set describing the elements for which to generate a
4587// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004588// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004589// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004590static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004591 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004592 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004593 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004594
Tobias Grosser99320862017-05-26 17:22:03 +00004595 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004596
Tobias Grosser99320862017-05-26 17:22:03 +00004597 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4598 int Dim = S.dim(isl::dim::set);
4599 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4600 N, Dim - N);
4601 if (N > 1)
4602 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004603
Tobias Grosser99320862017-05-26 17:22:03 +00004604 Result = Result.add_pw_multi_aff(PMA);
4605 return isl::stat::ok;
4606 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004607
Tobias Grosser99320862017-05-26 17:22:03 +00004608 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004609 (void)Res;
4610
Tobias Grosser99320862017-05-26 17:22:03 +00004611 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004612
Tobias Grosser99320862017-05-26 17:22:03 +00004613 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004614}
4615
Michael Krused6e22082018-01-18 15:15:38 +00004616void Scop::addScopStmt(BasicBlock *BB, StringRef Name, Loop *SurroundingLoop,
4617 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004618 assert(BB && "Unexpected nullptr!");
Michael Krused6e22082018-01-18 15:15:38 +00004619 Stmts.emplace_back(*this, *BB, Name, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004620 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004621 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004622 for (Instruction *Inst : Instructions) {
4623 assert(!InstStmtMap.count(Inst) &&
4624 "Unexpected statement corresponding to the instruction.");
4625 InstStmtMap[Inst] = Stmt;
4626 }
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004627}
4628
Michael Krused6e22082018-01-18 15:15:38 +00004629void Scop::addScopStmt(Region *R, StringRef Name, Loop *SurroundingLoop,
Tobias Grosserbd15d132017-08-31 03:15:56 +00004630 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004631 assert(R && "Unexpected nullptr!");
Michael Krused6e22082018-01-18 15:15:38 +00004632 Stmts.emplace_back(*this, *R, Name, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004633 auto *Stmt = &Stmts.back();
Tobias Grosserbd15d132017-08-31 03:15:56 +00004634
4635 for (Instruction *Inst : Instructions) {
4636 assert(!InstStmtMap.count(Inst) &&
4637 "Unexpected statement corresponding to the instruction.");
4638 InstStmtMap[Inst] = Stmt;
4639 }
4640
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004641 for (BasicBlock *BB : R->blocks()) {
Michael Kruse4dfa7322017-07-18 15:41:49 +00004642 StmtMap[BB].push_back(Stmt);
Tobias Grosserbd15d132017-08-31 03:15:56 +00004643 if (BB == R->getEntry())
4644 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004645 for (Instruction &Inst : *BB) {
4646 assert(!InstStmtMap.count(&Inst) &&
4647 "Unexpected statement corresponding to the instruction.");
4648 InstStmtMap[&Inst] = Stmt;
4649 }
4650 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004651}
4652
Tobias Grosser85048ef2017-08-06 17:24:59 +00004653ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
4654 isl::set Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004655#ifndef NDEBUG
Tobias Grosser85048ef2017-08-06 17:24:59 +00004656 isl::set SourceDomain = SourceRel.domain();
4657 isl::set TargetDomain = TargetRel.domain();
4658 assert(Domain.is_subset(TargetDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004659 "Target access not defined for complete statement domain");
Tobias Grosser85048ef2017-08-06 17:24:59 +00004660 assert(Domain.is_subset(SourceDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004661 "Source access not defined for complete statement domain");
Tobias Grossereba86a12016-11-09 04:24:49 +00004662#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004663 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4664 CopyStmtsNum++;
4665 return &(Stmts.back());
4666}
4667
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004668void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004669 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004670 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004671 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004672 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4673 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004674}
4675
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004676/// To generate a schedule for the elements in a Region we traverse the Region
4677/// in reverse-post-order and add the contained RegionNodes in traversal order
4678/// to the schedule of the loop that is currently at the top of the LoopStack.
4679/// For loop-free codes, this results in a correct sequential ordering.
4680///
4681/// Example:
4682/// bb1(0)
4683/// / \.
4684/// bb2(1) bb3(2)
4685/// \ / \.
4686/// bb4(3) bb5(4)
4687/// \ /
4688/// bb6(5)
4689///
4690/// Including loops requires additional processing. Whenever a loop header is
4691/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4692/// from an empty schedule, we first process all RegionNodes that are within
4693/// this loop and complete the sequential schedule at this loop-level before
4694/// processing about any other nodes. To implement this
4695/// loop-nodes-first-processing, the reverse post-order traversal is
4696/// insufficient. Hence, we additionally check if the traversal yields
4697/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4698/// These region-nodes are then queue and only traverse after the all nodes
4699/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004700void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004701 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004702
4703 ReversePostOrderTraversal<Region *> RTraversal(R);
4704 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4705 std::deque<RegionNode *> DelayList;
4706 bool LastRNWaiting = false;
4707
4708 // Iterate over the region @p R in reverse post-order but queue
4709 // sub-regions/blocks iff they are not part of the last encountered but not
4710 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4711 // that we queued the last sub-region/block from the reverse post-order
4712 // iterator. If it is set we have to explore the next sub-region/block from
4713 // the iterator (if any) to guarantee progress. If it is not set we first try
4714 // the next queued sub-region/blocks.
4715 while (!WorkList.empty() || !DelayList.empty()) {
4716 RegionNode *RN;
4717
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004718 if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004719 RN = WorkList.front();
4720 WorkList.pop_front();
4721 LastRNWaiting = false;
4722 } else {
4723 RN = DelayList.front();
4724 DelayList.pop_front();
4725 }
4726
4727 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004728 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004729 L = OuterScopLoop;
4730
Tobias Grosser151ae322016-04-03 19:36:52 +00004731 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004732 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004733 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004734 LastRNWaiting = true;
4735 DelayList.push_back(RN);
4736 continue;
4737 }
4738 LoopStack.push_back({L, nullptr, 0});
4739 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004740 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004741 }
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004742}
4743
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004744void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004745 if (RN->isSubRegion()) {
4746 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004747 if (!isNonAffineSubRegion(LocalRegion)) {
4748 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004749 return;
4750 }
4751 }
Michael Kruse046dde42015-08-10 13:01:57 +00004752
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004753 assert(LoopStack.rbegin() != LoopStack.rend());
4754 auto LoopData = LoopStack.rbegin();
4755 LoopData->NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004756
Michael Kruse1ce67912017-07-20 17:18:58 +00004757 for (auto *Stmt : getStmtListFor(RN)) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004758 isl::union_set UDomain{Stmt->getDomain()};
4759 auto StmtSchedule = isl::schedule::from_domain(UDomain);
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004760 LoopData->Schedule = combineInSequence(LoopData->Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004761 }
4762
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004763 // Check if we just processed the last node in this loop. If we did, finalize
4764 // the loop by:
4765 //
4766 // - adding new schedule dimensions
4767 // - folding the resulting schedule into the parent loop schedule
4768 // - dropping the loop schedule from the LoopStack.
4769 //
4770 // Then continue to check surrounding loops, which might also have been
4771 // completed by this node.
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004772 size_t Dimension = LoopStack.size();
4773 while (LoopData->L &&
4774 LoopData->NumBlocksProcessed == getNumBlocksInLoop(LoopData->L)) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004775 isl::schedule Schedule = LoopData->Schedule;
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004776 auto NumBlocksProcessed = LoopData->NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004777
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004778 assert(std::next(LoopData) != LoopStack.rend());
4779 ++LoopData;
4780 --Dimension;
Tobias Grosser8362c262016-01-06 15:30:06 +00004781
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004782 if (Schedule) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004783 isl::union_set Domain = Schedule.get_domain();
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004784 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, Dimension);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004785 Schedule = Schedule.insert_partial_schedule(MUPA);
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004786 LoopData->Schedule = combineInSequence(LoopData->Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004787 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004788
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004789 LoopData->NumBlocksProcessed += NumBlocksProcessed;
Tobias Grosser808cd692015-07-14 09:33:13 +00004790 }
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004791 // Now pop all loops processed up there from the LoopStack
4792 LoopStack.erase(LoopStack.begin() + Dimension, LoopStack.end());
Tobias Grosser75805372011-04-29 06:27:02 +00004793}
4794
Michael Kruse6eba4b12017-07-20 17:08:50 +00004795ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
4796 auto StmtMapIt = StmtMap.find(BB);
4797 if (StmtMapIt == StmtMap.end())
4798 return {};
Michael Kruse6eba4b12017-07-20 17:08:50 +00004799 return StmtMapIt->second;
4800}
4801
Michael Krusea230f222018-01-23 23:56:36 +00004802ScopStmt *Scop::getIncomingStmtFor(const Use &U) const {
4803 auto *PHI = cast<PHINode>(U.getUser());
4804 BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
4805
4806 // If the value is a non-synthesizable from the incoming block, use the
4807 // statement that contains it as user statement.
4808 if (auto *IncomingInst = dyn_cast<Instruction>(U.get())) {
4809 if (IncomingInst->getParent() == IncomingBB) {
4810 if (ScopStmt *IncomingStmt = getStmtFor(IncomingInst))
4811 return IncomingStmt;
4812 }
4813 }
4814
4815 // Otherwise, use the epilogue/last statement.
4816 return getLastStmtFor(IncomingBB);
4817}
4818
Michael Kruse6eba4b12017-07-20 17:08:50 +00004819ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
4820 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004821 if (!StmtList.empty())
Michael Kruse6eba4b12017-07-20 17:08:50 +00004822 return StmtList.back();
4823 return nullptr;
4824}
4825
Michael Kruse1ce67912017-07-20 17:18:58 +00004826ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004827 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00004828 return getStmtListFor(RN->getNodeAs<Region>());
4829 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00004830}
4831
Michael Kruse1ce67912017-07-20 17:18:58 +00004832ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
4833 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00004834}
4835
Johannes Doerfert96425c22015-08-30 21:13:53 +00004836int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004837 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00004838 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004839 // outermostLoopInRegion always returns nullptr for top level regions
4840 if (R.isTopLevelRegion()) {
4841 // LoopInfo's depths start at 1, we start at 0
4842 return L->getLoopDepth() - 1;
4843 } else {
4844 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4845 assert(OuterLoop);
4846 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4847 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00004848}
4849
Roman Gareevd7754a12016-07-30 09:25:51 +00004850ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4851 for (auto &SAI : arrays()) {
4852 if (SAI->getName() == BaseName)
4853 return SAI;
4854 }
4855 return nullptr;
4856}
4857
Michael Kruse8b805802017-07-19 17:11:25 +00004858void Scop::addAccessData(MemoryAccess *Access) {
4859 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
4860 assert(SAI && "can only use after access relations have been constructed");
4861
4862 if (Access->isOriginalValueKind() && Access->isRead())
4863 ValueUseAccs[SAI].push_back(Access);
4864 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
4865 PHIIncomingAccs[SAI].push_back(Access);
4866}
4867
4868void Scop::removeAccessData(MemoryAccess *Access) {
Michael Kruse6d7a7892017-09-21 14:23:11 +00004869 if (Access->isOriginalValueKind() && Access->isWrite()) {
4870 ValueDefAccs.erase(Access->getAccessValue());
4871 } else if (Access->isOriginalValueKind() && Access->isRead()) {
Michael Kruse8b805802017-07-19 17:11:25 +00004872 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
Michael Kruse7de61662018-04-09 23:13:01 +00004873 auto NewEnd = std::remove(Uses.begin(), Uses.end(), Access);
4874 Uses.erase(NewEnd, Uses.end());
Michael Kruse6d7a7892017-09-21 14:23:11 +00004875 } else if (Access->isOriginalPHIKind() && Access->isRead()) {
4876 PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
4877 PHIReadAccs.erase(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00004878 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
4879 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
Michael Kruse7de61662018-04-09 23:13:01 +00004880 auto NewEnd = std::remove(Incomings.begin(), Incomings.end(), Access);
4881 Incomings.erase(NewEnd, Incomings.end());
Michael Kruse8b805802017-07-19 17:11:25 +00004882 }
4883}
4884
4885MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
4886 assert(SAI->isValueKind());
4887
4888 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
4889 if (!Val)
4890 return nullptr;
4891
Michael Kruse6d7a7892017-09-21 14:23:11 +00004892 return ValueDefAccs.lookup(Val);
Michael Kruse8b805802017-07-19 17:11:25 +00004893}
4894
4895ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
4896 assert(SAI->isValueKind());
4897 auto It = ValueUseAccs.find(SAI);
4898 if (It == ValueUseAccs.end())
4899 return {};
4900 return It->second;
4901}
4902
4903MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
4904 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4905
4906 if (SAI->isExitPHIKind())
4907 return nullptr;
4908
4909 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
Michael Kruse6d7a7892017-09-21 14:23:11 +00004910 return PHIReadAccs.lookup(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00004911}
4912
4913ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
4914 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4915 auto It = PHIIncomingAccs.find(SAI);
4916 if (It == PHIIncomingAccs.end())
4917 return {};
4918 return It->second;
4919}
4920
Michael Krusea508a4e2017-07-27 14:39:52 +00004921bool Scop::isEscaping(Instruction *Inst) {
4922 assert(contains(Inst) && "The concept of escaping makes only sense for "
4923 "values defined inside the SCoP");
4924
4925 for (Use &Use : Inst->uses()) {
4926 BasicBlock *UserBB = getUseBlock(Use);
4927 if (!contains(UserBB))
4928 return true;
4929
4930 // When the SCoP region exit needs to be simplified, PHIs in the region exit
4931 // move to a new basic block such that its incoming blocks are not in the
4932 // SCoP anymore.
4933 if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
4934 isExit(cast<PHINode>(Use.getUser())->getParent()))
4935 return true;
4936 }
4937 return false;
4938}
4939
Michael Kruse06ed5292017-08-23 13:50:30 +00004940Scop::ScopStatistics Scop::getStatistics() const {
4941 ScopStatistics Result;
4942#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
4943 auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
4944
4945 int NumTotalLoops = LoopStat.NumLoops;
4946 Result.NumBoxedLoops = getBoxedLoops().size();
4947 Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
4948
4949 for (const ScopStmt &Stmt : *this) {
4950 isl::set Domain = Stmt.getDomain().intersect_params(getContext());
4951 bool IsInLoop = Stmt.getNumIterators() >= 1;
4952 for (MemoryAccess *MA : Stmt) {
4953 if (!MA->isWrite())
4954 continue;
4955
4956 if (MA->isLatestValueKind()) {
4957 Result.NumValueWrites += 1;
4958 if (IsInLoop)
4959 Result.NumValueWritesInLoops += 1;
4960 }
4961
4962 if (MA->isLatestAnyPHIKind()) {
4963 Result.NumPHIWrites += 1;
4964 if (IsInLoop)
4965 Result.NumPHIWritesInLoops += 1;
4966 }
4967
4968 isl::set AccSet =
4969 MA->getAccessRelation().intersect_domain(Domain).range();
4970 if (AccSet.is_singleton()) {
4971 Result.NumSingletonWrites += 1;
4972 if (IsInLoop)
4973 Result.NumSingletonWritesInLoops += 1;
4974 }
4975 }
4976 }
4977#endif
4978 return Result;
4979}
4980
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004981raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
4982 scop.print(OS, PollyPrintInstructions);
4983 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00004984}
4985
Johannes Doerfert99191c72016-05-31 09:41:04 +00004986//===----------------------------------------------------------------------===//
4987void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4988 AU.addRequired<LoopInfoWrapperPass>();
4989 AU.addRequired<RegionInfoPass>();
4990 AU.addRequired<DominatorTreeWrapperPass>();
4991 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004992 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004993 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004994 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00004995 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004996 AU.setPreservesAll();
4997}
4998
Michael Kruse06ed5292017-08-23 13:50:30 +00004999void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
5000 Scop::ScopStatistics ScopStats) {
5001 assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
5002
5003 NumScops++;
Tobias Grossercd01a362017-02-17 08:12:36 +00005004 NumLoopsInScop += Stats.NumLoops;
5005 MaxNumLoopsInScop =
5006 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5007
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00005008 if (Stats.MaxDepth == 0)
5009 NumScopsDepthZero++;
5010 else if (Stats.MaxDepth == 1)
Tobias Grossercd01a362017-02-17 08:12:36 +00005011 NumScopsDepthOne++;
5012 else if (Stats.MaxDepth == 2)
5013 NumScopsDepthTwo++;
5014 else if (Stats.MaxDepth == 3)
5015 NumScopsDepthThree++;
5016 else if (Stats.MaxDepth == 4)
5017 NumScopsDepthFour++;
5018 else if (Stats.MaxDepth == 5)
5019 NumScopsDepthFive++;
5020 else
5021 NumScopsDepthLarger++;
Michael Kruse06ed5292017-08-23 13:50:30 +00005022
5023 NumAffineLoops += ScopStats.NumAffineLoops;
5024 NumBoxedLoops += ScopStats.NumBoxedLoops;
5025
5026 NumValueWrites += ScopStats.NumValueWrites;
5027 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
5028 NumPHIWrites += ScopStats.NumPHIWrites;
5029 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
5030 NumSingletonWrites += ScopStats.NumSingletonWrites;
5031 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
Tobias Grossercd01a362017-02-17 08:12:36 +00005032}
5033
Johannes Doerfert99191c72016-05-31 09:41:04 +00005034bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005035 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005036
5037 if (!SD.isMaxRegionInScop(*R))
5038 return false;
5039
5040 Function *F = R->getEntry()->getParent();
5041 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5042 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5043 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5044 auto const &DL = F->getParent()->getDataLayout();
5045 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005046 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005047 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005048
Michael Krusea4f447c2017-08-28 14:07:33 +00005049 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005050 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005051
Michael Kruse06ed5292017-08-23 13:50:30 +00005052#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Tobias Grossercd01a362017-02-17 08:12:36 +00005053 if (S) {
5054 ScopDetection::LoopStats Stats =
5055 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005056 updateLoopCountStatistic(Stats, S->getStatistics());
Tobias Grossercd01a362017-02-17 08:12:36 +00005057 }
Michael Kruse06ed5292017-08-23 13:50:30 +00005058#endif
Tobias Grossercd01a362017-02-17 08:12:36 +00005059
Tobias Grosser75805372011-04-29 06:27:02 +00005060 return false;
5061}
5062
Johannes Doerfert99191c72016-05-31 09:41:04 +00005063void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005064 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005065 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005066 else
5067 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005068}
Tobias Grosser75805372011-04-29 06:27:02 +00005069
Johannes Doerfert99191c72016-05-31 09:41:04 +00005070char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005071
Johannes Doerfert99191c72016-05-31 09:41:04 +00005072Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5073
5074INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005075 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005076 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005077INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005078INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005079INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005080INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005081INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005082INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005083INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005084INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005085 "Polly - Create polyhedral description of Scops", false,
5086 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005087
5088//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005089ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5090 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
Michael Krusea4f447c2017-08-28 14:07:33 +00005091 AssumptionCache &AC, OptimizationRemarkEmitter &ORE)
5092 : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC), ORE(ORE) {
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005093 recompute();
5094}
5095
5096void ScopInfo::recompute() {
5097 RegionToScopMap.clear();
Michael Krusea6d48f52017-06-08 12:06:15 +00005098 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005099 /// function.
5100 for (auto &It : SD) {
5101 Region *R = const_cast<Region *>(It);
5102 if (!SD.isMaxRegionInScop(*R))
5103 continue;
5104
Michael Krusea4f447c2017-08-28 14:07:33 +00005105 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005106 std::unique_ptr<Scop> S = SB.getScop();
5107 if (!S)
5108 continue;
Michael Kruse06ed5292017-08-23 13:50:30 +00005109#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Philip Pfaffeead67db2017-08-02 11:14:41 +00005110 ScopDetection::LoopStats Stats =
5111 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005112 updateLoopCountStatistic(Stats, S->getStatistics());
5113#endif
Philip Pfaffe838e0882017-05-15 12:55:14 +00005114 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5115 assert(Inserted && "Building Scop for the same region twice!");
5116 (void)Inserted;
5117 }
5118}
5119
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005120bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
5121 FunctionAnalysisManager::Invalidator &Inv) {
5122 // Check whether the analysis, all analyses on functions have been preserved
5123 // or anything we're holding references to is being invalidated
5124 auto PAC = PA.getChecker<ScopInfoAnalysis>();
5125 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
5126 Inv.invalidate<ScopAnalysis>(F, PA) ||
5127 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
5128 Inv.invalidate<LoopAnalysis>(F, PA) ||
5129 Inv.invalidate<AAManager>(F, PA) ||
5130 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
5131 Inv.invalidate<AssumptionAnalysis>(F, PA);
5132}
5133
Philip Pfaffe838e0882017-05-15 12:55:14 +00005134AnalysisKey ScopInfoAnalysis::Key;
5135
5136ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5137 FunctionAnalysisManager &FAM) {
5138 auto &SD = FAM.getResult<ScopAnalysis>(F);
5139 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5140 auto &LI = FAM.getResult<LoopAnalysis>(F);
5141 auto &AA = FAM.getResult<AAManager>(F);
5142 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5143 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5144 auto &DL = F.getParent()->getDataLayout();
Michael Krusea4f447c2017-08-28 14:07:33 +00005145 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5146 return {DL, SD, SE, LI, AA, DT, AC, ORE};
Philip Pfaffe838e0882017-05-15 12:55:14 +00005147}
5148
5149PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5150 FunctionAnalysisManager &FAM) {
5151 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
Philip Pfaffe96d21432017-08-04 11:28:51 +00005152 // Since the legacy PM processes Scops in bottom up, we print them in reverse
5153 // order here to keep the output persistent
5154 for (auto &It : reverse(SI)) {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005155 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005156 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005157 else
5158 Stream << "Invalid Scop!\n";
5159 }
5160 return PreservedAnalyses::all();
5161}
5162
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005163void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5164 AU.addRequired<LoopInfoWrapperPass>();
5165 AU.addRequired<RegionInfoPass>();
5166 AU.addRequired<DominatorTreeWrapperPass>();
5167 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005168 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005169 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005170 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00005171 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005172 AU.setPreservesAll();
5173}
5174
5175bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005176 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005177 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5178 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5179 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5180 auto const &DL = F.getParent()->getDataLayout();
5181 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005182 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005183 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005184
Michael Krusea4f447c2017-08-28 14:07:33 +00005185 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC, ORE});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005186 return false;
5187}
5188
5189void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005190 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005191 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005192 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005193 else
5194 OS << "Invalid Scop!\n";
5195 }
5196}
5197
5198char ScopInfoWrapperPass::ID = 0;
5199
5200Pass *polly::createScopInfoWrapperPassPass() {
5201 return new ScopInfoWrapperPass();
5202}
5203
5204INITIALIZE_PASS_BEGIN(
5205 ScopInfoWrapperPass, "polly-function-scops",
5206 "Polly - Create polyhedral description of all Scops of a function", false,
5207 false);
5208INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005209INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005210INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5211INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5212INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005213INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005214INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5215INITIALIZE_PASS_END(
5216 ScopInfoWrapperPass, "polly-function-scops",
5217 "Polly - Create polyhedral description of all Scops of a function", false,
5218 false)